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 |
|---|---|---|---|---|---|
Instead of casting it here twice (here and below), let's cast it in the `createFeedResponseFromGroupingTable` itself and return `FeedResponse<T>` What if it is null the very first time ? Casting will throw a NPE. | public Flux<FeedResponse<T>> drainAsync(int maxPageSize) {
return this.component.drainAsync(maxPageSize)
.collectList()
.map(superList -> {
double requestCharge = 0;
HashMap<String, String> headers = new HashMap<>();
List<Document> documentList = new ArrayList<>();
/* Do groupBy stuff here */
for (FeedResponse<T> page : superList) {
List<Document> results = (List<Document>) page.getResults();
documentList.addAll(results);
requestCharge += page.getRequestCharge();
}
this.aggregateGroupings(documentList);
return (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, requestCharge);
}).expand(tFeedResponse -> {
FeedResponse<T> response = (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, 0);
if (response == null) {
return Mono.empty();
}
return Mono.just(response);
});
} | return (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, requestCharge); | Drain the groupings fully from all continuation and all partitions
for (FeedResponse<T> page : superList) {
List<Document> results = (List<Document>) page.getResults();
documentList.addAll(results);
requestCharge += page.getRequestCharge();
} | class GroupByDocumentQueryExecutionContext<T extends Resource> implements
IDocumentQueryExecutionComponent<T> {
public static final String CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY = "Continuation token is not supported " +
"for queries with GROUP BY." +
"Do not use continuation token" +
" or remove the GROUP BY " +
"from the query.";
private final IDocumentQueryExecutionComponent<T> component;
private final GroupingTable groupingTable;
GroupByDocumentQueryExecutionContext(
IDocumentQueryExecutionComponent<T> component,
GroupingTable groupingTable) {
this.component = component;
this.groupingTable = groupingTable;
}
public static <T extends Resource> Flux<IDocumentQueryExecutionComponent<T>> createAsync(
BiFunction<String, PipelinedDocumentQueryParams<T>, Flux<IDocumentQueryExecutionComponent<T>>> createSourceComponentFunction,
String continuationToken,
Map<String, AggregateOperator> groupByAliasToAggregateType,
List<String> orderedAliases,
boolean hasSelectValue,
PipelinedDocumentQueryParams<T> documentQueryParams) {
if (continuationToken != null) {
CosmosException dce = new BadRequestException(CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY);
return Flux.error(dce);
}
if (groupByAliasToAggregateType == null) {
throw new IllegalArgumentException("groupByAliasToAggregateType should not be null");
}
if (orderedAliases == null) {
throw new IllegalArgumentException("orderedAliases should not be null");
}
GroupingTable table = new GroupingTable(groupByAliasToAggregateType, orderedAliases, hasSelectValue);
return createSourceComponentFunction.apply(null, documentQueryParams)
.map(component -> new GroupByDocumentQueryExecutionContext<>(component,
table));
}
@SuppressWarnings("unchecked")
@Override
public Flux<FeedResponse<T>> drainAsync(int maxPageSize) {
return this.component.drainAsync(maxPageSize)
.collectList()
.map(superList -> {
double requestCharge = 0;
HashMap<String, String> headers = new HashMap<>();
List<Document> documentList = new ArrayList<>();
/* Do groupBy stuff here */
this.aggregateGroupings(documentList);
return (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, requestCharge);
}).expand(tFeedResponse -> {
FeedResponse<T> response = (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, 0);
if (response == null) {
return Mono.empty();
}
return Mono.just(response);
});
}
private FeedResponse<Document> createFeedResponseFromGroupingTable(int pageSize, double requestCharge) {
if (this.groupingTable != null) {
List<Document> groupByResults = groupingTable.drain(pageSize);
if (groupByResults.size() == 0) {
return null;
}
HashMap<String, String> headers = new HashMap<>();
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
FeedResponse<Document> frp = BridgeInternal.createFeedResponse(groupByResults, headers);
return frp;
}
return null;
}
private void aggregateGroupings(List<Document> superList) {
for (Document d : superList) {
RewrittenGroupByProjection rewrittenGroupByProjection =
new RewrittenGroupByProjection(ModelBridgeInternal.getPropertyBagFromJsonSerializable(d));
this.groupingTable.addPayLoad(rewrittenGroupByProjection);
}
}
IDocumentQueryExecutionComponent<T> getComponent() {
return this.component;
}
/**
* When a group by query gets rewritten the projection looks like:
* <p>
* SELECT
* [{"item": c.age}, {"item": c.name}] AS groupByItems,
* {"age": c.age, "name": c.name} AS payload
* <p>
* This class just lets us easily access the "groupByItems" and "payload" property.
*/
public class RewrittenGroupByProjection extends JsonSerializable {
private static final String GROUP_BY_ITEMS_PROPERTY_NAME = "groupByItems";
private static final String PAYLOAD_PROPERTY_NAME = "payload";
private List<Document> groupByItems;
public RewrittenGroupByProjection(ObjectNode objectNode) {
super(objectNode);
if (objectNode == null) {
throw new IllegalArgumentException("objectNode can not be null");
}
}
/**
* Getter for property 'groupByItems'.
*
* @return Value for property 'groupByItems'.
*/
public List<Document> getGroupByItems() {
groupByItems = this.getList(GROUP_BY_ITEMS_PROPERTY_NAME, Document.class);
if (groupByItems == null) {
throw new IllegalStateException("Underlying object does not have an 'groupByItems' field.");
}
return groupByItems;
}
/**
* Getter for property 'payload'.
*
* @return Value for property 'payload'.
*/
public Document getPayload() {
if (!this.has(PAYLOAD_PROPERTY_NAME)) {
throw new IllegalStateException("Underlying object does not have an 'payload' field.");
}
return new Document((ObjectNode) this.get(PAYLOAD_PROPERTY_NAME));
}
}
} | class GroupByDocumentQueryExecutionContext<T extends Resource> implements
IDocumentQueryExecutionComponent<T> {
public static final String CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY = "Continuation token is not supported " +
"for queries with GROUP BY." +
"Do not use continuation token" +
" or remove the GROUP BY " +
"from the query.";
private final IDocumentQueryExecutionComponent<T> component;
private final GroupingTable groupingTable;
GroupByDocumentQueryExecutionContext(
IDocumentQueryExecutionComponent<T> component,
GroupingTable groupingTable) {
this.component = component;
this.groupingTable = groupingTable;
}
public static <T extends Resource> Flux<IDocumentQueryExecutionComponent<T>> createAsync(
BiFunction<String, PipelinedDocumentQueryParams<T>, Flux<IDocumentQueryExecutionComponent<T>>> createSourceComponentFunction,
String continuationToken,
Map<String, AggregateOperator> groupByAliasToAggregateType,
List<String> orderedAliases,
boolean hasSelectValue,
PipelinedDocumentQueryParams<T> documentQueryParams) {
if (continuationToken != null) {
CosmosException dce = new BadRequestException(CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY);
return Flux.error(dce);
}
if (groupByAliasToAggregateType == null) {
throw new IllegalArgumentException("groupByAliasToAggregateType should not be null");
}
if (orderedAliases == null) {
throw new IllegalArgumentException("orderedAliases should not be null");
}
GroupingTable table = new GroupingTable(groupByAliasToAggregateType, orderedAliases, hasSelectValue);
return createSourceComponentFunction.apply(null, documentQueryParams)
.map(component -> new GroupByDocumentQueryExecutionContext<>(component,
table));
}
@SuppressWarnings("unchecked")
@Override
public Flux<FeedResponse<T>> drainAsync(int maxPageSize) {
return this.component.drainAsync(maxPageSize)
.collectList()
.map(superList -> {
double requestCharge = 0;
HashMap<String, String> headers = new HashMap<>();
List<Document> documentList = new ArrayList<>();
/* Do groupBy stuff here */
this.aggregateGroupings(documentList);
return createFeedResponseFromGroupingTable(maxPageSize, requestCharge);
}).expand(tFeedResponse -> {
FeedResponse<T> response = createFeedResponseFromGroupingTable(maxPageSize, 0);
if (response == null) {
return Mono.empty();
}
return Mono.just(response);
});
}
@SuppressWarnings("unchecked")
private FeedResponse<T> createFeedResponseFromGroupingTable(int pageSize, double requestCharge) {
if (this.groupingTable != null) {
List<Document> groupByResults = groupingTable.drain(pageSize);
if (groupByResults.size() == 0) {
return null;
}
HashMap<String, String> headers = new HashMap<>();
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
FeedResponse<Document> frp = BridgeInternal.createFeedResponse(groupByResults, headers);
return (FeedResponse<T>) frp;
}
return null;
}
private void aggregateGroupings(List<Document> superList) {
for (Document d : superList) {
RewrittenGroupByProjection rewrittenGroupByProjection =
new RewrittenGroupByProjection(ModelBridgeInternal.getPropertyBagFromJsonSerializable(d));
this.groupingTable.addPayLoad(rewrittenGroupByProjection);
}
}
IDocumentQueryExecutionComponent<T> getComponent() {
return this.component;
}
/**
* When a group by query gets rewritten the projection looks like:
* <p>
* SELECT
* [{"item": c.age}, {"item": c.name}] AS groupByItems,
* {"age": c.age, "name": c.name} AS payload
* <p>
* This class just lets us easily access the "groupByItems" and "payload" property.
*/
public class RewrittenGroupByProjection extends JsonSerializable {
private static final String GROUP_BY_ITEMS_PROPERTY_NAME = "groupByItems";
private static final String PAYLOAD_PROPERTY_NAME = "payload";
private List<Document> groupByItems;
public RewrittenGroupByProjection(ObjectNode objectNode) {
super(objectNode);
if (objectNode == null) {
throw new IllegalArgumentException("objectNode can not be null");
}
}
/**
* Getter for property 'groupByItems'.
*
* @return Value for property 'groupByItems'.
*/
public List<Document> getGroupByItems() {
groupByItems = this.getList(GROUP_BY_ITEMS_PROPERTY_NAME, Document.class);
if (groupByItems == null) {
throw new IllegalStateException("Underlying object does not have an 'groupByItems' field.");
}
return groupByItems;
}
/**
* Getter for property 'payload'.
*
* @return Value for property 'payload'.
*/
public Document getPayload() {
if (!this.has(PAYLOAD_PROPERTY_NAME)) {
throw new IllegalStateException("Underlying object does not have an 'payload' field.");
}
return new Document((ObjectNode) this.get(PAYLOAD_PROPERTY_NAME));
}
}
} |
Please add some comments to expand (explaining how it will be called second time onwards) | public Flux<FeedResponse<T>> drainAsync(int maxPageSize) {
return this.component.drainAsync(maxPageSize)
.collectList()
.map(superList -> {
double requestCharge = 0;
HashMap<String, String> headers = new HashMap<>();
List<Document> documentList = new ArrayList<>();
/* Do groupBy stuff here */
for (FeedResponse<T> page : superList) {
List<Document> results = (List<Document>) page.getResults();
documentList.addAll(results);
requestCharge += page.getRequestCharge();
}
this.aggregateGroupings(documentList);
return (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, requestCharge);
}).expand(tFeedResponse -> {
FeedResponse<T> response = (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, 0);
if (response == null) {
return Mono.empty();
}
return Mono.just(response);
});
} | Drain the groupings fully from all continuation and all partitions
for (FeedResponse<T> page : superList) {
List<Document> results = (List<Document>) page.getResults();
documentList.addAll(results);
requestCharge += page.getRequestCharge();
} | class GroupByDocumentQueryExecutionContext<T extends Resource> implements
IDocumentQueryExecutionComponent<T> {
public static final String CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY = "Continuation token is not supported " +
"for queries with GROUP BY." +
"Do not use continuation token" +
" or remove the GROUP BY " +
"from the query.";
private final IDocumentQueryExecutionComponent<T> component;
private final GroupingTable groupingTable;
GroupByDocumentQueryExecutionContext(
IDocumentQueryExecutionComponent<T> component,
GroupingTable groupingTable) {
this.component = component;
this.groupingTable = groupingTable;
}
public static <T extends Resource> Flux<IDocumentQueryExecutionComponent<T>> createAsync(
BiFunction<String, PipelinedDocumentQueryParams<T>, Flux<IDocumentQueryExecutionComponent<T>>> createSourceComponentFunction,
String continuationToken,
Map<String, AggregateOperator> groupByAliasToAggregateType,
List<String> orderedAliases,
boolean hasSelectValue,
PipelinedDocumentQueryParams<T> documentQueryParams) {
if (continuationToken != null) {
CosmosException dce = new BadRequestException(CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY);
return Flux.error(dce);
}
if (groupByAliasToAggregateType == null) {
throw new IllegalArgumentException("groupByAliasToAggregateType should not be null");
}
if (orderedAliases == null) {
throw new IllegalArgumentException("orderedAliases should not be null");
}
GroupingTable table = new GroupingTable(groupByAliasToAggregateType, orderedAliases, hasSelectValue);
return createSourceComponentFunction.apply(null, documentQueryParams)
.map(component -> new GroupByDocumentQueryExecutionContext<>(component,
table));
}
@SuppressWarnings("unchecked")
@Override
public Flux<FeedResponse<T>> drainAsync(int maxPageSize) {
return this.component.drainAsync(maxPageSize)
.collectList()
.map(superList -> {
double requestCharge = 0;
HashMap<String, String> headers = new HashMap<>();
List<Document> documentList = new ArrayList<>();
/* Do groupBy stuff here */
this.aggregateGroupings(documentList);
return (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, requestCharge);
}).expand(tFeedResponse -> {
FeedResponse<T> response = (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, 0);
if (response == null) {
return Mono.empty();
}
return Mono.just(response);
});
}
private FeedResponse<Document> createFeedResponseFromGroupingTable(int pageSize, double requestCharge) {
if (this.groupingTable != null) {
List<Document> groupByResults = groupingTable.drain(pageSize);
if (groupByResults.size() == 0) {
return null;
}
HashMap<String, String> headers = new HashMap<>();
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
FeedResponse<Document> frp = BridgeInternal.createFeedResponse(groupByResults, headers);
return frp;
}
return null;
}
private void aggregateGroupings(List<Document> superList) {
for (Document d : superList) {
RewrittenGroupByProjection rewrittenGroupByProjection =
new RewrittenGroupByProjection(ModelBridgeInternal.getPropertyBagFromJsonSerializable(d));
this.groupingTable.addPayLoad(rewrittenGroupByProjection);
}
}
IDocumentQueryExecutionComponent<T> getComponent() {
return this.component;
}
/**
* When a group by query gets rewritten the projection looks like:
* <p>
* SELECT
* [{"item": c.age}, {"item": c.name}] AS groupByItems,
* {"age": c.age, "name": c.name} AS payload
* <p>
* This class just lets us easily access the "groupByItems" and "payload" property.
*/
public class RewrittenGroupByProjection extends JsonSerializable {
private static final String GROUP_BY_ITEMS_PROPERTY_NAME = "groupByItems";
private static final String PAYLOAD_PROPERTY_NAME = "payload";
private List<Document> groupByItems;
public RewrittenGroupByProjection(ObjectNode objectNode) {
super(objectNode);
if (objectNode == null) {
throw new IllegalArgumentException("objectNode can not be null");
}
}
/**
* Getter for property 'groupByItems'.
*
* @return Value for property 'groupByItems'.
*/
public List<Document> getGroupByItems() {
groupByItems = this.getList(GROUP_BY_ITEMS_PROPERTY_NAME, Document.class);
if (groupByItems == null) {
throw new IllegalStateException("Underlying object does not have an 'groupByItems' field.");
}
return groupByItems;
}
/**
* Getter for property 'payload'.
*
* @return Value for property 'payload'.
*/
public Document getPayload() {
if (!this.has(PAYLOAD_PROPERTY_NAME)) {
throw new IllegalStateException("Underlying object does not have an 'payload' field.");
}
return new Document((ObjectNode) this.get(PAYLOAD_PROPERTY_NAME));
}
}
} | class GroupByDocumentQueryExecutionContext<T extends Resource> implements
IDocumentQueryExecutionComponent<T> {
public static final String CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY = "Continuation token is not supported " +
"for queries with GROUP BY." +
"Do not use continuation token" +
" or remove the GROUP BY " +
"from the query.";
private final IDocumentQueryExecutionComponent<T> component;
private final GroupingTable groupingTable;
GroupByDocumentQueryExecutionContext(
IDocumentQueryExecutionComponent<T> component,
GroupingTable groupingTable) {
this.component = component;
this.groupingTable = groupingTable;
}
public static <T extends Resource> Flux<IDocumentQueryExecutionComponent<T>> createAsync(
BiFunction<String, PipelinedDocumentQueryParams<T>, Flux<IDocumentQueryExecutionComponent<T>>> createSourceComponentFunction,
String continuationToken,
Map<String, AggregateOperator> groupByAliasToAggregateType,
List<String> orderedAliases,
boolean hasSelectValue,
PipelinedDocumentQueryParams<T> documentQueryParams) {
if (continuationToken != null) {
CosmosException dce = new BadRequestException(CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY);
return Flux.error(dce);
}
if (groupByAliasToAggregateType == null) {
throw new IllegalArgumentException("groupByAliasToAggregateType should not be null");
}
if (orderedAliases == null) {
throw new IllegalArgumentException("orderedAliases should not be null");
}
GroupingTable table = new GroupingTable(groupByAliasToAggregateType, orderedAliases, hasSelectValue);
return createSourceComponentFunction.apply(null, documentQueryParams)
.map(component -> new GroupByDocumentQueryExecutionContext<>(component,
table));
}
@SuppressWarnings("unchecked")
@Override
public Flux<FeedResponse<T>> drainAsync(int maxPageSize) {
return this.component.drainAsync(maxPageSize)
.collectList()
.map(superList -> {
double requestCharge = 0;
HashMap<String, String> headers = new HashMap<>();
List<Document> documentList = new ArrayList<>();
/* Do groupBy stuff here */
this.aggregateGroupings(documentList);
return createFeedResponseFromGroupingTable(maxPageSize, requestCharge);
}).expand(tFeedResponse -> {
FeedResponse<T> response = createFeedResponseFromGroupingTable(maxPageSize, 0);
if (response == null) {
return Mono.empty();
}
return Mono.just(response);
});
}
@SuppressWarnings("unchecked")
private FeedResponse<T> createFeedResponseFromGroupingTable(int pageSize, double requestCharge) {
if (this.groupingTable != null) {
List<Document> groupByResults = groupingTable.drain(pageSize);
if (groupByResults.size() == 0) {
return null;
}
HashMap<String, String> headers = new HashMap<>();
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
FeedResponse<Document> frp = BridgeInternal.createFeedResponse(groupByResults, headers);
return (FeedResponse<T>) frp;
}
return null;
}
private void aggregateGroupings(List<Document> superList) {
for (Document d : superList) {
RewrittenGroupByProjection rewrittenGroupByProjection =
new RewrittenGroupByProjection(ModelBridgeInternal.getPropertyBagFromJsonSerializable(d));
this.groupingTable.addPayLoad(rewrittenGroupByProjection);
}
}
IDocumentQueryExecutionComponent<T> getComponent() {
return this.component;
}
/**
* When a group by query gets rewritten the projection looks like:
* <p>
* SELECT
* [{"item": c.age}, {"item": c.name}] AS groupByItems,
* {"age": c.age, "name": c.name} AS payload
* <p>
* This class just lets us easily access the "groupByItems" and "payload" property.
*/
public class RewrittenGroupByProjection extends JsonSerializable {
private static final String GROUP_BY_ITEMS_PROPERTY_NAME = "groupByItems";
private static final String PAYLOAD_PROPERTY_NAME = "payload";
private List<Document> groupByItems;
public RewrittenGroupByProjection(ObjectNode objectNode) {
super(objectNode);
if (objectNode == null) {
throw new IllegalArgumentException("objectNode can not be null");
}
}
/**
* Getter for property 'groupByItems'.
*
* @return Value for property 'groupByItems'.
*/
public List<Document> getGroupByItems() {
groupByItems = this.getList(GROUP_BY_ITEMS_PROPERTY_NAME, Document.class);
if (groupByItems == null) {
throw new IllegalStateException("Underlying object does not have an 'groupByItems' field.");
}
return groupByItems;
}
/**
* Getter for property 'payload'.
*
* @return Value for property 'payload'.
*/
public Document getPayload() {
if (!this.has(PAYLOAD_PROPERTY_NAME)) {
throw new IllegalStateException("Underlying object does not have an 'payload' field.");
}
return new Document((ObjectNode) this.get(PAYLOAD_PROPERTY_NAME));
}
}
} | |
You can do the same thing here, what you did down below, return an empty Mono to avoid NPE. | public Flux<FeedResponse<T>> drainAsync(int maxPageSize) {
return this.component.drainAsync(maxPageSize)
.collectList()
.map(superList -> {
double requestCharge = 0;
HashMap<String, String> headers = new HashMap<>();
List<Document> documentList = new ArrayList<>();
/* Do groupBy stuff here */
for (FeedResponse<T> page : superList) {
List<Document> results = (List<Document>) page.getResults();
documentList.addAll(results);
requestCharge += page.getRequestCharge();
}
this.aggregateGroupings(documentList);
return (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, requestCharge);
}).expand(tFeedResponse -> {
FeedResponse<T> response = (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, 0);
if (response == null) {
return Mono.empty();
}
return Mono.just(response);
});
} | return (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, requestCharge); | Drain the groupings fully from all continuation and all partitions
for (FeedResponse<T> page : superList) {
List<Document> results = (List<Document>) page.getResults();
documentList.addAll(results);
requestCharge += page.getRequestCharge();
} | class GroupByDocumentQueryExecutionContext<T extends Resource> implements
IDocumentQueryExecutionComponent<T> {
public static final String CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY = "Continuation token is not supported " +
"for queries with GROUP BY." +
"Do not use continuation token" +
" or remove the GROUP BY " +
"from the query.";
private final IDocumentQueryExecutionComponent<T> component;
private final GroupingTable groupingTable;
GroupByDocumentQueryExecutionContext(
IDocumentQueryExecutionComponent<T> component,
GroupingTable groupingTable) {
this.component = component;
this.groupingTable = groupingTable;
}
public static <T extends Resource> Flux<IDocumentQueryExecutionComponent<T>> createAsync(
BiFunction<String, PipelinedDocumentQueryParams<T>, Flux<IDocumentQueryExecutionComponent<T>>> createSourceComponentFunction,
String continuationToken,
Map<String, AggregateOperator> groupByAliasToAggregateType,
List<String> orderedAliases,
boolean hasSelectValue,
PipelinedDocumentQueryParams<T> documentQueryParams) {
if (continuationToken != null) {
CosmosException dce = new BadRequestException(CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY);
return Flux.error(dce);
}
if (groupByAliasToAggregateType == null) {
throw new IllegalArgumentException("groupByAliasToAggregateType should not be null");
}
if (orderedAliases == null) {
throw new IllegalArgumentException("orderedAliases should not be null");
}
GroupingTable table = new GroupingTable(groupByAliasToAggregateType, orderedAliases, hasSelectValue);
return createSourceComponentFunction.apply(null, documentQueryParams)
.map(component -> new GroupByDocumentQueryExecutionContext<>(component,
table));
}
@SuppressWarnings("unchecked")
@Override
public Flux<FeedResponse<T>> drainAsync(int maxPageSize) {
return this.component.drainAsync(maxPageSize)
.collectList()
.map(superList -> {
double requestCharge = 0;
HashMap<String, String> headers = new HashMap<>();
List<Document> documentList = new ArrayList<>();
/* Do groupBy stuff here */
this.aggregateGroupings(documentList);
return (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, requestCharge);
}).expand(tFeedResponse -> {
FeedResponse<T> response = (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, 0);
if (response == null) {
return Mono.empty();
}
return Mono.just(response);
});
}
private FeedResponse<Document> createFeedResponseFromGroupingTable(int pageSize, double requestCharge) {
if (this.groupingTable != null) {
List<Document> groupByResults = groupingTable.drain(pageSize);
if (groupByResults.size() == 0) {
return null;
}
HashMap<String, String> headers = new HashMap<>();
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
FeedResponse<Document> frp = BridgeInternal.createFeedResponse(groupByResults, headers);
return frp;
}
return null;
}
private void aggregateGroupings(List<Document> superList) {
for (Document d : superList) {
RewrittenGroupByProjection rewrittenGroupByProjection =
new RewrittenGroupByProjection(ModelBridgeInternal.getPropertyBagFromJsonSerializable(d));
this.groupingTable.addPayLoad(rewrittenGroupByProjection);
}
}
IDocumentQueryExecutionComponent<T> getComponent() {
return this.component;
}
/**
* When a group by query gets rewritten the projection looks like:
* <p>
* SELECT
* [{"item": c.age}, {"item": c.name}] AS groupByItems,
* {"age": c.age, "name": c.name} AS payload
* <p>
* This class just lets us easily access the "groupByItems" and "payload" property.
*/
public class RewrittenGroupByProjection extends JsonSerializable {
private static final String GROUP_BY_ITEMS_PROPERTY_NAME = "groupByItems";
private static final String PAYLOAD_PROPERTY_NAME = "payload";
private List<Document> groupByItems;
public RewrittenGroupByProjection(ObjectNode objectNode) {
super(objectNode);
if (objectNode == null) {
throw new IllegalArgumentException("objectNode can not be null");
}
}
/**
* Getter for property 'groupByItems'.
*
* @return Value for property 'groupByItems'.
*/
public List<Document> getGroupByItems() {
groupByItems = this.getList(GROUP_BY_ITEMS_PROPERTY_NAME, Document.class);
if (groupByItems == null) {
throw new IllegalStateException("Underlying object does not have an 'groupByItems' field.");
}
return groupByItems;
}
/**
* Getter for property 'payload'.
*
* @return Value for property 'payload'.
*/
public Document getPayload() {
if (!this.has(PAYLOAD_PROPERTY_NAME)) {
throw new IllegalStateException("Underlying object does not have an 'payload' field.");
}
return new Document((ObjectNode) this.get(PAYLOAD_PROPERTY_NAME));
}
}
} | class GroupByDocumentQueryExecutionContext<T extends Resource> implements
IDocumentQueryExecutionComponent<T> {
public static final String CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY = "Continuation token is not supported " +
"for queries with GROUP BY." +
"Do not use continuation token" +
" or remove the GROUP BY " +
"from the query.";
private final IDocumentQueryExecutionComponent<T> component;
private final GroupingTable groupingTable;
GroupByDocumentQueryExecutionContext(
IDocumentQueryExecutionComponent<T> component,
GroupingTable groupingTable) {
this.component = component;
this.groupingTable = groupingTable;
}
public static <T extends Resource> Flux<IDocumentQueryExecutionComponent<T>> createAsync(
BiFunction<String, PipelinedDocumentQueryParams<T>, Flux<IDocumentQueryExecutionComponent<T>>> createSourceComponentFunction,
String continuationToken,
Map<String, AggregateOperator> groupByAliasToAggregateType,
List<String> orderedAliases,
boolean hasSelectValue,
PipelinedDocumentQueryParams<T> documentQueryParams) {
if (continuationToken != null) {
CosmosException dce = new BadRequestException(CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY);
return Flux.error(dce);
}
if (groupByAliasToAggregateType == null) {
throw new IllegalArgumentException("groupByAliasToAggregateType should not be null");
}
if (orderedAliases == null) {
throw new IllegalArgumentException("orderedAliases should not be null");
}
GroupingTable table = new GroupingTable(groupByAliasToAggregateType, orderedAliases, hasSelectValue);
return createSourceComponentFunction.apply(null, documentQueryParams)
.map(component -> new GroupByDocumentQueryExecutionContext<>(component,
table));
}
@SuppressWarnings("unchecked")
@Override
public Flux<FeedResponse<T>> drainAsync(int maxPageSize) {
return this.component.drainAsync(maxPageSize)
.collectList()
.map(superList -> {
double requestCharge = 0;
HashMap<String, String> headers = new HashMap<>();
List<Document> documentList = new ArrayList<>();
/* Do groupBy stuff here */
this.aggregateGroupings(documentList);
return createFeedResponseFromGroupingTable(maxPageSize, requestCharge);
}).expand(tFeedResponse -> {
FeedResponse<T> response = createFeedResponseFromGroupingTable(maxPageSize, 0);
if (response == null) {
return Mono.empty();
}
return Mono.just(response);
});
}
@SuppressWarnings("unchecked")
private FeedResponse<T> createFeedResponseFromGroupingTable(int pageSize, double requestCharge) {
if (this.groupingTable != null) {
List<Document> groupByResults = groupingTable.drain(pageSize);
if (groupByResults.size() == 0) {
return null;
}
HashMap<String, String> headers = new HashMap<>();
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
FeedResponse<Document> frp = BridgeInternal.createFeedResponse(groupByResults, headers);
return (FeedResponse<T>) frp;
}
return null;
}
private void aggregateGroupings(List<Document> superList) {
for (Document d : superList) {
RewrittenGroupByProjection rewrittenGroupByProjection =
new RewrittenGroupByProjection(ModelBridgeInternal.getPropertyBagFromJsonSerializable(d));
this.groupingTable.addPayLoad(rewrittenGroupByProjection);
}
}
IDocumentQueryExecutionComponent<T> getComponent() {
return this.component;
}
/**
* When a group by query gets rewritten the projection looks like:
* <p>
* SELECT
* [{"item": c.age}, {"item": c.name}] AS groupByItems,
* {"age": c.age, "name": c.name} AS payload
* <p>
* This class just lets us easily access the "groupByItems" and "payload" property.
*/
public class RewrittenGroupByProjection extends JsonSerializable {
private static final String GROUP_BY_ITEMS_PROPERTY_NAME = "groupByItems";
private static final String PAYLOAD_PROPERTY_NAME = "payload";
private List<Document> groupByItems;
public RewrittenGroupByProjection(ObjectNode objectNode) {
super(objectNode);
if (objectNode == null) {
throw new IllegalArgumentException("objectNode can not be null");
}
}
/**
* Getter for property 'groupByItems'.
*
* @return Value for property 'groupByItems'.
*/
public List<Document> getGroupByItems() {
groupByItems = this.getList(GROUP_BY_ITEMS_PROPERTY_NAME, Document.class);
if (groupByItems == null) {
throw new IllegalStateException("Underlying object does not have an 'groupByItems' field.");
}
return groupByItems;
}
/**
* Getter for property 'payload'.
*
* @return Value for property 'payload'.
*/
public Document getPayload() {
if (!this.has(PAYLOAD_PROPERTY_NAME)) {
throw new IllegalStateException("Underlying object does not have an 'payload' field.");
}
return new Document((ObjectNode) this.get(PAYLOAD_PROPERTY_NAME));
}
}
} |
Updated | public Flux<FeedResponse<T>> drainAsync(int maxPageSize) {
return this.component.drainAsync(maxPageSize)
.collectList()
.map(superList -> {
double requestCharge = 0;
HashMap<String, String> headers = new HashMap<>();
List<Document> documentList = new ArrayList<>();
/* Do groupBy stuff here */
for (FeedResponse<T> page : superList) {
List<Document> results = (List<Document>) page.getResults();
documentList.addAll(results);
requestCharge += page.getRequestCharge();
}
this.aggregateGroupings(documentList);
return (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, requestCharge);
}).expand(tFeedResponse -> {
FeedResponse<T> response = (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, 0);
if (response == null) {
return Mono.empty();
}
return Mono.just(response);
});
} | Drain the groupings fully from all continuation and all partitions
for (FeedResponse<T> page : superList) {
List<Document> results = (List<Document>) page.getResults();
documentList.addAll(results);
requestCharge += page.getRequestCharge();
} | class GroupByDocumentQueryExecutionContext<T extends Resource> implements
IDocumentQueryExecutionComponent<T> {
public static final String CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY = "Continuation token is not supported " +
"for queries with GROUP BY." +
"Do not use continuation token" +
" or remove the GROUP BY " +
"from the query.";
private final IDocumentQueryExecutionComponent<T> component;
private final GroupingTable groupingTable;
GroupByDocumentQueryExecutionContext(
IDocumentQueryExecutionComponent<T> component,
GroupingTable groupingTable) {
this.component = component;
this.groupingTable = groupingTable;
}
public static <T extends Resource> Flux<IDocumentQueryExecutionComponent<T>> createAsync(
BiFunction<String, PipelinedDocumentQueryParams<T>, Flux<IDocumentQueryExecutionComponent<T>>> createSourceComponentFunction,
String continuationToken,
Map<String, AggregateOperator> groupByAliasToAggregateType,
List<String> orderedAliases,
boolean hasSelectValue,
PipelinedDocumentQueryParams<T> documentQueryParams) {
if (continuationToken != null) {
CosmosException dce = new BadRequestException(CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY);
return Flux.error(dce);
}
if (groupByAliasToAggregateType == null) {
throw new IllegalArgumentException("groupByAliasToAggregateType should not be null");
}
if (orderedAliases == null) {
throw new IllegalArgumentException("orderedAliases should not be null");
}
GroupingTable table = new GroupingTable(groupByAliasToAggregateType, orderedAliases, hasSelectValue);
return createSourceComponentFunction.apply(null, documentQueryParams)
.map(component -> new GroupByDocumentQueryExecutionContext<>(component,
table));
}
@SuppressWarnings("unchecked")
@Override
public Flux<FeedResponse<T>> drainAsync(int maxPageSize) {
return this.component.drainAsync(maxPageSize)
.collectList()
.map(superList -> {
double requestCharge = 0;
HashMap<String, String> headers = new HashMap<>();
List<Document> documentList = new ArrayList<>();
/* Do groupBy stuff here */
this.aggregateGroupings(documentList);
return (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, requestCharge);
}).expand(tFeedResponse -> {
FeedResponse<T> response = (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, 0);
if (response == null) {
return Mono.empty();
}
return Mono.just(response);
});
}
private FeedResponse<Document> createFeedResponseFromGroupingTable(int pageSize, double requestCharge) {
if (this.groupingTable != null) {
List<Document> groupByResults = groupingTable.drain(pageSize);
if (groupByResults.size() == 0) {
return null;
}
HashMap<String, String> headers = new HashMap<>();
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
FeedResponse<Document> frp = BridgeInternal.createFeedResponse(groupByResults, headers);
return frp;
}
return null;
}
private void aggregateGroupings(List<Document> superList) {
for (Document d : superList) {
RewrittenGroupByProjection rewrittenGroupByProjection =
new RewrittenGroupByProjection(ModelBridgeInternal.getPropertyBagFromJsonSerializable(d));
this.groupingTable.addPayLoad(rewrittenGroupByProjection);
}
}
IDocumentQueryExecutionComponent<T> getComponent() {
return this.component;
}
/**
* When a group by query gets rewritten the projection looks like:
* <p>
* SELECT
* [{"item": c.age}, {"item": c.name}] AS groupByItems,
* {"age": c.age, "name": c.name} AS payload
* <p>
* This class just lets us easily access the "groupByItems" and "payload" property.
*/
public class RewrittenGroupByProjection extends JsonSerializable {
private static final String GROUP_BY_ITEMS_PROPERTY_NAME = "groupByItems";
private static final String PAYLOAD_PROPERTY_NAME = "payload";
private List<Document> groupByItems;
public RewrittenGroupByProjection(ObjectNode objectNode) {
super(objectNode);
if (objectNode == null) {
throw new IllegalArgumentException("objectNode can not be null");
}
}
/**
* Getter for property 'groupByItems'.
*
* @return Value for property 'groupByItems'.
*/
public List<Document> getGroupByItems() {
groupByItems = this.getList(GROUP_BY_ITEMS_PROPERTY_NAME, Document.class);
if (groupByItems == null) {
throw new IllegalStateException("Underlying object does not have an 'groupByItems' field.");
}
return groupByItems;
}
/**
* Getter for property 'payload'.
*
* @return Value for property 'payload'.
*/
public Document getPayload() {
if (!this.has(PAYLOAD_PROPERTY_NAME)) {
throw new IllegalStateException("Underlying object does not have an 'payload' field.");
}
return new Document((ObjectNode) this.get(PAYLOAD_PROPERTY_NAME));
}
}
} | class GroupByDocumentQueryExecutionContext<T extends Resource> implements
IDocumentQueryExecutionComponent<T> {
public static final String CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY = "Continuation token is not supported " +
"for queries with GROUP BY." +
"Do not use continuation token" +
" or remove the GROUP BY " +
"from the query.";
private final IDocumentQueryExecutionComponent<T> component;
private final GroupingTable groupingTable;
GroupByDocumentQueryExecutionContext(
IDocumentQueryExecutionComponent<T> component,
GroupingTable groupingTable) {
this.component = component;
this.groupingTable = groupingTable;
}
public static <T extends Resource> Flux<IDocumentQueryExecutionComponent<T>> createAsync(
BiFunction<String, PipelinedDocumentQueryParams<T>, Flux<IDocumentQueryExecutionComponent<T>>> createSourceComponentFunction,
String continuationToken,
Map<String, AggregateOperator> groupByAliasToAggregateType,
List<String> orderedAliases,
boolean hasSelectValue,
PipelinedDocumentQueryParams<T> documentQueryParams) {
if (continuationToken != null) {
CosmosException dce = new BadRequestException(CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY);
return Flux.error(dce);
}
if (groupByAliasToAggregateType == null) {
throw new IllegalArgumentException("groupByAliasToAggregateType should not be null");
}
if (orderedAliases == null) {
throw new IllegalArgumentException("orderedAliases should not be null");
}
GroupingTable table = new GroupingTable(groupByAliasToAggregateType, orderedAliases, hasSelectValue);
return createSourceComponentFunction.apply(null, documentQueryParams)
.map(component -> new GroupByDocumentQueryExecutionContext<>(component,
table));
}
@SuppressWarnings("unchecked")
@Override
public Flux<FeedResponse<T>> drainAsync(int maxPageSize) {
return this.component.drainAsync(maxPageSize)
.collectList()
.map(superList -> {
double requestCharge = 0;
HashMap<String, String> headers = new HashMap<>();
List<Document> documentList = new ArrayList<>();
/* Do groupBy stuff here */
this.aggregateGroupings(documentList);
return createFeedResponseFromGroupingTable(maxPageSize, requestCharge);
}).expand(tFeedResponse -> {
FeedResponse<T> response = createFeedResponseFromGroupingTable(maxPageSize, 0);
if (response == null) {
return Mono.empty();
}
return Mono.just(response);
});
}
@SuppressWarnings("unchecked")
private FeedResponse<T> createFeedResponseFromGroupingTable(int pageSize, double requestCharge) {
if (this.groupingTable != null) {
List<Document> groupByResults = groupingTable.drain(pageSize);
if (groupByResults.size() == 0) {
return null;
}
HashMap<String, String> headers = new HashMap<>();
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
FeedResponse<Document> frp = BridgeInternal.createFeedResponse(groupByResults, headers);
return (FeedResponse<T>) frp;
}
return null;
}
private void aggregateGroupings(List<Document> superList) {
for (Document d : superList) {
RewrittenGroupByProjection rewrittenGroupByProjection =
new RewrittenGroupByProjection(ModelBridgeInternal.getPropertyBagFromJsonSerializable(d));
this.groupingTable.addPayLoad(rewrittenGroupByProjection);
}
}
IDocumentQueryExecutionComponent<T> getComponent() {
return this.component;
}
/**
* When a group by query gets rewritten the projection looks like:
* <p>
* SELECT
* [{"item": c.age}, {"item": c.name}] AS groupByItems,
* {"age": c.age, "name": c.name} AS payload
* <p>
* This class just lets us easily access the "groupByItems" and "payload" property.
*/
public class RewrittenGroupByProjection extends JsonSerializable {
private static final String GROUP_BY_ITEMS_PROPERTY_NAME = "groupByItems";
private static final String PAYLOAD_PROPERTY_NAME = "payload";
private List<Document> groupByItems;
public RewrittenGroupByProjection(ObjectNode objectNode) {
super(objectNode);
if (objectNode == null) {
throw new IllegalArgumentException("objectNode can not be null");
}
}
/**
* Getter for property 'groupByItems'.
*
* @return Value for property 'groupByItems'.
*/
public List<Document> getGroupByItems() {
groupByItems = this.getList(GROUP_BY_ITEMS_PROPERTY_NAME, Document.class);
if (groupByItems == null) {
throw new IllegalStateException("Underlying object does not have an 'groupByItems' field.");
}
return groupByItems;
}
/**
* Getter for property 'payload'.
*
* @return Value for property 'payload'.
*/
public Document getPayload() {
if (!this.has(PAYLOAD_PROPERTY_NAME)) {
throw new IllegalStateException("Underlying object does not have an 'payload' field.");
}
return new Document((ObjectNode) this.get(PAYLOAD_PROPERTY_NAME));
}
}
} | |
changed to update in the createFeedResponseFromGroupingTable | public Flux<FeedResponse<T>> drainAsync(int maxPageSize) {
return this.component.drainAsync(maxPageSize)
.collectList()
.map(superList -> {
double requestCharge = 0;
HashMap<String, String> headers = new HashMap<>();
List<Document> documentList = new ArrayList<>();
/* Do groupBy stuff here */
for (FeedResponse<T> page : superList) {
List<Document> results = (List<Document>) page.getResults();
documentList.addAll(results);
requestCharge += page.getRequestCharge();
}
this.aggregateGroupings(documentList);
return (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, requestCharge);
}).expand(tFeedResponse -> {
FeedResponse<T> response = (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, 0);
if (response == null) {
return Mono.empty();
}
return Mono.just(response);
});
} | return (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, requestCharge); | Drain the groupings fully from all continuation and all partitions
for (FeedResponse<T> page : superList) {
List<Document> results = (List<Document>) page.getResults();
documentList.addAll(results);
requestCharge += page.getRequestCharge();
} | class GroupByDocumentQueryExecutionContext<T extends Resource> implements
IDocumentQueryExecutionComponent<T> {
public static final String CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY = "Continuation token is not supported " +
"for queries with GROUP BY." +
"Do not use continuation token" +
" or remove the GROUP BY " +
"from the query.";
private final IDocumentQueryExecutionComponent<T> component;
private final GroupingTable groupingTable;
GroupByDocumentQueryExecutionContext(
IDocumentQueryExecutionComponent<T> component,
GroupingTable groupingTable) {
this.component = component;
this.groupingTable = groupingTable;
}
public static <T extends Resource> Flux<IDocumentQueryExecutionComponent<T>> createAsync(
BiFunction<String, PipelinedDocumentQueryParams<T>, Flux<IDocumentQueryExecutionComponent<T>>> createSourceComponentFunction,
String continuationToken,
Map<String, AggregateOperator> groupByAliasToAggregateType,
List<String> orderedAliases,
boolean hasSelectValue,
PipelinedDocumentQueryParams<T> documentQueryParams) {
if (continuationToken != null) {
CosmosException dce = new BadRequestException(CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY);
return Flux.error(dce);
}
if (groupByAliasToAggregateType == null) {
throw new IllegalArgumentException("groupByAliasToAggregateType should not be null");
}
if (orderedAliases == null) {
throw new IllegalArgumentException("orderedAliases should not be null");
}
GroupingTable table = new GroupingTable(groupByAliasToAggregateType, orderedAliases, hasSelectValue);
return createSourceComponentFunction.apply(null, documentQueryParams)
.map(component -> new GroupByDocumentQueryExecutionContext<>(component,
table));
}
@SuppressWarnings("unchecked")
@Override
public Flux<FeedResponse<T>> drainAsync(int maxPageSize) {
return this.component.drainAsync(maxPageSize)
.collectList()
.map(superList -> {
double requestCharge = 0;
HashMap<String, String> headers = new HashMap<>();
List<Document> documentList = new ArrayList<>();
/* Do groupBy stuff here */
this.aggregateGroupings(documentList);
return (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, requestCharge);
}).expand(tFeedResponse -> {
FeedResponse<T> response = (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, 0);
if (response == null) {
return Mono.empty();
}
return Mono.just(response);
});
}
private FeedResponse<Document> createFeedResponseFromGroupingTable(int pageSize, double requestCharge) {
if (this.groupingTable != null) {
List<Document> groupByResults = groupingTable.drain(pageSize);
if (groupByResults.size() == 0) {
return null;
}
HashMap<String, String> headers = new HashMap<>();
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
FeedResponse<Document> frp = BridgeInternal.createFeedResponse(groupByResults, headers);
return frp;
}
return null;
}
private void aggregateGroupings(List<Document> superList) {
for (Document d : superList) {
RewrittenGroupByProjection rewrittenGroupByProjection =
new RewrittenGroupByProjection(ModelBridgeInternal.getPropertyBagFromJsonSerializable(d));
this.groupingTable.addPayLoad(rewrittenGroupByProjection);
}
}
IDocumentQueryExecutionComponent<T> getComponent() {
return this.component;
}
/**
* When a group by query gets rewritten the projection looks like:
* <p>
* SELECT
* [{"item": c.age}, {"item": c.name}] AS groupByItems,
* {"age": c.age, "name": c.name} AS payload
* <p>
* This class just lets us easily access the "groupByItems" and "payload" property.
*/
public class RewrittenGroupByProjection extends JsonSerializable {
private static final String GROUP_BY_ITEMS_PROPERTY_NAME = "groupByItems";
private static final String PAYLOAD_PROPERTY_NAME = "payload";
private List<Document> groupByItems;
public RewrittenGroupByProjection(ObjectNode objectNode) {
super(objectNode);
if (objectNode == null) {
throw new IllegalArgumentException("objectNode can not be null");
}
}
/**
* Getter for property 'groupByItems'.
*
* @return Value for property 'groupByItems'.
*/
public List<Document> getGroupByItems() {
groupByItems = this.getList(GROUP_BY_ITEMS_PROPERTY_NAME, Document.class);
if (groupByItems == null) {
throw new IllegalStateException("Underlying object does not have an 'groupByItems' field.");
}
return groupByItems;
}
/**
* Getter for property 'payload'.
*
* @return Value for property 'payload'.
*/
public Document getPayload() {
if (!this.has(PAYLOAD_PROPERTY_NAME)) {
throw new IllegalStateException("Underlying object does not have an 'payload' field.");
}
return new Document((ObjectNode) this.get(PAYLOAD_PROPERTY_NAME));
}
}
} | class GroupByDocumentQueryExecutionContext<T extends Resource> implements
IDocumentQueryExecutionComponent<T> {
public static final String CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY = "Continuation token is not supported " +
"for queries with GROUP BY." +
"Do not use continuation token" +
" or remove the GROUP BY " +
"from the query.";
private final IDocumentQueryExecutionComponent<T> component;
private final GroupingTable groupingTable;
GroupByDocumentQueryExecutionContext(
IDocumentQueryExecutionComponent<T> component,
GroupingTable groupingTable) {
this.component = component;
this.groupingTable = groupingTable;
}
public static <T extends Resource> Flux<IDocumentQueryExecutionComponent<T>> createAsync(
BiFunction<String, PipelinedDocumentQueryParams<T>, Flux<IDocumentQueryExecutionComponent<T>>> createSourceComponentFunction,
String continuationToken,
Map<String, AggregateOperator> groupByAliasToAggregateType,
List<String> orderedAliases,
boolean hasSelectValue,
PipelinedDocumentQueryParams<T> documentQueryParams) {
if (continuationToken != null) {
CosmosException dce = new BadRequestException(CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY);
return Flux.error(dce);
}
if (groupByAliasToAggregateType == null) {
throw new IllegalArgumentException("groupByAliasToAggregateType should not be null");
}
if (orderedAliases == null) {
throw new IllegalArgumentException("orderedAliases should not be null");
}
GroupingTable table = new GroupingTable(groupByAliasToAggregateType, orderedAliases, hasSelectValue);
return createSourceComponentFunction.apply(null, documentQueryParams)
.map(component -> new GroupByDocumentQueryExecutionContext<>(component,
table));
}
@SuppressWarnings("unchecked")
@Override
public Flux<FeedResponse<T>> drainAsync(int maxPageSize) {
return this.component.drainAsync(maxPageSize)
.collectList()
.map(superList -> {
double requestCharge = 0;
HashMap<String, String> headers = new HashMap<>();
List<Document> documentList = new ArrayList<>();
/* Do groupBy stuff here */
this.aggregateGroupings(documentList);
return createFeedResponseFromGroupingTable(maxPageSize, requestCharge);
}).expand(tFeedResponse -> {
FeedResponse<T> response = createFeedResponseFromGroupingTable(maxPageSize, 0);
if (response == null) {
return Mono.empty();
}
return Mono.just(response);
});
}
@SuppressWarnings("unchecked")
private FeedResponse<T> createFeedResponseFromGroupingTable(int pageSize, double requestCharge) {
if (this.groupingTable != null) {
List<Document> groupByResults = groupingTable.drain(pageSize);
if (groupByResults.size() == 0) {
return null;
}
HashMap<String, String> headers = new HashMap<>();
headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge));
FeedResponse<Document> frp = BridgeInternal.createFeedResponse(groupByResults, headers);
return (FeedResponse<T>) frp;
}
return null;
}
private void aggregateGroupings(List<Document> superList) {
for (Document d : superList) {
RewrittenGroupByProjection rewrittenGroupByProjection =
new RewrittenGroupByProjection(ModelBridgeInternal.getPropertyBagFromJsonSerializable(d));
this.groupingTable.addPayLoad(rewrittenGroupByProjection);
}
}
IDocumentQueryExecutionComponent<T> getComponent() {
return this.component;
}
/**
* When a group by query gets rewritten the projection looks like:
* <p>
* SELECT
* [{"item": c.age}, {"item": c.name}] AS groupByItems,
* {"age": c.age, "name": c.name} AS payload
* <p>
* This class just lets us easily access the "groupByItems" and "payload" property.
*/
public class RewrittenGroupByProjection extends JsonSerializable {
private static final String GROUP_BY_ITEMS_PROPERTY_NAME = "groupByItems";
private static final String PAYLOAD_PROPERTY_NAME = "payload";
private List<Document> groupByItems;
public RewrittenGroupByProjection(ObjectNode objectNode) {
super(objectNode);
if (objectNode == null) {
throw new IllegalArgumentException("objectNode can not be null");
}
}
/**
* Getter for property 'groupByItems'.
*
* @return Value for property 'groupByItems'.
*/
public List<Document> getGroupByItems() {
groupByItems = this.getList(GROUP_BY_ITEMS_PROPERTY_NAME, Document.class);
if (groupByItems == null) {
throw new IllegalStateException("Underlying object does not have an 'groupByItems' field.");
}
return groupByItems;
}
/**
* Getter for property 'payload'.
*
* @return Value for property 'payload'.
*/
public Document getPayload() {
if (!this.has(PAYLOAD_PROPERTY_NAME)) {
throw new IllegalStateException("Underlying object does not have an 'payload' field.");
}
return new Document((ObjectNode) this.get(PAYLOAD_PROPERTY_NAME));
}
}
} |
Are tokens guaranteed to be ASCII only? If not it may be better to use `StandardCharset.UTF_8` here as the `defaultCharset` is specific to the machine. Linux and Mac will default `UTF-8` while Windows defaults `CP1252`. | private void mockForMSICodeFlow(String tokenJson) throws Exception {
URL u = PowerMockito.mock(URL.class);
whenNew(URL.class).withAnyArguments().thenReturn(u);
HttpURLConnection huc = PowerMockito.mock(HttpURLConnection.class);
when(u.openConnection()).thenReturn(huc);
PowerMockito.doNothing().when(huc).setRequestMethod(anyString());
PowerMockito.doNothing().when(huc).setRequestMethod(anyString());
PowerMockito.doNothing().when(huc).setRequestMethod(anyString());
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
} | InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset())); | private void mockForMSICodeFlow(String tokenJson) throws Exception {
URL u = PowerMockito.mock(URL.class);
whenNew(URL.class).withAnyArguments().thenReturn(u);
HttpURLConnection huc = PowerMockito.mock(HttpURLConnection.class);
when(u.openConnection()).thenReturn(huc);
PowerMockito.doNothing().when(huc).setRequestMethod(anyString());
PowerMockito.doNothing().when(huc).setRequestMethod(anyString());
PowerMockito.doNothing().when(huc).setRequestMethod(anyString());
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
} | class IdentityClientTests {
private static final String TENANT_ID = "contoso.com";
private static final String CLIENT_ID = UUID.randomUUID().toString();
@Test
public void testValidSecret() throws Exception {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientSecret(secret, request, accessToken, expiresOn);
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).clientSecret(secret).build();
AccessToken token = client.authenticateWithConfidentialClient(request).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testInvalidSecret() throws Exception {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientSecret(secret, request, accessToken, expiresOn);
try {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).clientSecret("bad secret").build();
client.authenticateWithConfidentialClient(request).block();
fail();
} catch (MsalServiceException e) {
Assert.assertEquals("Invalid clientSecret", e.getMessage());
}
}
@Test
public void testValidCertificate() throws Exception {
String pfxPath = getClass().getResource("/keyStore.pfx").getPath();
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientCertificate(request, accessToken, expiresOn);
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.certificatePath(pfxPath).certificatePassword("StrongPass!123").build();
AccessToken token = client.authenticateWithConfidentialClient(request).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testPemCertificate() throws Exception {
String pemPath = getClass().getClassLoader().getResource("certificate.pem").getPath();
if (pemPath.contains(":")) {
pemPath = pemPath.substring(1);
}
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientPemCertificate(accessToken, request, expiresOn);
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).certificatePath(pemPath).build();
AccessToken token = client.authenticateWithConfidentialClient(request).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testInvalidCertificatePassword() throws Exception {
String pfxPath = getClass().getResource("/keyStore.pfx").getPath();
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientCertificate(request, accessToken, expiresOn);
try {
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.certificatePath(pfxPath).certificatePassword("BadPassword").build();
client.authenticateWithConfidentialClient(request).block();
fail();
} catch (Exception e) {
Assert.assertTrue(e.getMessage().contains("password was incorrect"));
}
}
@Test
public void testValidDeviceCodeFlow() throws Exception {
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForDeviceCodeFlow(request, accessToken, expiresOn);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
AccessToken token = client.authenticateWithDeviceCode(request, deviceCodeChallenge -> { /* do nothing */ }).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testValidMSICodeFlow() throws Exception {
Configuration configuration = Configuration.getGlobalConfiguration();
String endpoint = "http:
String secret = "secret";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
configuration.put("MSI_ENDPOINT", endpoint);
configuration.put("MSI_SECRET", secret);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
mockForMSICodeFlow(tokenJson);
IdentityClient client = new IdentityClientBuilder().build();
AccessToken token = client.authenticateToManagedIdentityEndpoint(endpoint, secret, request).block();
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testValidIMDSCodeFlow() throws Exception {
Configuration configuration = Configuration.getGlobalConfiguration();
String endpoint = "http:
String secret = "secret";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
configuration.put("MSI_ENDPOINT", endpoint);
configuration.put("MSI_SECRET", secret);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
mockForIMDSCodeFlow(tokenJson);
IdentityClient client = new IdentityClientBuilder().build();
AccessToken token = client.authenticateToIMDSEndpoint(request).block();
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testAuthorizationCodeFlow() throws Exception {
String token1 = "token1";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
String authCode1 = "authCode1";
URI redirectUri = new URI("http:
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForAuthorizationCodeFlow(token1, request, expiresAt);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithAuthorizationCode(request, authCode1, redirectUri))
.expectNextMatches(accessToken -> token1.equals(accessToken.getToken())
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
}
@Test
public void testUserRefreshTokenflow() throws Exception {
String token1 = "token1";
String token2 = "token1";
TokenRequestContext request2 = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForUserRefreshTokenFlow(token2, request2, expiresAt);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithPublicClientCache(request2, TestUtils.getMockMsalAccount(token1, expiresAt).block()))
.expectNextMatches(accessToken -> token2.equals(accessToken.getToken())
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
}
@Test
public void testUsernamePasswordCodeFlow() throws Exception {
String username = "testuser";
String password = "testpassword";
String token = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForUsernamePasswordCodeFlow(token, request, expiresOn);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithUsernamePassword(request, username, password))
.expectNextMatches(accessToken -> token.equals(accessToken.getToken())
&& expiresOn.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
}
@Test
public void testBrowserAuthenicationCodeFlow() throws Exception {
String username = "testuser";
String password = "testpassword";
String token = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForAuthorizationCodeFlow(token, request, expiresOn);
mocForBrowserAuthenticationCodeFlow();
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithBrowserInteraction(request, 4567))
.expectNextMatches(accessToken -> token.equals(accessToken.getToken())
&& expiresOn.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
}
@Test
public void testOpenUrl() throws Exception {
PowerMockito.mockStatic(Runtime.class);
Runtime rt = PowerMockito.mock(Runtime.class);
when(Runtime.getRuntime()).thenReturn(rt);
Process a = PowerMockito.mock(Process.class);
when(rt.exec(anyString())).thenReturn(a);
IdentityClient client = new IdentityClientBuilder().clientId("dummy").build();
client.openUrl("https:
}
/****** mocks ******/
private void mockForClientSecret(String secret, TokenRequestContext request, String accessToken, OffsetDateTime expiresOn) throws Exception {
ConfidentialClientApplication application = PowerMockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
ConfidentialClientApplication.Builder builder = PowerMockito.mock(ConfidentialClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(ConfidentialClientApplication.Builder.class).withAnyArguments().thenAnswer(invocation -> {
String cid = (String) invocation.getArguments()[0];
IClientSecret clientSecret = (IClientSecret) invocation.getArguments()[1];
if (!CLIENT_ID.equals(cid)) {
throw new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId");
}
if (!secret.equals(clientSecret.clientSecret())) {
throw new MsalServiceException("Invalid clientSecret", "InvalidClientSecret");
}
return builder;
});
}
private void mockForClientCertificate(TokenRequestContext request, String accessToken, OffsetDateTime expiresOn) throws Exception {
ConfidentialClientApplication application = PowerMockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
ConfidentialClientApplication.Builder builder = PowerMockito.mock(ConfidentialClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(ConfidentialClientApplication.Builder.class).withAnyArguments().thenAnswer(invocation -> {
String cid = (String) invocation.getArguments()[0];
IClientCredential keyCredential = (IClientCredential) invocation.getArguments()[1];
if (!CLIENT_ID.equals(cid)) {
throw new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId");
}
if (keyCredential == null) {
throw new MsalServiceException("Invalid clientCertificate", "InvalidClientCertificate");
}
return builder;
});
}
private void mockForDeviceCodeFlow(TokenRequestContext request, String accessToken, OffsetDateTime expiresOn) throws Exception {
PublicClientApplication application = PowerMockito.mock(PublicClientApplication.class);
AtomicBoolean cached = new AtomicBoolean(false);
when(application.acquireToken(any(DeviceCodeFlowParameters.class))).thenAnswer(invocation -> {
DeviceCodeFlowParameters argument = (DeviceCodeFlowParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || !request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
if (argument.deviceCodeConsumer() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid device code consumer", "InvalidDeviceCodeConsumer");
});
}
cached.set(true);
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
});
PublicClientApplication.Builder builder = PowerMockito.mock(PublicClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(PublicClientApplication.Builder.class).withArguments(CLIENT_ID).thenReturn(builder);
}
private void mockForClientPemCertificate(String accessToken, TokenRequestContext request, OffsetDateTime expiresOn) throws Exception {
ConfidentialClientApplication application = PowerMockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
ConfidentialClientApplication.Builder builder = PowerMockito.mock(ConfidentialClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(ConfidentialClientApplication.Builder.class).withAnyArguments().thenAnswer(invocation -> {
String cid = (String) invocation.getArguments()[0];
if (!CLIENT_ID.equals(cid)) {
throw new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId");
}
return builder;
});
PowerMockito.mockStatic(CertificateUtil.class);
PowerMockito.mockStatic(ClientCredentialFactory.class);
PrivateKey privateKey = PowerMockito.mock(PrivateKey.class);
IClientCertificate clientCertificate = PowerMockito.mock(IClientCertificate.class);
when(CertificateUtil.privateKeyFromPem(any())).thenReturn(privateKey);
when(ClientCredentialFactory.createFromCertificate(any(PrivateKey.class), any(X509Certificate.class)))
.thenReturn(clientCertificate);
}
private void mockForIMDSCodeFlow(String tokenJson) throws Exception {
URL u = PowerMockito.mock(URL.class);
whenNew(URL.class).withAnyArguments().thenReturn(u);
HttpURLConnection huc = PowerMockito.mock(HttpURLConnection.class);
when(u.openConnection()).thenReturn(huc);
PowerMockito.doNothing().when(huc).setRequestMethod(anyString());
PowerMockito.doNothing().when(huc).setConnectTimeout(ArgumentMatchers.anyInt());
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
}
private void mocForBrowserAuthenticationCodeFlow() throws Exception {
AuthorizationCodeListener authorizationCodeListener = PowerMockito.mock(AuthorizationCodeListener.class);
whenNew(AuthorizationCodeListener.class).withAnyArguments().thenReturn((authorizationCodeListener));
when(authorizationCodeListener.listen()).thenReturn(Mono.just("auth-Code"));
when(authorizationCodeListener.dispose()).thenReturn(Mono.empty());
when(authorizationCodeListener.dispose()).thenReturn(Mono.empty());
}
private void mockForAuthorizationCodeFlow(String token1, TokenRequestContext request, OffsetDateTime expiresAt) throws Exception {
PublicClientApplication application = PowerMockito.mock(PublicClientApplication.class);
AtomicBoolean cached = new AtomicBoolean(false);
when(application.acquireToken(any(AuthorizationCodeParameters.class))).thenAnswer(invocation -> {
AuthorizationCodeParameters argument = (AuthorizationCodeParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || !request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
if (argument.redirectUri() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid redirect uri", "InvalidAuthorizationCodeRedirectUri");
});
}
if (argument.authorizationCode() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid authorization code", "InvalidAuthorizationCode");
});
}
cached.set(true);
return TestUtils.getMockAuthenticationResult(token1, expiresAt);
});
PublicClientApplication.Builder builder = PowerMockito.mock(PublicClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(PublicClientApplication.Builder.class).withArguments(CLIENT_ID).thenReturn(builder);
}
private void mockForUsernamePasswordCodeFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn) throws Exception {
PublicClientApplication application = PowerMockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(UserNamePasswordParameters.class)))
.thenAnswer(invocation -> {
UserNamePasswordParameters argument = (UserNamePasswordParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
PublicClientApplication.Builder builder = PowerMockito.mock(PublicClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(PublicClientApplication.Builder.class).withArguments(CLIENT_ID).thenReturn(builder);
}
private void mockForUserRefreshTokenFlow(String token2, TokenRequestContext request2, OffsetDateTime expiresAt) throws Exception {
PublicClientApplication application = PowerMockito.mock(PublicClientApplication.class);
when(application.acquireTokenSilently(any()))
.thenAnswer(invocation -> {
SilentParameters argument = (SilentParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request2.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token2, expiresAt);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
PublicClientApplication.Builder builder = PowerMockito.mock(PublicClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(PublicClientApplication.Builder.class).withArguments(CLIENT_ID).thenReturn(builder);
}
} | class IdentityClientTests {
private static final String TENANT_ID = "contoso.com";
private static final String CLIENT_ID = UUID.randomUUID().toString();
@Test
public void testValidSecret() throws Exception {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientSecret(secret, request, accessToken, expiresOn);
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).clientSecret(secret).build();
AccessToken token = client.authenticateWithConfidentialClient(request).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testInvalidSecret() throws Exception {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientSecret(secret, request, accessToken, expiresOn);
try {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).clientSecret("bad secret").build();
client.authenticateWithConfidentialClient(request).block();
fail();
} catch (MsalServiceException e) {
Assert.assertEquals("Invalid clientSecret", e.getMessage());
}
}
@Test
public void testValidCertificate() throws Exception {
String pfxPath = getClass().getResource("/keyStore.pfx").getPath();
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientCertificate(request, accessToken, expiresOn);
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.certificatePath(pfxPath).certificatePassword("StrongPass!123").build();
AccessToken token = client.authenticateWithConfidentialClient(request).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testPemCertificate() throws Exception {
String pemPath = getClass().getClassLoader().getResource("certificate.pem").getPath();
if (pemPath.contains(":")) {
pemPath = pemPath.substring(1);
}
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientPemCertificate(accessToken, request, expiresOn);
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).certificatePath(pemPath).build();
AccessToken token = client.authenticateWithConfidentialClient(request).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testInvalidCertificatePassword() throws Exception {
String pfxPath = getClass().getResource("/keyStore.pfx").getPath();
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientCertificate(request, accessToken, expiresOn);
try {
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.certificatePath(pfxPath).certificatePassword("BadPassword").build();
client.authenticateWithConfidentialClient(request).block();
fail();
} catch (Exception e) {
Assert.assertTrue(e.getMessage().contains("password was incorrect"));
}
}
@Test
public void testValidDeviceCodeFlow() throws Exception {
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForDeviceCodeFlow(request, accessToken, expiresOn);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
AccessToken token = client.authenticateWithDeviceCode(request, deviceCodeChallenge -> { /* do nothing */ }).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testValidMSICodeFlow() throws Exception {
Configuration configuration = Configuration.getGlobalConfiguration();
String endpoint = "http:
String secret = "secret";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
configuration.put("MSI_ENDPOINT", endpoint);
configuration.put("MSI_SECRET", secret);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
mockForMSICodeFlow(tokenJson);
IdentityClient client = new IdentityClientBuilder().build();
AccessToken token = client.authenticateToManagedIdentityEndpoint(endpoint, secret, request).block();
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testValidIMDSCodeFlow() throws Exception {
Configuration configuration = Configuration.getGlobalConfiguration();
String endpoint = "http:
String secret = "secret";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
configuration.put("MSI_ENDPOINT", endpoint);
configuration.put("MSI_SECRET", secret);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
mockForIMDSCodeFlow(tokenJson);
IdentityClient client = new IdentityClientBuilder().build();
AccessToken token = client.authenticateToIMDSEndpoint(request).block();
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testAuthorizationCodeFlow() throws Exception {
String token1 = "token1";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
String authCode1 = "authCode1";
URI redirectUri = new URI("http:
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForAuthorizationCodeFlow(token1, request, expiresAt);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithAuthorizationCode(request, authCode1, redirectUri))
.expectNextMatches(accessToken -> token1.equals(accessToken.getToken())
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
}
@Test
public void testUserRefreshTokenflow() throws Exception {
String token1 = "token1";
String token2 = "token1";
TokenRequestContext request2 = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForUserRefreshTokenFlow(token2, request2, expiresAt);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithPublicClientCache(request2, TestUtils.getMockMsalAccount(token1, expiresAt).block()))
.expectNextMatches(accessToken -> token2.equals(accessToken.getToken())
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
}
@Test
public void testUsernamePasswordCodeFlow() throws Exception {
String username = "testuser";
String password = "testpassword";
String token = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForUsernamePasswordCodeFlow(token, request, expiresOn);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithUsernamePassword(request, username, password))
.expectNextMatches(accessToken -> token.equals(accessToken.getToken())
&& expiresOn.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
}
@Test
public void testBrowserAuthenicationCodeFlow() throws Exception {
String username = "testuser";
String password = "testpassword";
String token = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForAuthorizationCodeFlow(token, request, expiresOn);
mocForBrowserAuthenticationCodeFlow();
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithBrowserInteraction(request, 4567))
.expectNextMatches(accessToken -> token.equals(accessToken.getToken())
&& expiresOn.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
}
@Test
public void testOpenUrl() throws Exception {
PowerMockito.mockStatic(Runtime.class);
Runtime rt = PowerMockito.mock(Runtime.class);
when(Runtime.getRuntime()).thenReturn(rt);
Process a = PowerMockito.mock(Process.class);
when(rt.exec(anyString())).thenReturn(a);
IdentityClient client = new IdentityClientBuilder().clientId("dummy").build();
client.openUrl("https:
}
/****** mocks ******/
private void mockForClientSecret(String secret, TokenRequestContext request, String accessToken, OffsetDateTime expiresOn) throws Exception {
ConfidentialClientApplication application = PowerMockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
ConfidentialClientApplication.Builder builder = PowerMockito.mock(ConfidentialClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(ConfidentialClientApplication.Builder.class).withAnyArguments().thenAnswer(invocation -> {
String cid = (String) invocation.getArguments()[0];
IClientSecret clientSecret = (IClientSecret) invocation.getArguments()[1];
if (!CLIENT_ID.equals(cid)) {
throw new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId");
}
if (!secret.equals(clientSecret.clientSecret())) {
throw new MsalServiceException("Invalid clientSecret", "InvalidClientSecret");
}
return builder;
});
}
private void mockForClientCertificate(TokenRequestContext request, String accessToken, OffsetDateTime expiresOn) throws Exception {
ConfidentialClientApplication application = PowerMockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
ConfidentialClientApplication.Builder builder = PowerMockito.mock(ConfidentialClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(ConfidentialClientApplication.Builder.class).withAnyArguments().thenAnswer(invocation -> {
String cid = (String) invocation.getArguments()[0];
IClientCredential keyCredential = (IClientCredential) invocation.getArguments()[1];
if (!CLIENT_ID.equals(cid)) {
throw new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId");
}
if (keyCredential == null) {
throw new MsalServiceException("Invalid clientCertificate", "InvalidClientCertificate");
}
return builder;
});
}
private void mockForDeviceCodeFlow(TokenRequestContext request, String accessToken, OffsetDateTime expiresOn) throws Exception {
PublicClientApplication application = PowerMockito.mock(PublicClientApplication.class);
AtomicBoolean cached = new AtomicBoolean(false);
when(application.acquireToken(any(DeviceCodeFlowParameters.class))).thenAnswer(invocation -> {
DeviceCodeFlowParameters argument = (DeviceCodeFlowParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || !request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
if (argument.deviceCodeConsumer() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid device code consumer", "InvalidDeviceCodeConsumer");
});
}
cached.set(true);
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
});
PublicClientApplication.Builder builder = PowerMockito.mock(PublicClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(PublicClientApplication.Builder.class).withArguments(CLIENT_ID).thenReturn(builder);
}
private void mockForClientPemCertificate(String accessToken, TokenRequestContext request, OffsetDateTime expiresOn) throws Exception {
ConfidentialClientApplication application = PowerMockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
ConfidentialClientApplication.Builder builder = PowerMockito.mock(ConfidentialClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(ConfidentialClientApplication.Builder.class).withAnyArguments().thenAnswer(invocation -> {
String cid = (String) invocation.getArguments()[0];
if (!CLIENT_ID.equals(cid)) {
throw new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId");
}
return builder;
});
PowerMockito.mockStatic(CertificateUtil.class);
PowerMockito.mockStatic(ClientCredentialFactory.class);
PrivateKey privateKey = PowerMockito.mock(PrivateKey.class);
IClientCertificate clientCertificate = PowerMockito.mock(IClientCertificate.class);
when(CertificateUtil.privateKeyFromPem(any())).thenReturn(privateKey);
when(ClientCredentialFactory.createFromCertificate(any(PrivateKey.class), any(X509Certificate.class)))
.thenReturn(clientCertificate);
}
private void mockForIMDSCodeFlow(String tokenJson) throws Exception {
URL u = PowerMockito.mock(URL.class);
whenNew(URL.class).withAnyArguments().thenReturn(u);
HttpURLConnection huc = PowerMockito.mock(HttpURLConnection.class);
when(u.openConnection()).thenReturn(huc);
PowerMockito.doNothing().when(huc).setRequestMethod(anyString());
PowerMockito.doNothing().when(huc).setConnectTimeout(ArgumentMatchers.anyInt());
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
}
private void mocForBrowserAuthenticationCodeFlow() throws Exception {
AuthorizationCodeListener authorizationCodeListener = PowerMockito.mock(AuthorizationCodeListener.class);
whenNew(AuthorizationCodeListener.class).withAnyArguments().thenReturn((authorizationCodeListener));
when(authorizationCodeListener.listen()).thenReturn(Mono.just("auth-Code"));
when(authorizationCodeListener.dispose()).thenReturn(Mono.empty());
when(authorizationCodeListener.dispose()).thenReturn(Mono.empty());
}
private void mockForAuthorizationCodeFlow(String token1, TokenRequestContext request, OffsetDateTime expiresAt) throws Exception {
PublicClientApplication application = PowerMockito.mock(PublicClientApplication.class);
AtomicBoolean cached = new AtomicBoolean(false);
when(application.acquireToken(any(AuthorizationCodeParameters.class))).thenAnswer(invocation -> {
AuthorizationCodeParameters argument = (AuthorizationCodeParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || !request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
if (argument.redirectUri() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid redirect uri", "InvalidAuthorizationCodeRedirectUri");
});
}
if (argument.authorizationCode() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid authorization code", "InvalidAuthorizationCode");
});
}
cached.set(true);
return TestUtils.getMockAuthenticationResult(token1, expiresAt);
});
PublicClientApplication.Builder builder = PowerMockito.mock(PublicClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(PublicClientApplication.Builder.class).withArguments(CLIENT_ID).thenReturn(builder);
}
private void mockForUsernamePasswordCodeFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn) throws Exception {
PublicClientApplication application = PowerMockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(UserNamePasswordParameters.class)))
.thenAnswer(invocation -> {
UserNamePasswordParameters argument = (UserNamePasswordParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
PublicClientApplication.Builder builder = PowerMockito.mock(PublicClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(PublicClientApplication.Builder.class).withArguments(CLIENT_ID).thenReturn(builder);
}
private void mockForUserRefreshTokenFlow(String token2, TokenRequestContext request2, OffsetDateTime expiresAt) throws Exception {
PublicClientApplication application = PowerMockito.mock(PublicClientApplication.class);
when(application.acquireTokenSilently(any()))
.thenAnswer(invocation -> {
SilentParameters argument = (SilentParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request2.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token2, expiresAt);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
PublicClientApplication.Builder builder = PowerMockito.mock(PublicClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(PublicClientApplication.Builder.class).withArguments(CLIENT_ID).thenReturn(builder);
}
} |
yeah, ASCII covers tokens char range. This is test code. So, if any failures are ever encountered, it'd interesting to look at and we can fix it. | private void mockForMSICodeFlow(String tokenJson) throws Exception {
URL u = PowerMockito.mock(URL.class);
whenNew(URL.class).withAnyArguments().thenReturn(u);
HttpURLConnection huc = PowerMockito.mock(HttpURLConnection.class);
when(u.openConnection()).thenReturn(huc);
PowerMockito.doNothing().when(huc).setRequestMethod(anyString());
PowerMockito.doNothing().when(huc).setRequestMethod(anyString());
PowerMockito.doNothing().when(huc).setRequestMethod(anyString());
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
} | InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset())); | private void mockForMSICodeFlow(String tokenJson) throws Exception {
URL u = PowerMockito.mock(URL.class);
whenNew(URL.class).withAnyArguments().thenReturn(u);
HttpURLConnection huc = PowerMockito.mock(HttpURLConnection.class);
when(u.openConnection()).thenReturn(huc);
PowerMockito.doNothing().when(huc).setRequestMethod(anyString());
PowerMockito.doNothing().when(huc).setRequestMethod(anyString());
PowerMockito.doNothing().when(huc).setRequestMethod(anyString());
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
} | class IdentityClientTests {
private static final String TENANT_ID = "contoso.com";
private static final String CLIENT_ID = UUID.randomUUID().toString();
@Test
public void testValidSecret() throws Exception {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientSecret(secret, request, accessToken, expiresOn);
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).clientSecret(secret).build();
AccessToken token = client.authenticateWithConfidentialClient(request).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testInvalidSecret() throws Exception {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientSecret(secret, request, accessToken, expiresOn);
try {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).clientSecret("bad secret").build();
client.authenticateWithConfidentialClient(request).block();
fail();
} catch (MsalServiceException e) {
Assert.assertEquals("Invalid clientSecret", e.getMessage());
}
}
@Test
public void testValidCertificate() throws Exception {
String pfxPath = getClass().getResource("/keyStore.pfx").getPath();
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientCertificate(request, accessToken, expiresOn);
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.certificatePath(pfxPath).certificatePassword("StrongPass!123").build();
AccessToken token = client.authenticateWithConfidentialClient(request).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testPemCertificate() throws Exception {
String pemPath = getClass().getClassLoader().getResource("certificate.pem").getPath();
if (pemPath.contains(":")) {
pemPath = pemPath.substring(1);
}
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientPemCertificate(accessToken, request, expiresOn);
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).certificatePath(pemPath).build();
AccessToken token = client.authenticateWithConfidentialClient(request).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testInvalidCertificatePassword() throws Exception {
String pfxPath = getClass().getResource("/keyStore.pfx").getPath();
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientCertificate(request, accessToken, expiresOn);
try {
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.certificatePath(pfxPath).certificatePassword("BadPassword").build();
client.authenticateWithConfidentialClient(request).block();
fail();
} catch (Exception e) {
Assert.assertTrue(e.getMessage().contains("password was incorrect"));
}
}
@Test
public void testValidDeviceCodeFlow() throws Exception {
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForDeviceCodeFlow(request, accessToken, expiresOn);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
AccessToken token = client.authenticateWithDeviceCode(request, deviceCodeChallenge -> { /* do nothing */ }).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testValidMSICodeFlow() throws Exception {
Configuration configuration = Configuration.getGlobalConfiguration();
String endpoint = "http:
String secret = "secret";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
configuration.put("MSI_ENDPOINT", endpoint);
configuration.put("MSI_SECRET", secret);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
mockForMSICodeFlow(tokenJson);
IdentityClient client = new IdentityClientBuilder().build();
AccessToken token = client.authenticateToManagedIdentityEndpoint(endpoint, secret, request).block();
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testValidIMDSCodeFlow() throws Exception {
Configuration configuration = Configuration.getGlobalConfiguration();
String endpoint = "http:
String secret = "secret";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
configuration.put("MSI_ENDPOINT", endpoint);
configuration.put("MSI_SECRET", secret);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
mockForIMDSCodeFlow(tokenJson);
IdentityClient client = new IdentityClientBuilder().build();
AccessToken token = client.authenticateToIMDSEndpoint(request).block();
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testAuthorizationCodeFlow() throws Exception {
String token1 = "token1";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
String authCode1 = "authCode1";
URI redirectUri = new URI("http:
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForAuthorizationCodeFlow(token1, request, expiresAt);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithAuthorizationCode(request, authCode1, redirectUri))
.expectNextMatches(accessToken -> token1.equals(accessToken.getToken())
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
}
@Test
public void testUserRefreshTokenflow() throws Exception {
String token1 = "token1";
String token2 = "token1";
TokenRequestContext request2 = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForUserRefreshTokenFlow(token2, request2, expiresAt);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithPublicClientCache(request2, TestUtils.getMockMsalAccount(token1, expiresAt).block()))
.expectNextMatches(accessToken -> token2.equals(accessToken.getToken())
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
}
@Test
public void testUsernamePasswordCodeFlow() throws Exception {
String username = "testuser";
String password = "testpassword";
String token = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForUsernamePasswordCodeFlow(token, request, expiresOn);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithUsernamePassword(request, username, password))
.expectNextMatches(accessToken -> token.equals(accessToken.getToken())
&& expiresOn.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
}
@Test
public void testBrowserAuthenicationCodeFlow() throws Exception {
String username = "testuser";
String password = "testpassword";
String token = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForAuthorizationCodeFlow(token, request, expiresOn);
mocForBrowserAuthenticationCodeFlow();
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithBrowserInteraction(request, 4567))
.expectNextMatches(accessToken -> token.equals(accessToken.getToken())
&& expiresOn.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
}
@Test
public void testOpenUrl() throws Exception {
PowerMockito.mockStatic(Runtime.class);
Runtime rt = PowerMockito.mock(Runtime.class);
when(Runtime.getRuntime()).thenReturn(rt);
Process a = PowerMockito.mock(Process.class);
when(rt.exec(anyString())).thenReturn(a);
IdentityClient client = new IdentityClientBuilder().clientId("dummy").build();
client.openUrl("https:
}
/****** mocks ******/
private void mockForClientSecret(String secret, TokenRequestContext request, String accessToken, OffsetDateTime expiresOn) throws Exception {
ConfidentialClientApplication application = PowerMockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
ConfidentialClientApplication.Builder builder = PowerMockito.mock(ConfidentialClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(ConfidentialClientApplication.Builder.class).withAnyArguments().thenAnswer(invocation -> {
String cid = (String) invocation.getArguments()[0];
IClientSecret clientSecret = (IClientSecret) invocation.getArguments()[1];
if (!CLIENT_ID.equals(cid)) {
throw new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId");
}
if (!secret.equals(clientSecret.clientSecret())) {
throw new MsalServiceException("Invalid clientSecret", "InvalidClientSecret");
}
return builder;
});
}
private void mockForClientCertificate(TokenRequestContext request, String accessToken, OffsetDateTime expiresOn) throws Exception {
ConfidentialClientApplication application = PowerMockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
ConfidentialClientApplication.Builder builder = PowerMockito.mock(ConfidentialClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(ConfidentialClientApplication.Builder.class).withAnyArguments().thenAnswer(invocation -> {
String cid = (String) invocation.getArguments()[0];
IClientCredential keyCredential = (IClientCredential) invocation.getArguments()[1];
if (!CLIENT_ID.equals(cid)) {
throw new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId");
}
if (keyCredential == null) {
throw new MsalServiceException("Invalid clientCertificate", "InvalidClientCertificate");
}
return builder;
});
}
private void mockForDeviceCodeFlow(TokenRequestContext request, String accessToken, OffsetDateTime expiresOn) throws Exception {
PublicClientApplication application = PowerMockito.mock(PublicClientApplication.class);
AtomicBoolean cached = new AtomicBoolean(false);
when(application.acquireToken(any(DeviceCodeFlowParameters.class))).thenAnswer(invocation -> {
DeviceCodeFlowParameters argument = (DeviceCodeFlowParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || !request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
if (argument.deviceCodeConsumer() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid device code consumer", "InvalidDeviceCodeConsumer");
});
}
cached.set(true);
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
});
PublicClientApplication.Builder builder = PowerMockito.mock(PublicClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(PublicClientApplication.Builder.class).withArguments(CLIENT_ID).thenReturn(builder);
}
private void mockForClientPemCertificate(String accessToken, TokenRequestContext request, OffsetDateTime expiresOn) throws Exception {
ConfidentialClientApplication application = PowerMockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
ConfidentialClientApplication.Builder builder = PowerMockito.mock(ConfidentialClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(ConfidentialClientApplication.Builder.class).withAnyArguments().thenAnswer(invocation -> {
String cid = (String) invocation.getArguments()[0];
if (!CLIENT_ID.equals(cid)) {
throw new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId");
}
return builder;
});
PowerMockito.mockStatic(CertificateUtil.class);
PowerMockito.mockStatic(ClientCredentialFactory.class);
PrivateKey privateKey = PowerMockito.mock(PrivateKey.class);
IClientCertificate clientCertificate = PowerMockito.mock(IClientCertificate.class);
when(CertificateUtil.privateKeyFromPem(any())).thenReturn(privateKey);
when(ClientCredentialFactory.createFromCertificate(any(PrivateKey.class), any(X509Certificate.class)))
.thenReturn(clientCertificate);
}
private void mockForIMDSCodeFlow(String tokenJson) throws Exception {
URL u = PowerMockito.mock(URL.class);
whenNew(URL.class).withAnyArguments().thenReturn(u);
HttpURLConnection huc = PowerMockito.mock(HttpURLConnection.class);
when(u.openConnection()).thenReturn(huc);
PowerMockito.doNothing().when(huc).setRequestMethod(anyString());
PowerMockito.doNothing().when(huc).setConnectTimeout(ArgumentMatchers.anyInt());
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
}
private void mocForBrowserAuthenticationCodeFlow() throws Exception {
AuthorizationCodeListener authorizationCodeListener = PowerMockito.mock(AuthorizationCodeListener.class);
whenNew(AuthorizationCodeListener.class).withAnyArguments().thenReturn((authorizationCodeListener));
when(authorizationCodeListener.listen()).thenReturn(Mono.just("auth-Code"));
when(authorizationCodeListener.dispose()).thenReturn(Mono.empty());
when(authorizationCodeListener.dispose()).thenReturn(Mono.empty());
}
private void mockForAuthorizationCodeFlow(String token1, TokenRequestContext request, OffsetDateTime expiresAt) throws Exception {
PublicClientApplication application = PowerMockito.mock(PublicClientApplication.class);
AtomicBoolean cached = new AtomicBoolean(false);
when(application.acquireToken(any(AuthorizationCodeParameters.class))).thenAnswer(invocation -> {
AuthorizationCodeParameters argument = (AuthorizationCodeParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || !request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
if (argument.redirectUri() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid redirect uri", "InvalidAuthorizationCodeRedirectUri");
});
}
if (argument.authorizationCode() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid authorization code", "InvalidAuthorizationCode");
});
}
cached.set(true);
return TestUtils.getMockAuthenticationResult(token1, expiresAt);
});
PublicClientApplication.Builder builder = PowerMockito.mock(PublicClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(PublicClientApplication.Builder.class).withArguments(CLIENT_ID).thenReturn(builder);
}
private void mockForUsernamePasswordCodeFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn) throws Exception {
PublicClientApplication application = PowerMockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(UserNamePasswordParameters.class)))
.thenAnswer(invocation -> {
UserNamePasswordParameters argument = (UserNamePasswordParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
PublicClientApplication.Builder builder = PowerMockito.mock(PublicClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(PublicClientApplication.Builder.class).withArguments(CLIENT_ID).thenReturn(builder);
}
private void mockForUserRefreshTokenFlow(String token2, TokenRequestContext request2, OffsetDateTime expiresAt) throws Exception {
PublicClientApplication application = PowerMockito.mock(PublicClientApplication.class);
when(application.acquireTokenSilently(any()))
.thenAnswer(invocation -> {
SilentParameters argument = (SilentParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request2.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token2, expiresAt);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
PublicClientApplication.Builder builder = PowerMockito.mock(PublicClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(PublicClientApplication.Builder.class).withArguments(CLIENT_ID).thenReturn(builder);
}
} | class IdentityClientTests {
private static final String TENANT_ID = "contoso.com";
private static final String CLIENT_ID = UUID.randomUUID().toString();
@Test
public void testValidSecret() throws Exception {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientSecret(secret, request, accessToken, expiresOn);
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).clientSecret(secret).build();
AccessToken token = client.authenticateWithConfidentialClient(request).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testInvalidSecret() throws Exception {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientSecret(secret, request, accessToken, expiresOn);
try {
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).clientSecret("bad secret").build();
client.authenticateWithConfidentialClient(request).block();
fail();
} catch (MsalServiceException e) {
Assert.assertEquals("Invalid clientSecret", e.getMessage());
}
}
@Test
public void testValidCertificate() throws Exception {
String pfxPath = getClass().getResource("/keyStore.pfx").getPath();
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientCertificate(request, accessToken, expiresOn);
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.certificatePath(pfxPath).certificatePassword("StrongPass!123").build();
AccessToken token = client.authenticateWithConfidentialClient(request).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testPemCertificate() throws Exception {
String pemPath = getClass().getClassLoader().getResource("certificate.pem").getPath();
if (pemPath.contains(":")) {
pemPath = pemPath.substring(1);
}
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientPemCertificate(accessToken, request, expiresOn);
IdentityClient client = new IdentityClientBuilder()
.tenantId(TENANT_ID).clientId(CLIENT_ID).certificatePath(pemPath).build();
AccessToken token = client.authenticateWithConfidentialClient(request).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testInvalidCertificatePassword() throws Exception {
String pfxPath = getClass().getResource("/keyStore.pfx").getPath();
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForClientCertificate(request, accessToken, expiresOn);
try {
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID)
.certificatePath(pfxPath).certificatePassword("BadPassword").build();
client.authenticateWithConfidentialClient(request).block();
fail();
} catch (Exception e) {
Assert.assertTrue(e.getMessage().contains("password was incorrect"));
}
}
@Test
public void testValidDeviceCodeFlow() throws Exception {
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForDeviceCodeFlow(request, accessToken, expiresOn);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
AccessToken token = client.authenticateWithDeviceCode(request, deviceCodeChallenge -> { /* do nothing */ }).block();
Assert.assertEquals(accessToken, token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testValidMSICodeFlow() throws Exception {
Configuration configuration = Configuration.getGlobalConfiguration();
String endpoint = "http:
String secret = "secret";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
configuration.put("MSI_ENDPOINT", endpoint);
configuration.put("MSI_SECRET", secret);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
mockForMSICodeFlow(tokenJson);
IdentityClient client = new IdentityClientBuilder().build();
AccessToken token = client.authenticateToManagedIdentityEndpoint(endpoint, secret, request).block();
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testValidIMDSCodeFlow() throws Exception {
Configuration configuration = Configuration.getGlobalConfiguration();
String endpoint = "http:
String secret = "secret";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
configuration.put("MSI_ENDPOINT", endpoint);
configuration.put("MSI_SECRET", secret);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy H:mm:ss XXX");
String tokenJson = "{ \"access_token\" : \"token1\", \"expires_on\" : \"" + expiresOn.format(dtf) + "\" }";
mockForIMDSCodeFlow(tokenJson);
IdentityClient client = new IdentityClientBuilder().build();
AccessToken token = client.authenticateToIMDSEndpoint(request).block();
Assert.assertEquals("token1", token.getToken());
Assert.assertEquals(expiresOn.getSecond(), token.getExpiresAt().getSecond());
}
@Test
public void testAuthorizationCodeFlow() throws Exception {
String token1 = "token1";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
String authCode1 = "authCode1";
URI redirectUri = new URI("http:
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForAuthorizationCodeFlow(token1, request, expiresAt);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithAuthorizationCode(request, authCode1, redirectUri))
.expectNextMatches(accessToken -> token1.equals(accessToken.getToken())
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
}
@Test
public void testUserRefreshTokenflow() throws Exception {
String token1 = "token1";
String token2 = "token1";
TokenRequestContext request2 = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForUserRefreshTokenFlow(token2, request2, expiresAt);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithPublicClientCache(request2, TestUtils.getMockMsalAccount(token1, expiresAt).block()))
.expectNextMatches(accessToken -> token2.equals(accessToken.getToken())
&& expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
}
@Test
public void testUsernamePasswordCodeFlow() throws Exception {
String username = "testuser";
String password = "testpassword";
String token = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForUsernamePasswordCodeFlow(token, request, expiresOn);
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithUsernamePassword(request, username, password))
.expectNextMatches(accessToken -> token.equals(accessToken.getToken())
&& expiresOn.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
}
@Test
public void testBrowserAuthenicationCodeFlow() throws Exception {
String username = "testuser";
String password = "testpassword";
String token = "token";
TokenRequestContext request = new TokenRequestContext().addScopes("https:
OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
mockForAuthorizationCodeFlow(token, request, expiresOn);
mocForBrowserAuthenticationCodeFlow();
IdentityClientOptions options = new IdentityClientOptions();
IdentityClient client = new IdentityClientBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).identityClientOptions(options).build();
StepVerifier.create(client.authenticateWithBrowserInteraction(request, 4567))
.expectNextMatches(accessToken -> token.equals(accessToken.getToken())
&& expiresOn.getSecond() == accessToken.getExpiresAt().getSecond())
.verifyComplete();
}
@Test
public void testOpenUrl() throws Exception {
PowerMockito.mockStatic(Runtime.class);
Runtime rt = PowerMockito.mock(Runtime.class);
when(Runtime.getRuntime()).thenReturn(rt);
Process a = PowerMockito.mock(Process.class);
when(rt.exec(anyString())).thenReturn(a);
IdentityClient client = new IdentityClientBuilder().clientId("dummy").build();
client.openUrl("https:
}
/****** mocks ******/
private void mockForClientSecret(String secret, TokenRequestContext request, String accessToken, OffsetDateTime expiresOn) throws Exception {
ConfidentialClientApplication application = PowerMockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
ConfidentialClientApplication.Builder builder = PowerMockito.mock(ConfidentialClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(ConfidentialClientApplication.Builder.class).withAnyArguments().thenAnswer(invocation -> {
String cid = (String) invocation.getArguments()[0];
IClientSecret clientSecret = (IClientSecret) invocation.getArguments()[1];
if (!CLIENT_ID.equals(cid)) {
throw new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId");
}
if (!secret.equals(clientSecret.clientSecret())) {
throw new MsalServiceException("Invalid clientSecret", "InvalidClientSecret");
}
return builder;
});
}
private void mockForClientCertificate(TokenRequestContext request, String accessToken, OffsetDateTime expiresOn) throws Exception {
ConfidentialClientApplication application = PowerMockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
ConfidentialClientApplication.Builder builder = PowerMockito.mock(ConfidentialClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(ConfidentialClientApplication.Builder.class).withAnyArguments().thenAnswer(invocation -> {
String cid = (String) invocation.getArguments()[0];
IClientCredential keyCredential = (IClientCredential) invocation.getArguments()[1];
if (!CLIENT_ID.equals(cid)) {
throw new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId");
}
if (keyCredential == null) {
throw new MsalServiceException("Invalid clientCertificate", "InvalidClientCertificate");
}
return builder;
});
}
private void mockForDeviceCodeFlow(TokenRequestContext request, String accessToken, OffsetDateTime expiresOn) throws Exception {
PublicClientApplication application = PowerMockito.mock(PublicClientApplication.class);
AtomicBoolean cached = new AtomicBoolean(false);
when(application.acquireToken(any(DeviceCodeFlowParameters.class))).thenAnswer(invocation -> {
DeviceCodeFlowParameters argument = (DeviceCodeFlowParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || !request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
if (argument.deviceCodeConsumer() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid device code consumer", "InvalidDeviceCodeConsumer");
});
}
cached.set(true);
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
});
PublicClientApplication.Builder builder = PowerMockito.mock(PublicClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(PublicClientApplication.Builder.class).withArguments(CLIENT_ID).thenReturn(builder);
}
private void mockForClientPemCertificate(String accessToken, TokenRequestContext request, OffsetDateTime expiresOn) throws Exception {
ConfidentialClientApplication application = PowerMockito.mock(ConfidentialClientApplication.class);
when(application.acquireToken(any(ClientCredentialParameters.class))).thenAnswer(invocation -> {
ClientCredentialParameters argument = (ClientCredentialParameters) invocation.getArguments()[0];
if (argument.scopes().size() == 1 && request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(accessToken, expiresOn);
} else {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
});
ConfidentialClientApplication.Builder builder = PowerMockito.mock(ConfidentialClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(ConfidentialClientApplication.Builder.class).withAnyArguments().thenAnswer(invocation -> {
String cid = (String) invocation.getArguments()[0];
if (!CLIENT_ID.equals(cid)) {
throw new MsalServiceException("Invalid CLIENT_ID", "InvalidClientId");
}
return builder;
});
PowerMockito.mockStatic(CertificateUtil.class);
PowerMockito.mockStatic(ClientCredentialFactory.class);
PrivateKey privateKey = PowerMockito.mock(PrivateKey.class);
IClientCertificate clientCertificate = PowerMockito.mock(IClientCertificate.class);
when(CertificateUtil.privateKeyFromPem(any())).thenReturn(privateKey);
when(ClientCredentialFactory.createFromCertificate(any(PrivateKey.class), any(X509Certificate.class)))
.thenReturn(clientCertificate);
}
private void mockForIMDSCodeFlow(String tokenJson) throws Exception {
URL u = PowerMockito.mock(URL.class);
whenNew(URL.class).withAnyArguments().thenReturn(u);
HttpURLConnection huc = PowerMockito.mock(HttpURLConnection.class);
when(u.openConnection()).thenReturn(huc);
PowerMockito.doNothing().when(huc).setRequestMethod(anyString());
PowerMockito.doNothing().when(huc).setConnectTimeout(ArgumentMatchers.anyInt());
InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset()));
when(huc.getInputStream()).thenReturn(inputStream);
}
private void mocForBrowserAuthenticationCodeFlow() throws Exception {
AuthorizationCodeListener authorizationCodeListener = PowerMockito.mock(AuthorizationCodeListener.class);
whenNew(AuthorizationCodeListener.class).withAnyArguments().thenReturn((authorizationCodeListener));
when(authorizationCodeListener.listen()).thenReturn(Mono.just("auth-Code"));
when(authorizationCodeListener.dispose()).thenReturn(Mono.empty());
when(authorizationCodeListener.dispose()).thenReturn(Mono.empty());
}
private void mockForAuthorizationCodeFlow(String token1, TokenRequestContext request, OffsetDateTime expiresAt) throws Exception {
PublicClientApplication application = PowerMockito.mock(PublicClientApplication.class);
AtomicBoolean cached = new AtomicBoolean(false);
when(application.acquireToken(any(AuthorizationCodeParameters.class))).thenAnswer(invocation -> {
AuthorizationCodeParameters argument = (AuthorizationCodeParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || !request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid request", "InvalidScopes");
});
}
if (argument.redirectUri() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid redirect uri", "InvalidAuthorizationCodeRedirectUri");
});
}
if (argument.authorizationCode() == null) {
return CompletableFuture.runAsync(() -> {
throw new MsalServiceException("Invalid authorization code", "InvalidAuthorizationCode");
});
}
cached.set(true);
return TestUtils.getMockAuthenticationResult(token1, expiresAt);
});
PublicClientApplication.Builder builder = PowerMockito.mock(PublicClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(PublicClientApplication.Builder.class).withArguments(CLIENT_ID).thenReturn(builder);
}
private void mockForUsernamePasswordCodeFlow(String token, TokenRequestContext request, OffsetDateTime expiresOn) throws Exception {
PublicClientApplication application = PowerMockito.mock(PublicClientApplication.class);
when(application.acquireToken(any(UserNamePasswordParameters.class)))
.thenAnswer(invocation -> {
UserNamePasswordParameters argument = (UserNamePasswordParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token, expiresOn);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
PublicClientApplication.Builder builder = PowerMockito.mock(PublicClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(PublicClientApplication.Builder.class).withArguments(CLIENT_ID).thenReturn(builder);
}
private void mockForUserRefreshTokenFlow(String token2, TokenRequestContext request2, OffsetDateTime expiresAt) throws Exception {
PublicClientApplication application = PowerMockito.mock(PublicClientApplication.class);
when(application.acquireTokenSilently(any()))
.thenAnswer(invocation -> {
SilentParameters argument = (SilentParameters) invocation.getArguments()[0];
if (argument.scopes().size() != 1 || request2.getScopes().get(0).equals(argument.scopes().iterator().next())) {
return TestUtils.getMockAuthenticationResult(token2, expiresAt);
} else {
throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
}
});
PublicClientApplication.Builder builder = PowerMockito.mock(PublicClientApplication.Builder.class);
when(builder.build()).thenReturn(application);
when(builder.authority(any())).thenReturn(builder);
when(builder.httpClient(any())).thenReturn(builder);
whenNew(PublicClientApplication.Builder.class).withArguments(CLIENT_ID).thenReturn(builder);
}
} |
I don't think we need to do this. We should deprecate the HttpLogOptions one, and have it take lower precedence to the clientOptions one (so we only use it when the clientOptions one is not set). | private HttpPipeline createPipeline() {
if (pipeline != null) {
return pipeline;
}
final Configuration buildConfiguration = configuration == null
? Configuration.getGlobalConfiguration().clone()
: configuration;
final List<HttpPipelinePolicy> httpPolicies = new ArrayList<>();
final String clientName = properties.getOrDefault("name", "UnknownName");
final String clientVersion = properties.getOrDefault("version", "UnknownVersion");
final String applicationId = CoreUtils.validateApplicationId(httpLogOptions, clientOptions,
new IllegalStateException("applicationId should be same in httpLogOptions and clientOptions."));
httpPolicies.add(new UserAgentPolicy(applicationId, clientName, clientVersion,
buildConfiguration));
httpPolicies.add(new ServiceBusTokenCredentialHttpPolicy(tokenCredential));
httpPolicies.add(new AddHeadersFromContextPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(httpPolicies);
httpPolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy);
httpPolicies.addAll(userPolicies);
httpPolicies.add(new HttpLoggingPolicy(httpLogOptions));
HttpPolicyProviders.addAfterRetryPolicies(httpPolicies);
return new HttpPipelineBuilder()
.policies(httpPolicies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
} | new IllegalStateException("applicationId should be same in httpLogOptions and clientOptions.")); | private HttpPipeline createPipeline() {
if (pipeline != null) {
return pipeline;
}
final Configuration buildConfiguration = configuration == null
? Configuration.getGlobalConfiguration().clone()
: configuration;
final List<HttpPipelinePolicy> httpPolicies = new ArrayList<>();
final String clientName = properties.getOrDefault("name", "UnknownName");
final String clientVersion = properties.getOrDefault("version", "UnknownVersion");
String logApplicationId = null;
if (httpLogOptions != null) {
logApplicationId = httpLogOptions.getApplicationId();
}
String clientApplicationId = null;
if (clientOptions != null && clientOptions.getApplicationId() != null) {
clientApplicationId = clientOptions.getApplicationId();
}
if (logApplicationId != null && clientApplicationId != null
&& !logApplicationId.equalsIgnoreCase(clientApplicationId)) {
throw logger.logExceptionAsError(new IllegalStateException(
"'httpLogOptions.getApplicationId() and clientOptions.getApplicationId()' cannot be different."));
}
final String applicationId = clientApplicationId != null ? clientApplicationId : logApplicationId;
httpPolicies.add(new UserAgentPolicy(applicationId, clientName, clientVersion,
buildConfiguration));
httpPolicies.add(new ServiceBusTokenCredentialHttpPolicy(tokenCredential));
httpPolicies.add(new AddHeadersFromContextPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(httpPolicies);
httpPolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy);
httpPolicies.addAll(userPolicies);
httpPolicies.add(new HttpLoggingPolicy(httpLogOptions));
HttpPolicyProviders.addAfterRetryPolicies(httpPolicies);
return new HttpPipelineBuilder()
.policies(httpPolicies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
} | class ServiceBusAdministrationClientBuilder {
private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationClientBuilder.class);
private final ServiceBusManagementSerializer serializer = new ServiceBusManagementSerializer();
private final List<HttpPipelinePolicy> userPolicies = new ArrayList<>();
private final Map<String, String> properties =
CoreUtils.getProperties("azure-messaging-servicebus.properties");
private Configuration configuration;
private String endpoint;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions = new HttpLogOptions();
private HttpPipeline pipeline;
private HttpPipelinePolicy retryPolicy;
private TokenCredential tokenCredential;
private ServiceBusServiceVersion serviceVersion;
private ClientOptions clientOptions;
/**
* Constructs a builder with the default parameters.
*/
public ServiceBusAdministrationClientBuilder() {
}
/**
* Creates a {@link ServiceBusAdministrationAsyncClient} based on options set in the builder. Every time {@code
* buildAsyncClient} is invoked, a new instance of the client is created.
*
* <p>If {@link
* {@link
* other builder settings are ignored.</p>
*
* @return A {@link ServiceBusAdministrationAsyncClient} with the options set in the builder.
* @throws NullPointerException if {@code endpoint} has not been set. This is automatically set when {@link
*
* @throws IllegalStateException If {@link
* applicationId if set in both {@code httpLogOptions} and {@code clientOptions} and not same.
*/
public ServiceBusAdministrationAsyncClient buildAsyncClient() {
if (endpoint == null) {
throw logger.logExceptionAsError(new NullPointerException("'endpoint' cannot be null."));
}
final ServiceBusServiceVersion apiVersion = serviceVersion == null
? ServiceBusServiceVersion.getLatest()
: serviceVersion;
final HttpPipeline httpPipeline = createPipeline();
final ServiceBusManagementClientImpl client = new ServiceBusManagementClientImplBuilder()
.pipeline(httpPipeline)
.serializerAdapter(serializer)
.endpoint(endpoint)
.apiVersion(apiVersion.getVersion())
.buildClient();
return new ServiceBusAdministrationAsyncClient(client, serializer);
}
/**
* Creates a {@link ServiceBusAdministrationClient} based on options set in the builder. Every time {@code
* buildAsyncClient} is invoked, a new instance of the client is created.
*
* <p>If {@link
* {@link
* other builder settings are ignored.</p>
*
* @return A {@link ServiceBusAdministrationClient} with the options set in the builder.
* @throws NullPointerException if {@code endpoint} has not been set. This is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
*/
public ServiceBusAdministrationClient buildClient() {
return new ServiceBusAdministrationClient(buildAsyncClient());
}
/**
* Adds a policy to the set of existing policies that are executed after required policies.
*
* @param policy The retry policy for service requests.
*
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
* @throws NullPointerException If {@code policy} is {@code null}.
*/
public ServiceBusAdministrationClientBuilder addPolicy(HttpPipelinePolicy policy) {
Objects.requireNonNull(policy);
userPolicies.add(policy);
return this;
}
/**
* Sets the service endpoint for the Service Bus namespace.
*
* @param endpoint The URL of the Service Bus namespace.
*
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
* @throws NullPointerException if {@code endpoint} is null.
* @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL.
*/
public ServiceBusAdministrationClientBuilder endpoint(String endpoint) {
final URL url;
try {
url = new URL(Objects.requireNonNull(endpoint, "'endpoint' cannot be null."));
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL"));
}
this.endpoint = url.getHost();
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
*
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
*/
public ServiceBusAdministrationClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @param connectionString Connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
* @throws NullPointerException If {@code connectionString} is {@code null}.
* @throws IllegalArgumentException If {@code connectionString} is an entity specific connection string, and not
* a {@code connectionString} for the Service Bus namespace.
*/
public ServiceBusAdministrationClientBuilder connectionString(String connectionString) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
final TokenCredential tokenCredential;
try {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ServiceBusConstants.TOKEN_VALIDITY);
} catch (Exception e) {
throw logger.logExceptionAsError(
new AzureException("Could not create the ServiceBusSharedKeyCredential.", e));
}
this.endpoint = properties.getEndpoint().getHost();
if (properties.getEntityPath() != null && !properties.getEntityPath().isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'connectionString' cannot contain an EntityPath. It should be a namespace connection string."));
}
return credential(properties.getEndpoint().getHost(), tokenCredential);
}
/**
* Sets the credential used to authenticate HTTP requests to the Service Bus namespace.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link TokenCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
*/
public ServiceBusAdministrationClientBuilder credential(String fullyQualifiedNamespace,
TokenCredential credential) {
this.endpoint = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.tokenCredential = Objects.requireNonNull(credential, "'credential' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
/**
* Sets the HTTP client to use for sending and receiving requests to and from the service.
*
* @param client The HTTP client to use for requests.
*
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
*/
public ServiceBusAdministrationClientBuilder httpClient(HttpClient client) {
if (this.httpClient != null && client == null) {
logger.info("HttpClient is being set to 'null' when it was previously configured.");
}
this.httpClient = client;
return this;
}
/**
* Sets the logging configuration for HTTP requests and responses.
*
* <p>If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
*
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
*/
public ServiceBusAdministrationClientBuilder httpLogOptions(HttpLogOptions logOptions) {
httpLogOptions = logOptions;
return this;
}
/**
* Sets various options on the client. For example application-id which will be used in user-agent while creating
* connection with Azure Service Bus.
*
* @param clientOptions to be set on the client.
*
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
*/
public ServiceBusAdministrationClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the HTTP pipeline to use for the service client.
*
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
* ServiceBusAdministrationClientBuilder
* or {@link ServiceBusAdministrationAsyncClient}.
*
* @param pipeline The HTTP pipeline to use for sending service requests and receiving responses.
*
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
*/
public ServiceBusAdministrationClientBuilder pipeline(HttpPipeline pipeline) {
if (this.pipeline != null && pipeline == null) {
logger.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.pipeline = pipeline;
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used when each request is sent.
*
* The default retry policy will be used if not provided {@link
* to build {@link ServiceBusAdministrationClient} or {@link ServiceBusAdministrationAsyncClient}.
*
* @param retryPolicy user's retry policy applied to each request.
*
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
*/
public ServiceBusAdministrationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link ServiceBusServiceVersion} that is used. By default {@link ServiceBusServiceVersion
* is used when none is specified.
*
* @param serviceVersion Service version to use.
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
*/
public ServiceBusAdministrationClientBuilder serviceVersion(ServiceBusServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Builds a new HTTP pipeline if none is set, or returns a user-provided one.
*
* @return A new HTTP pipeline or the user-defined one from {@link
* @throws IllegalStateException if applicationId is not same in httpLogOptions and clientOptions.
*/
} | class ServiceBusAdministrationClientBuilder {
private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationClientBuilder.class);
private final ServiceBusManagementSerializer serializer = new ServiceBusManagementSerializer();
private final List<HttpPipelinePolicy> userPolicies = new ArrayList<>();
private final Map<String, String> properties =
CoreUtils.getProperties("azure-messaging-servicebus.properties");
private Configuration configuration;
private String endpoint;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions = new HttpLogOptions();
private HttpPipeline pipeline;
private HttpPipelinePolicy retryPolicy;
private TokenCredential tokenCredential;
private ServiceBusServiceVersion serviceVersion;
private ClientOptions clientOptions;
/**
* Constructs a builder with the default parameters.
*/
public ServiceBusAdministrationClientBuilder() {
}
/**
* Creates a {@link ServiceBusAdministrationAsyncClient} based on options set in the builder. Every time {@code
* buildAsyncClient} is invoked, a new instance of the client is created.
*
* <p>If {@link
* {@link
* other builder settings are ignored.</p>
*
* @return A {@link ServiceBusAdministrationAsyncClient} with the options set in the builder.
* @throws NullPointerException if {@code endpoint} has not been set. This is automatically set when {@link
*
* @throws IllegalStateException If {@link
* applicationId if set in both {@code httpLogOptions} and {@code clientOptions} and not same.
*/
public ServiceBusAdministrationAsyncClient buildAsyncClient() {
if (endpoint == null) {
throw logger.logExceptionAsError(new NullPointerException("'endpoint' cannot be null."));
}
final ServiceBusServiceVersion apiVersion = serviceVersion == null
? ServiceBusServiceVersion.getLatest()
: serviceVersion;
final HttpPipeline httpPipeline = createPipeline();
final ServiceBusManagementClientImpl client = new ServiceBusManagementClientImplBuilder()
.pipeline(httpPipeline)
.serializerAdapter(serializer)
.endpoint(endpoint)
.apiVersion(apiVersion.getVersion())
.buildClient();
return new ServiceBusAdministrationAsyncClient(client, serializer);
}
/**
* Creates a {@link ServiceBusAdministrationClient} based on options set in the builder. Every time {@code
* buildAsyncClient} is invoked, a new instance of the client is created.
*
* <p>If {@link
* {@link
* other builder settings are ignored.</p>
*
* @return A {@link ServiceBusAdministrationClient} with the options set in the builder.
* @throws NullPointerException if {@code endpoint} has not been set. This is automatically set when {@link
*
*
* @throws IllegalStateException If {@link
*/
public ServiceBusAdministrationClient buildClient() {
return new ServiceBusAdministrationClient(buildAsyncClient());
}
/**
* Adds a policy to the set of existing policies that are executed after required policies.
*
* @param policy The retry policy for service requests.
*
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
* @throws NullPointerException If {@code policy} is {@code null}.
*/
public ServiceBusAdministrationClientBuilder addPolicy(HttpPipelinePolicy policy) {
Objects.requireNonNull(policy);
userPolicies.add(policy);
return this;
}
/**
* Sets the service endpoint for the Service Bus namespace.
*
* @param endpoint The URL of the Service Bus namespace.
*
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
* @throws NullPointerException if {@code endpoint} is null.
* @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL.
*/
public ServiceBusAdministrationClientBuilder endpoint(String endpoint) {
final URL url;
try {
url = new URL(Objects.requireNonNull(endpoint, "'endpoint' cannot be null."));
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL"));
}
this.endpoint = url.getHost();
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
*
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
*/
public ServiceBusAdministrationClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @param connectionString Connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
* @throws NullPointerException If {@code connectionString} is {@code null}.
* @throws IllegalArgumentException If {@code connectionString} is an entity specific connection string, and not
* a {@code connectionString} for the Service Bus namespace.
*/
public ServiceBusAdministrationClientBuilder connectionString(String connectionString) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
final TokenCredential tokenCredential;
try {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ServiceBusConstants.TOKEN_VALIDITY);
} catch (Exception e) {
throw logger.logExceptionAsError(
new AzureException("Could not create the ServiceBusSharedKeyCredential.", e));
}
this.endpoint = properties.getEndpoint().getHost();
if (properties.getEntityPath() != null && !properties.getEntityPath().isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'connectionString' cannot contain an EntityPath. It should be a namespace connection string."));
}
return credential(properties.getEndpoint().getHost(), tokenCredential);
}
/**
* Sets the credential used to authenticate HTTP requests to the Service Bus namespace.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link TokenCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
*/
public ServiceBusAdministrationClientBuilder credential(String fullyQualifiedNamespace,
TokenCredential credential) {
this.endpoint = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.tokenCredential = Objects.requireNonNull(credential, "'credential' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
/**
* Sets the HTTP client to use for sending and receiving requests to and from the service.
*
* @param client The HTTP client to use for requests.
*
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
*/
public ServiceBusAdministrationClientBuilder httpClient(HttpClient client) {
if (this.httpClient != null && client == null) {
logger.info("HttpClient is being set to 'null' when it was previously configured.");
}
this.httpClient = client;
return this;
}
/**
* Sets the logging configuration for HTTP requests and responses.
*
* <p>If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
*
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
*/
public ServiceBusAdministrationClientBuilder httpLogOptions(HttpLogOptions logOptions) {
httpLogOptions = logOptions;
return this;
}
/**
* Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting
* {@code applicationId} using {@link ClientOptions
* for telemetry/monitoring purpose.
* <p>
* More About <a href="https:
*
* @param clientOptions to be set on the client.
*
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
* @see ClientOptions
*/
public ServiceBusAdministrationClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the HTTP pipeline to use for the service client.
*
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
* ServiceBusAdministrationClientBuilder
* or {@link ServiceBusAdministrationAsyncClient}.
*
* @param pipeline The HTTP pipeline to use for sending service requests and receiving responses.
*
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
*/
public ServiceBusAdministrationClientBuilder pipeline(HttpPipeline pipeline) {
if (this.pipeline != null && pipeline == null) {
logger.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.pipeline = pipeline;
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used when each request is sent.
*
* The default retry policy will be used if not provided {@link
* to build {@link ServiceBusAdministrationClient} or {@link ServiceBusAdministrationAsyncClient}.
*
* @param retryPolicy user's retry policy applied to each request.
*
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
*/
public ServiceBusAdministrationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link ServiceBusServiceVersion} that is used. By default {@link ServiceBusServiceVersion
* is used when none is specified.
*
* @param serviceVersion Service version to use.
* @return The updated {@link ServiceBusAdministrationClientBuilder} object.
*/
public ServiceBusAdministrationClientBuilder serviceVersion(ServiceBusServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Builds a new HTTP pipeline if none is set, or returns a user-provided one.
*
* @return A new HTTP pipeline or the user-defined one from {@link
* @throws IllegalStateException if applicationId is not same in httpLogOptions and clientOptions.
*/
} |
nit: I'm not a fan of multiple nested if statements because it makes things harder to read if it's not necessary. Can we bounce early? ```java if (CoreUtils.isNullorEmpty(applicationId)) { return this; } ... // other stuff. ``` | public ClientOptions setApplicationId(String applicationId) {
if (!CoreUtils.isNullOrEmpty(applicationId)) {
if (applicationId.length() > MAX_APPLICATION_ID_LENGTH) {
throw logger
.logExceptionAsError(new IllegalArgumentException("'applicationId' length cannot be greater than "
+ MAX_APPLICATION_ID_LENGTH));
} else if (applicationId.contains(" ")) {
throw logger
.logExceptionAsError(new IllegalArgumentException("'applicationId' must not contain a space."));
} else {
this.applicationId = applicationId;
}
}
return this;
} | if (!CoreUtils.isNullOrEmpty(applicationId)) { | public ClientOptions setApplicationId(String applicationId) {
if (CoreUtils.isNullOrEmpty(applicationId)) {
this.applicationId = applicationId;
return this;
}
if (applicationId.length() > MAX_APPLICATION_ID_LENGTH) {
throw logger
.logExceptionAsError(new IllegalArgumentException("'applicationId' length cannot be greater than "
+ MAX_APPLICATION_ID_LENGTH));
} else if (applicationId.contains(" ")) {
throw logger
.logExceptionAsError(new IllegalArgumentException("'applicationId' must not contain a space."));
} else {
this.applicationId = applicationId;
}
return this;
} | class ClientOptions {
private final ClientLogger logger = new ClientLogger(ClientOptions.class);
private final Map<String, Header> headers = new ConcurrentHashMap<>();
private static final int MAX_APPLICATION_ID_LENGTH = 24;
private String applicationId;
/**
* Gets the applicationId.
*
* @return The applicationId.
*/
public String getApplicationId() {
return applicationId;
}
/**
* Sets the applicationId provided.
*
* @param applicationId to be set.
* @return updated {@link ClientOptions}.
*
*/
/**
* Sets the provided headers.
*
* @param headers headers to be set.
* @return updated {@link ClientOptions}.
*
* @throws NullPointerException if {@code headers} is null.
*/
public ClientOptions headers(Iterable<Header> headers) {
Objects.requireNonNull(headers, "'headers' cannot be null.");
for (final Header header : headers) {
this.headers.put(formatKey(header.getName()), header);
}
return this;
}
/**
* Sets a {@link Header header} with the given name and value or append the {@code value} separated by {@code comma}
* if the {@link Header} exists for given {@code name}.
*
* @param name the name
* @param value the value
* @return The updated ClientOptions object
*
* @throws NullPointerException if {@code name} or {@code value} is null.
*/
public ClientOptions addHeader(String name, String value) {
Objects.requireNonNull(name, "'name' cannot be null.");
Objects.requireNonNull(value, "'value' cannot be null.");
Header existing = get(name);
if (existing == null) {
this.headers.put(formatKey(name), new Header(name, value));
} else {
existing.addValue(value);
}
return this;
}
/**
* Gets the {@link Header header} for the provided header name. {@code Null} is returned if the header isn't
* found.
*
* @param name the name of the header to find.
* @return the header if found, null otherwise.
*
* @throws NullPointerException if {@code name} is null.
*/
public Header get(String name) {
Objects.requireNonNull(name, "'name' cannot be null.");
return headers.get(formatKey(name));
}
/**
* Removes the {@link Header header} with the provided header name. {@code Null} is returned if the header
* isn't found.
*
* @param name the name of the header to remove.
* @return the header if removed, null otherwise.
*
* @throws NullPointerException if {@code name} is null.
*/
public Header remove(String name) {
Objects.requireNonNull(name, "'name' cannot be null.");
return headers.remove(formatKey(name));
}
/**
* Get the value for the provided header name. {@code Null} is returned if the header name isn't found.
*
* @param name the name of the header whose value is being retrieved.
* @return the value of the header, or null if the header isn't found
*
* @throws NullPointerException if {@code name} is null.
*/
public String getValue(String name) {
final Header header = get(name);
return header == null ? null : header.getValue();
}
/**
* Get the values for the provided header name. {@code Null} is returned if the header name isn't found.
*
* <p>This returns {@link
*
* @param name the name of the header whose value is being retrieved.
* @return the values of the header, or null if the header isn't found
*/
public String[] getValues(String name) {
final Header header = get(name);
return header == null ? null : header.getValues();
}
/**
* Gets a {@link Map} representation of the {@link Header} collection. The keys are {@link Header
* given {@link Header}.
*
* @return the headers as map
*/
public Map<String, Header> toMap() {
return headers;
}
private String formatKey(final String key) {
return key.toLowerCase(Locale.ROOT);
}
} | class ClientOptions {
private static final int MAX_APPLICATION_ID_LENGTH = 24;
private final ClientLogger logger = new
ClientLogger(ClientOptions.class);
private Iterable<Header> headers;
private String applicationId;
/**
* Gets the applicationId.
* @return The applicationId.
*/
public String getApplicationId() {
return applicationId;
}
/**
* Sets the applicationId provided. The {@code applicationId} is used to configure {@link UserAgentPolicy} for
* telemetry/monitoring purpose. It can be set using {@link ClientOptions
* ClientOptions
* <p>
* More About <a href="https:
* @param applicationId to be set.
*
* @return updated {@link ClientOptions}.
* @throws IllegalArgumentException If {@code applicationId} contains space or larger than 24 in length.
*/
/**
* Sets the headers, overwriting all previously set headers in the process. For example if you set a header,
* {@link Header Header("name", "value")}, on {@link ClientOptions}, it will be set on the request being sent to
* Azure Service.
* @param headers to be set on the request being sent to Azure Service.
*
* @return updated {@link ClientOptions}.
*/
public ClientOptions setHeaders(Iterable<Header> headers) {
this.headers = headers;
return this;
}
/**
* Gets a {@link Iterable} representation of the {@link Header}.
* @return the headers. If {@link Header} is not set previously, it returns an empty list (immutable).
*/
public Iterable<Header> getHeaders() {
if (headers == null) {
return Collections.emptyList();
}
return headers;
}
} |
If `value` is `null` does this return `name:` or `name:null`? | public String toString() {
return name + ":" + value;
} | return name + ":" + value; | public String toString() {
return name + ":" + value;
} | class Header {
private final String name;
private String value;
/**
* Create a Header instance using the provided name and value.
*
* @param name the name
* @param value the value
* @throws NullPointerException if {@code name} or {@code value} is null.
*/
public Header(String name, String value) {
Objects.requireNonNull(name, "'name' cannot be null.");
this.name = name;
this.value = value;
}
/**
* Get the header name.
*
* @return the name of this Header
*/
public String getName() {
return name;
}
/**
* Get the header value.
*
* @return the value of this Header
*/
public String getValue() {
return value;
}
/**
* Get the comma separated value as an array.
*
* @return the values of this Header that are separated by a comma
*/
public String[] getValues() {
return value == null ? null : value.split(",");
}
/**
* Add a new value to the end of the Header.
*
* @param value the value to add
* @throws NullPointerException if {@code value} is null.
*/
public void addValue(String value) {
Objects.requireNonNull(value, "'value' cannot be null.");
this.value += "," + value;
}
/**
* Get the String representation of the header.
*
* @return the String representation of this Header.
*/
@Override
} | class Header {
private final String name;
private String value;
/**
* Create a Header instance using the provided name and value.
*
* @param name the name of the header.
* @param value the value of the header.
* @throws NullPointerException if {@code name} is null.
*/
public Header(String name, String value) {
Objects.requireNonNull(name, "'name' cannot be null.");
this.name = name;
this.value = value;
}
/**
* Gets the header name.
*
* @return the name of this {@link Header}
*/
public String getName() {
return name;
}
/**
* Gets the value of this {@link Header}.
*
* @return the value of this Header
*/
public String getValue() {
return value;
}
/**
* Gets the comma separated value as an array.
*
* @return the values of this {@link Header} that are separated by a comma
*/
public String[] getValues() {
return value == null ? null : value.split(",");
}
/**
* Add a new value to the end of the Header.
*
* @param value the value to add
*/
public void addValue(String value) {
if (this.value != null) {
this.value += "," + value;
} else {
this.value = value;
}
}
/**
* Gets the String representation of the header.
*
* @return the String representation of this Header.
*/
@Override
} |
It should show `name:null`, Same way how HttpHeader shows. | public String toString() {
return name + ":" + value;
} | return name + ":" + value; | public String toString() {
return name + ":" + value;
} | class Header {
private final String name;
private String value;
/**
* Create a Header instance using the provided name and value.
*
* @param name the name
* @param value the value
* @throws NullPointerException if {@code name} or {@code value} is null.
*/
public Header(String name, String value) {
Objects.requireNonNull(name, "'name' cannot be null.");
this.name = name;
this.value = value;
}
/**
* Get the header name.
*
* @return the name of this Header
*/
public String getName() {
return name;
}
/**
* Get the header value.
*
* @return the value of this Header
*/
public String getValue() {
return value;
}
/**
* Get the comma separated value as an array.
*
* @return the values of this Header that are separated by a comma
*/
public String[] getValues() {
return value == null ? null : value.split(",");
}
/**
* Add a new value to the end of the Header.
*
* @param value the value to add
* @throws NullPointerException if {@code value} is null.
*/
public void addValue(String value) {
Objects.requireNonNull(value, "'value' cannot be null.");
this.value += "," + value;
}
/**
* Get the String representation of the header.
*
* @return the String representation of this Header.
*/
@Override
} | class Header {
private final String name;
private String value;
/**
* Create a Header instance using the provided name and value.
*
* @param name the name of the header.
* @param value the value of the header.
* @throws NullPointerException if {@code name} is null.
*/
public Header(String name, String value) {
Objects.requireNonNull(name, "'name' cannot be null.");
this.name = name;
this.value = value;
}
/**
* Gets the header name.
*
* @return the name of this {@link Header}
*/
public String getName() {
return name;
}
/**
* Gets the value of this {@link Header}.
*
* @return the value of this Header
*/
public String getValue() {
return value;
}
/**
* Gets the comma separated value as an array.
*
* @return the values of this {@link Header} that are separated by a comma
*/
public String[] getValues() {
return value == null ? null : value.split(",");
}
/**
* Add a new value to the end of the Header.
*
* @param value the value to add
*/
public void addValue(String value) {
if (this.value != null) {
this.value += "," + value;
} else {
this.value = value;
}
}
/**
* Gets the String representation of the header.
*
* @return the String representation of this Header.
*/
@Override
} |
Rather than return a new arraylist - just return an empty iterable, e.g. `return Collections.emptyList();` | public Iterable<Header> getHeaders() {
if (headers == null) {
headers = new ArrayList<>();
}
return headers;
} | headers = new ArrayList<>(); | public Iterable<Header> getHeaders() {
if (headers == null) {
return Collections.emptyList();
}
return headers;
} | class ClientOptions {
private static final int MAX_APPLICATION_ID_LENGTH = 24;
private final ClientLogger logger = new ClientLogger(ClientOptions.class);
private Iterable<Header> headers;
private String applicationId;
/**
* Gets the applicationId.
* @return The applicationId.
*/
public String getApplicationId() {
return applicationId;
}
/**
* Sets the applicationId provided.
* @param applicationId to be set.
*
* @return updated {@link ClientOptions}.
*/
public ClientOptions setApplicationId(String applicationId) {
if (CoreUtils.isNullOrEmpty(applicationId)) {
this.applicationId = applicationId;
return this;
}
if (applicationId.length() > MAX_APPLICATION_ID_LENGTH) {
throw logger
.logExceptionAsError(new IllegalArgumentException("'applicationId' length cannot be greater than "
+ MAX_APPLICATION_ID_LENGTH));
} else if (applicationId.contains(" ")) {
throw logger
.logExceptionAsError(new IllegalArgumentException("'applicationId' must not contain a space."));
} else {
this.applicationId = applicationId;
}
return this;
}
/**
* Sets the provided headers, overwriting all previously-set headers in the process.
* @param headers headers to be set.
*
* @return updated {@link ClientOptions}.
* @throws NullPointerException if {@code headers} is null.
*/
public ClientOptions setHeaders(Iterable<Header> headers) {
this.headers = Objects.requireNonNull(headers, "'headers' cannot be null.");
return this;
}
/**
* Gets a {@link Iterable} representation of the {@link Header}.
* @return the headers.
*/
} | class ClientOptions {
private static final int MAX_APPLICATION_ID_LENGTH = 24;
private final ClientLogger logger = new
ClientLogger(ClientOptions.class);
private Iterable<Header> headers;
private String applicationId;
/**
* Gets the applicationId.
* @return The applicationId.
*/
public String getApplicationId() {
return applicationId;
}
/**
* Sets the applicationId provided. The {@code applicationId} is used to configure {@link UserAgentPolicy} for
* telemetry/monitoring purpose. It can be set using {@link ClientOptions
* ClientOptions
* <p>
* More About <a href="https:
* @param applicationId to be set.
*
* @return updated {@link ClientOptions}.
* @throws IllegalArgumentException If {@code applicationId} contains space or larger than 24 in length.
*/
public ClientOptions setApplicationId(String applicationId) {
if (CoreUtils.isNullOrEmpty(applicationId)) {
this.applicationId = applicationId;
return this;
}
if (applicationId.length() > MAX_APPLICATION_ID_LENGTH) {
throw logger
.logExceptionAsError(new IllegalArgumentException("'applicationId' length cannot be greater than "
+ MAX_APPLICATION_ID_LENGTH));
} else if (applicationId.contains(" ")) {
throw logger
.logExceptionAsError(new IllegalArgumentException("'applicationId' must not contain a space."));
} else {
this.applicationId = applicationId;
}
return this;
}
/**
* Sets the headers, overwriting all previously set headers in the process. For example if you set a header,
* {@link Header Header("name", "value")}, on {@link ClientOptions}, it will be set on the request being sent to
* Azure Service.
* @param headers to be set on the request being sent to Azure Service.
*
* @return updated {@link ClientOptions}.
*/
public ClientOptions setHeaders(Iterable<Header> headers) {
this.headers = headers;
return this;
}
/**
* Gets a {@link Iterable} representation of the {@link Header}.
* @return the headers. If {@link Header} is not set previously, it returns an empty list (immutable).
*/
} |
Yeah, this creates a new instance of ArrayList each time. Instead, using Collections.emptyList() will return a static singleton list instance. | public Iterable<Header> getHeaders() {
if (headers == null) {
headers = new ArrayList<>();
}
return headers;
} | headers = new ArrayList<>(); | public Iterable<Header> getHeaders() {
if (headers == null) {
return Collections.emptyList();
}
return headers;
} | class ClientOptions {
private static final int MAX_APPLICATION_ID_LENGTH = 24;
private final ClientLogger logger = new ClientLogger(ClientOptions.class);
private Iterable<Header> headers;
private String applicationId;
/**
* Gets the applicationId.
* @return The applicationId.
*/
public String getApplicationId() {
return applicationId;
}
/**
* Sets the applicationId provided.
* @param applicationId to be set.
*
* @return updated {@link ClientOptions}.
*/
public ClientOptions setApplicationId(String applicationId) {
if (CoreUtils.isNullOrEmpty(applicationId)) {
this.applicationId = applicationId;
return this;
}
if (applicationId.length() > MAX_APPLICATION_ID_LENGTH) {
throw logger
.logExceptionAsError(new IllegalArgumentException("'applicationId' length cannot be greater than "
+ MAX_APPLICATION_ID_LENGTH));
} else if (applicationId.contains(" ")) {
throw logger
.logExceptionAsError(new IllegalArgumentException("'applicationId' must not contain a space."));
} else {
this.applicationId = applicationId;
}
return this;
}
/**
* Sets the provided headers, overwriting all previously-set headers in the process.
* @param headers headers to be set.
*
* @return updated {@link ClientOptions}.
* @throws NullPointerException if {@code headers} is null.
*/
public ClientOptions setHeaders(Iterable<Header> headers) {
this.headers = Objects.requireNonNull(headers, "'headers' cannot be null.");
return this;
}
/**
* Gets a {@link Iterable} representation of the {@link Header}.
* @return the headers.
*/
} | class ClientOptions {
private static final int MAX_APPLICATION_ID_LENGTH = 24;
private final ClientLogger logger = new
ClientLogger(ClientOptions.class);
private Iterable<Header> headers;
private String applicationId;
/**
* Gets the applicationId.
* @return The applicationId.
*/
public String getApplicationId() {
return applicationId;
}
/**
* Sets the applicationId provided. The {@code applicationId} is used to configure {@link UserAgentPolicy} for
* telemetry/monitoring purpose. It can be set using {@link ClientOptions
* ClientOptions
* <p>
* More About <a href="https:
* @param applicationId to be set.
*
* @return updated {@link ClientOptions}.
* @throws IllegalArgumentException If {@code applicationId} contains space or larger than 24 in length.
*/
public ClientOptions setApplicationId(String applicationId) {
if (CoreUtils.isNullOrEmpty(applicationId)) {
this.applicationId = applicationId;
return this;
}
if (applicationId.length() > MAX_APPLICATION_ID_LENGTH) {
throw logger
.logExceptionAsError(new IllegalArgumentException("'applicationId' length cannot be greater than "
+ MAX_APPLICATION_ID_LENGTH));
} else if (applicationId.contains(" ")) {
throw logger
.logExceptionAsError(new IllegalArgumentException("'applicationId' must not contain a space."));
} else {
this.applicationId = applicationId;
}
return this;
}
/**
* Sets the headers, overwriting all previously set headers in the process. For example if you set a header,
* {@link Header Header("name", "value")}, on {@link ClientOptions}, it will be set on the request being sent to
* Azure Service.
* @param headers to be set on the request being sent to Azure Service.
*
* @return updated {@link ClientOptions}.
*/
public ClientOptions setHeaders(Iterable<Header> headers) {
this.headers = headers;
return this;
}
/**
* Gets a {@link Iterable} representation of the {@link Header}.
* @return the headers. If {@link Header} is not set previously, it returns an empty list (immutable).
*/
} |
If we set negative values to these numbers, We should validate these values. | void createQueue() {
final String queueName = "some-queue";
final CreateQueueOptions expected = new CreateQueueOptions(queueName)
.setAutoDeleteOnIdle(Duration.ofSeconds(15))
.setDefaultMessageTimeToLive(Duration.ofSeconds(50))
.setDeadLetteringOnMessageExpiration(true)
.setDuplicateDetectionHistoryTimeWindow(Duration.ofSeconds(13))
.setEnableBatchedOperations(false)
.setEnablePartitioning(true)
.setForwardTo("Forward-To-This-Queue")
.setForwardDeadLetteredMessagesTo("Dead-Lettered-Forward-To")
.setLockDuration(Duration.ofSeconds(120))
.setMaxDeliveryCount(15)
.setMaxSizeInMegabytes(2048)
.setRequiresDuplicateDetection(true)
.setRequiresSession(true)
.setUserMetadata("Test-queue-Metadata")
.setStatus(EntityStatus.DISABLED);
final QueueProperties actual = EntityHelper.createQueue(expected);
assertEquals(expected.getName(), actual.getName());
assertEquals(expected.getAutoDeleteOnIdle(), actual.getAutoDeleteOnIdle());
assertEquals(expected.getDefaultMessageTimeToLive(), actual.getDefaultMessageTimeToLive());
assertEquals(expected.deadLetteringOnMessageExpiration(), actual.deadLetteringOnMessageExpiration());
assertEquals(expected.getDuplicateDetectionHistoryTimeWindow(), actual.getDuplicateDetectionHistoryTimeWindow());
assertEquals(expected.enableBatchedOperations(), actual.enableBatchedOperations());
assertEquals(expected.enablePartitioning(), actual.enablePartitioning());
assertEquals(expected.getForwardTo(), actual.getForwardTo());
assertEquals(expected.getForwardDeadLetteredMessagesTo(), actual.getForwardDeadLetteredMessagesTo());
assertEquals(expected.getLockDuration(), actual.getLockDuration());
assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount());
assertEquals(expected.requiresDuplicateDetection(), actual.requiresDuplicateDetection());
assertEquals(expected.requiresSession(), actual.requiresSession());
assertEquals(expected.getUserMetadata(), actual.getUserMetadata());
assertEquals(expected.getStatus(), actual.getStatus());
} | .setMaxSizeInMegabytes(2048) | void createQueue() {
final String queueName = "some-queue";
final CreateQueueOptions expected = new CreateQueueOptions(queueName)
.setAutoDeleteOnIdle(Duration.ofSeconds(15))
.setDefaultMessageTimeToLive(Duration.ofSeconds(50))
.setDeadLetteringOnMessageExpiration(true)
.setDuplicateDetectionHistoryTimeWindow(Duration.ofSeconds(13))
.setEnableBatchedOperations(false)
.setEnablePartitioning(true)
.setForwardTo("Forward-To-This-Queue")
.setForwardDeadLetteredMessagesTo("Dead-Lettered-Forward-To")
.setLockDuration(Duration.ofSeconds(120))
.setMaxDeliveryCount(15)
.setMaxSizeInMegabytes(2048)
.setRequiresDuplicateDetection(true)
.setRequiresSession(true)
.setUserMetadata("Test-queue-Metadata")
.setStatus(EntityStatus.DISABLED);
final QueueDescription actual = EntityHelper.getQueueDescription(expected);
assertEquals(expected.getAutoDeleteOnIdle(), actual.getAutoDeleteOnIdle());
assertEquals(expected.getDefaultMessageTimeToLive(), actual.getDefaultMessageTimeToLive());
assertEquals(expected.deadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration());
assertEquals(expected.getDuplicateDetectionHistoryTimeWindow(), actual.getDuplicateDetectionHistoryTimeWindow());
assertEquals(expected.enableBatchedOperations(), actual.isEnableBatchedOperations());
assertEquals(expected.enablePartitioning(), actual.isEnablePartitioning());
assertEquals(expected.getForwardTo(), actual.getForwardTo());
assertEquals(expected.getForwardDeadLetteredMessagesTo(), actual.getForwardDeadLetteredMessagesTo());
assertEquals(expected.getLockDuration(), actual.getLockDuration());
assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount());
assertEquals(expected.requiresDuplicateDetection(), actual.isRequiresDuplicateDetection());
assertEquals(expected.requiresSession(), actual.isRequiresSession());
assertEquals(expected.getUserMetadata(), actual.getUserMetadata());
assertEquals(expected.getStatus(), actual.getStatus());
} | class EntityHelperTest {
@Test
@Test
void setQueueName() {
final String newName = "I'm a new name";
final CreateQueueOptions options = new CreateQueueOptions("some name");
final QueueProperties properties = EntityHelper.createQueue(options);
EntityHelper.setQueueName(properties, newName);
assertEquals(newName, properties.getName());
}
} | class EntityHelperTest {
@Test
@Test
void setQueueName() {
final String newName = "I'm a new name";
final CreateQueueOptions options = new CreateQueueOptions("some name");
final QueueProperties properties = EntityHelper.toModel(EntityHelper.getQueueDescription(options));
EntityHelper.setQueueName(properties, newName);
assertEquals(newName, properties.getName());
}
} |
I see that generally, there is no Null check, is this by design ? | public CreateQueueOptions setDuplicateDetectionHistoryTimeWindow(Duration duplicateDetectionHistoryTimeWindow) {
this.duplicateDetectionHistoryTimeWindow = duplicateDetectionHistoryTimeWindow;
return this;
} | this.duplicateDetectionHistoryTimeWindow = duplicateDetectionHistoryTimeWindow; | public CreateQueueOptions setDuplicateDetectionHistoryTimeWindow(Duration duplicateDetectionHistoryTimeWindow) {
this.duplicateDetectionHistoryTimeWindow = duplicateDetectionHistoryTimeWindow;
return this;
} | class CreateQueueOptions {
private final String name;
private Duration autoDeleteOnIdle;
private Duration defaultMessageTimeToLive;
private boolean deadLetteringOnMessageExpiration;
private Duration duplicateDetectionHistoryTimeWindow;
private boolean enableBatchedOperations;
private boolean enablePartitioning;
private String forwardTo;
private String forwardDeadLetteredMessagesTo;
private Duration lockDuration;
private int maxDeliveryCount;
private int maxSizeInMegabytes;
private boolean requiresDuplicateDetection;
private boolean requiresSession;
private String userMetadata;
private EntityStatus status;
/**
* Creates an instance with the name of the queue. Default values for the queue are populated. The properties
* populated with defaults are:
*
* <ul>
* <li>{@link
* <li>{@link
* <li>{@link
* detection is disabled.</li>
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* </ul>
*
* @param queueName Name of the queue.
*
* @throws NullPointerException if {@code queueName} is a null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
*/
public CreateQueueOptions(String queueName) {
Objects.requireNonNull(queueName, "'queueName' cannot be null.");
if (queueName.isEmpty()) {
ClientLogger logger = new ClientLogger(CreateQueueOptions.class);
throw logger.logThrowableAsError(new IllegalArgumentException("Queue name cannot be empty."));
}
this.name = queueName;
this.autoDeleteOnIdle = MAX_DURATION;
this.defaultMessageTimeToLive = MAX_DURATION;
this.duplicateDetectionHistoryTimeWindow = DEFAULT_DUPLICATE_DETECTION_DURATION;
this.enableBatchedOperations = true;
this.enablePartitioning = false;
this.lockDuration = DEFAULT_LOCK_DURATION;
this.maxDeliveryCount = DEFAULT_MAX_DELIVERY_COUNT;
this.maxSizeInMegabytes = DEFAULT_QUEUE_SIZE;
this.requiresDuplicateDetection = false;
this.requiresSession = false;
this.deadLetteringOnMessageExpiration = false;
this.status = EntityStatus.ACTIVE;
}
/**
* Initializes a new instance based on the specified {@link QueueProperties} instance. This is useful for creating a
* new queue based on the properties of an existing queue.
*
* @param queue Existing queue to create options with.
*/
public CreateQueueOptions(QueueProperties queue) {
Objects.requireNonNull(queue, "'queue' cannot be null.");
Objects.requireNonNull(queue.getName(), "Queue name cannot be null.");
if (queue.getName().isEmpty()) {
final ClientLogger logger = new ClientLogger(CreateQueueOptions.class);
throw logger.logExceptionAsError(new IllegalArgumentException("Queue name cannot be empty."));
}
this.name = queue.getName();
this.autoDeleteOnIdle = queue.getAutoDeleteOnIdle();
this.defaultMessageTimeToLive = queue.getDefaultMessageTimeToLive();
this.deadLetteringOnMessageExpiration = queue.deadLetteringOnMessageExpiration() != null
? queue.deadLetteringOnMessageExpiration()
: false;
this.duplicateDetectionHistoryTimeWindow = queue.getDuplicateDetectionHistoryTimeWindow() != null
? queue.getDuplicateDetectionHistoryTimeWindow()
: DEFAULT_DUPLICATE_DETECTION_DURATION;
this.enableBatchedOperations = queue.enableBatchedOperations() != null
? queue.enableBatchedOperations()
: false;
this.enablePartitioning = queue.enablePartitioning() != null
? queue.enablePartitioning()
: false;
this.forwardTo = queue.getForwardTo();
this.forwardDeadLetteredMessagesTo = queue.getForwardDeadLetteredMessagesTo();
this.lockDuration = queue.getLockDuration();
this.maxDeliveryCount = queue.getMaxDeliveryCount() != null
? queue.getMaxDeliveryCount()
: DEFAULT_MAX_DELIVERY_COUNT;
this.maxSizeInMegabytes = queue.getMaxSizeInMegabytes() != null
? queue.getMaxSizeInMegabytes()
: DEFAULT_QUEUE_SIZE;
this.requiresDuplicateDetection = queue.requiresDuplicateDetection() != null
? queue.requiresDuplicateDetection()
: false;
this.requiresSession = queue.requiresSession() != null
? queue.requiresSession()
: false;
this.status = queue.getStatus();
this.userMetadata = queue.getUserMetadata();
}
/**
* Gets the name of the queue.
*
* @return The name of the queue.
*/
public String getName() {
return name;
}
/**
* Get the autoDeleteOnIdle property: ISO 8601 timeSpan idle interval after which the queue is automatically
* deleted. The minimum duration is 5 minutes.
*
* @return the autoDeleteOnIdle value.
*/
public Duration getAutoDeleteOnIdle() {
return this.autoDeleteOnIdle;
}
/**
* Set the autoDeleteOnIdle property: ISO 8601 timeSpan idle interval after which the queue is automatically
* deleted. The minimum duration is 5 minutes.
*
* @param autoDeleteOnIdle the autoDeleteOnIdle value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setAutoDeleteOnIdle(Duration autoDeleteOnIdle) {
this.autoDeleteOnIdle = autoDeleteOnIdle;
return this;
}
/**
* Get the defaultMessageTimeToLive property: ISO 8601 default message timespan to live value. This is the duration
* after which the message expires, starting from when the message is sent to Service Bus. This is the default value
* used when TimeToLive is not set on a message itself.
*
* @return the defaultMessageTimeToLive value.
*/
public Duration getDefaultMessageTimeToLive() {
return this.defaultMessageTimeToLive;
}
/**
* Set the defaultMessageTimeToLive property: ISO 8601 default message timespan to live value. This is the duration
* after which the message expires, starting from when the message is sent to Service Bus. This is the default value
* used when TimeToLive is not set on a message itself.
*
* @param defaultMessageTimeToLive the defaultMessageTimeToLive value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setDefaultMessageTimeToLive(Duration defaultMessageTimeToLive) {
this.defaultMessageTimeToLive = defaultMessageTimeToLive;
return this;
}
/**
* Get the deadLetteringOnMessageExpiration property: A value that indicates whether this queue has dead letter
* support when a message expires.
*
* @return the deadLetteringOnMessageExpiration value.
*/
public boolean deadLetteringOnMessageExpiration() {
return this.deadLetteringOnMessageExpiration;
}
/**
* Set the deadLetteringOnMessageExpiration property: A value that indicates whether this queue has dead letter
* support when a message expires.
*
* @param deadLetteringOnMessageExpiration the deadLetteringOnMessageExpiration value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setDeadLetteringOnMessageExpiration(boolean deadLetteringOnMessageExpiration) {
this.deadLetteringOnMessageExpiration = deadLetteringOnMessageExpiration;
return this;
}
/**
* Get the duplicateDetectionHistoryTimeWindow property: ISO 8601 timeSpan structure that defines the duration of
* the duplicate detection history. The default value is 10 minutes.
*
* @return the duplicateDetectionHistoryTimeWindow value.
*/
public Duration getDuplicateDetectionHistoryTimeWindow() {
return this.duplicateDetectionHistoryTimeWindow;
}
/**
* Set the duplicateDetectionHistoryTimeWindow property: ISO 8601 timeSpan structure that defines the duration of
* the duplicate detection history. The default value is 10 minutes.
*
* @param duplicateDetectionHistoryTimeWindow the duplicateDetectionHistoryTimeWindow value to set.
*
* @return the CreateQueueOptions object itself.
*/
/**
* Get the enableBatchedOperations property: Value that indicates whether server-side batched operations are
* enabled.
*
* @return the enableBatchedOperations value.
*/
public boolean enableBatchedOperations() {
return this.enableBatchedOperations;
}
/**
* Set the enableBatchedOperations property: Value that indicates whether server-side batched operations are
* enabled.
*
* @param enableBatchedOperations the enableBatchedOperations value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setEnableBatchedOperations(boolean enableBatchedOperations) {
this.enableBatchedOperations = enableBatchedOperations;
return this;
}
/**
* Get the enablePartitioning property: A value that indicates whether the queue is to be partitioned across
* multiple message brokers.
*
* @return the enablePartitioning value.
*/
public boolean enablePartitioning() {
return this.enablePartitioning;
}
/**
* Set the enablePartitioning property: A value that indicates whether the queue is to be partitioned across
* multiple message brokers.
*
* @param enablePartitioning the enablePartitioning value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setEnablePartitioning(boolean enablePartitioning) {
this.enablePartitioning = enablePartitioning;
return this;
}
/**
* Get the forwardTo property: The name of the recipient entity to which all the messages sent to the queue are
* forwarded to.
*
* @return the forwardTo value.
*/
public String getForwardTo() {
return this.forwardTo;
}
/**
* Set the forwardTo property: The name of the recipient entity to which all the messages sent to the queue are
* forwarded to.
*
* @param forwardTo the forwardTo value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setForwardTo(String forwardTo) {
this.forwardTo = forwardTo;
return this;
}
/**
* Get the forwardDeadLetteredMessagesTo property: The name of the recipient entity to which all the dead-lettered
* messages of this queue are forwarded to.
*
* @return the forwardDeadLetteredMessagesTo value.
*/
public String getForwardDeadLetteredMessagesTo() {
return this.forwardDeadLetteredMessagesTo;
}
/**
* Set the forwardDeadLetteredMessagesTo property: The name of the recipient entity to which all the dead-lettered
* messages of this queue are forwarded to.
*
* @param forwardDeadLetteredMessagesTo the forwardDeadLetteredMessagesTo value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setForwardDeadLetteredMessagesTo(String forwardDeadLetteredMessagesTo) {
this.forwardDeadLetteredMessagesTo = forwardDeadLetteredMessagesTo;
return this;
}
/**
* Get the lockDuration property: ISO 8601 timespan duration of a peek-lock; that is, the amount of time that the
* message is locked for other receivers. The maximum value for LockDuration is 5 minutes; the default value is 1
* minute.
*
* @return the lockDuration value.
*/
public Duration getLockDuration() {
return this.lockDuration;
}
/**
* Set the lockDuration property: ISO 8601 timespan duration of a peek-lock; that is, the amount of time that the
* message is locked for other receivers. The maximum value for LockDuration is 5 minutes; the default value is 1
* minute.
*
* @param lockDuration the lockDuration value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setLockDuration(Duration lockDuration) {
this.lockDuration = lockDuration;
return this;
}
/**
* Get the maxDeliveryCount property: The maximum delivery count. A message is automatically deadlettered after this
* number of deliveries. Default value is 10.
*
* @return the maxDeliveryCount value.
*/
public int getMaxDeliveryCount() {
return this.maxDeliveryCount;
}
/**
* Set the maxDeliveryCount property: The maximum delivery count. A message is automatically deadlettered after this
* number of deliveries. Default value is 10.
*
* @param maxDeliveryCount the maxDeliveryCount value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setMaxDeliveryCount(int maxDeliveryCount) {
this.maxDeliveryCount = maxDeliveryCount;
return this;
}
/**
* Get the maxSizeInMegabytes property: The maximum size of the queue in megabytes, which is the size of memory
* allocated for the queue.
*
* @return the maxSizeInMegabytes value.
*/
public int getMaxSizeInMegabytes() {
return this.maxSizeInMegabytes;
}
/**
* Set the maxSizeInMegabytes property: The maximum size of the queue in megabytes, which is the size of memory
* allocated for the queue.
*
* @param maxSizeInMegabytes the maxSizeInMegabytes value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setMaxSizeInMegabytes(int maxSizeInMegabytes) {
this.maxSizeInMegabytes = maxSizeInMegabytes;
return this;
}
/**
* Get the requiresDuplicateDetection property: A value indicating if this queue requires duplicate detection.
*
* @return the requiresDuplicateDetection value.
*/
public boolean requiresDuplicateDetection() {
return this.requiresDuplicateDetection;
}
/**
* Set the requiresDuplicateDetection property: A value indicating if this queue requires duplicate detection.
*
* @param requiresDuplicateDetection the requiresDuplicateDetection value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setRequiresDuplicateDetection(boolean requiresDuplicateDetection) {
this.requiresDuplicateDetection = requiresDuplicateDetection;
return this;
}
/**
* Get the requiresSession property: A value that indicates whether the queue supports the concept of sessions.
*
* @return the requiresSession value.
*/
public boolean requiresSession() {
return this.requiresSession;
}
/**
* Set the requiresSession property: A value that indicates whether the queue supports the concept of sessions.
*
* @param requiresSession the requiresSession value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setRequiresSession(boolean requiresSession) {
this.requiresSession = requiresSession;
return this;
}
/**
* Get the status property: Status of a Service Bus resource.
*
* @return the status value.
*/
public EntityStatus getStatus() {
return this.status;
}
/**
* Set the status property: Status of a Service Bus resource.
*
* @param status the status value to set.
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setStatus(EntityStatus status) {
this.status = status;
return this;
}
/**
* Get the userMetadata property: Custom metdata that user can associate with the description. Max length is 1024
* chars.
*
* @return the userMetadata value.
*/
public String getUserMetadata() {
return this.userMetadata;
}
/**
* Set the userMetadata property: Custom metdata that user can associate with the description. Max length is 1024
* chars.
*
* @param userMetadata the userMetadata value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setUserMetadata(String userMetadata) {
this.userMetadata = userMetadata;
return this;
}
} | class CreateQueueOptions {
private final String name;
private Duration autoDeleteOnIdle;
private Duration defaultMessageTimeToLive;
private boolean deadLetteringOnMessageExpiration;
private Duration duplicateDetectionHistoryTimeWindow;
private boolean enableBatchedOperations;
private boolean enablePartitioning;
private String forwardTo;
private String forwardDeadLetteredMessagesTo;
private Duration lockDuration;
private int maxDeliveryCount;
private long maxSizeInMegabytes;
private boolean requiresDuplicateDetection;
private boolean requiresSession;
private String userMetadata;
private EntityStatus status;
/**
* Creates an instance with the name of the queue. Default values for the queue are populated. The properties
* populated with defaults are:
*
* <ul>
* <li>{@link
* <li>{@link
* <li>{@link
* detection is disabled.</li>
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* </ul>
*
* @param queueName Name of the queue.
*
* @throws NullPointerException if {@code queueName} is a null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
*/
public CreateQueueOptions(String queueName) {
Objects.requireNonNull(queueName, "'queueName' cannot be null.");
if (queueName.isEmpty()) {
ClientLogger logger = new ClientLogger(CreateQueueOptions.class);
throw logger.logThrowableAsError(new IllegalArgumentException("Queue name cannot be empty."));
}
this.name = queueName;
this.autoDeleteOnIdle = MAX_DURATION;
this.defaultMessageTimeToLive = MAX_DURATION;
this.duplicateDetectionHistoryTimeWindow = DEFAULT_DUPLICATE_DETECTION_DURATION;
this.enableBatchedOperations = true;
this.enablePartitioning = false;
this.lockDuration = DEFAULT_LOCK_DURATION;
this.maxDeliveryCount = DEFAULT_MAX_DELIVERY_COUNT;
this.maxSizeInMegabytes = DEFAULT_QUEUE_SIZE;
this.requiresDuplicateDetection = false;
this.requiresSession = false;
this.deadLetteringOnMessageExpiration = false;
this.status = EntityStatus.ACTIVE;
}
/**
* Initializes a new instance based on the specified {@link QueueProperties} instance. This is useful for creating a
* new queue based on the properties of an existing queue.
*
* @param queue Existing queue to create options with.
*/
public CreateQueueOptions(QueueProperties queue) {
Objects.requireNonNull(queue, "'queue' cannot be null.");
Objects.requireNonNull(queue.getName(), "Queue name cannot be null.");
if (queue.getName().isEmpty()) {
final ClientLogger logger = new ClientLogger(CreateQueueOptions.class);
throw logger.logExceptionAsError(new IllegalArgumentException("Queue name cannot be empty."));
}
this.name = queue.getName();
this.autoDeleteOnIdle = queue.getAutoDeleteOnIdle();
this.defaultMessageTimeToLive = queue.getDefaultMessageTimeToLive();
this.deadLetteringOnMessageExpiration = queue.isDeadLetteringOnMessageExpiration();
this.duplicateDetectionHistoryTimeWindow = queue.getDuplicateDetectionHistoryTimeWindow() != null
? queue.getDuplicateDetectionHistoryTimeWindow()
: DEFAULT_DUPLICATE_DETECTION_DURATION;
this.enableBatchedOperations = queue.enableBatchedOperations();
this.enablePartitioning = queue.enablePartitioning();
this.forwardTo = queue.getForwardTo();
this.forwardDeadLetteredMessagesTo = queue.getForwardDeadLetteredMessagesTo();
this.lockDuration = queue.getLockDuration();
this.maxDeliveryCount = queue.getMaxDeliveryCount();
this.maxSizeInMegabytes = queue.getMaxSizeInMegabytes();
this.requiresDuplicateDetection = queue.requiresDuplicateDetection();
this.requiresSession = queue.requiresSession();
this.status = queue.getStatus();
this.userMetadata = queue.getUserMetadata();
}
/**
* Gets the name of the queue.
*
* @return The name of the queue.
*/
public String getName() {
return name;
}
/**
* Get the autoDeleteOnIdle property: ISO 8601 timeSpan idle interval after which the queue is automatically
* deleted. The minimum duration is 5 minutes.
*
* @return the autoDeleteOnIdle value.
*/
public Duration getAutoDeleteOnIdle() {
return this.autoDeleteOnIdle;
}
/**
* Set the autoDeleteOnIdle property: ISO 8601 timeSpan idle interval after which the queue is automatically
* deleted. The minimum duration is 5 minutes.
*
* @param autoDeleteOnIdle the autoDeleteOnIdle value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setAutoDeleteOnIdle(Duration autoDeleteOnIdle) {
this.autoDeleteOnIdle = autoDeleteOnIdle;
return this;
}
/**
* Get the defaultMessageTimeToLive property: ISO 8601 default message timespan to live value. This is the duration
* after which the message expires, starting from when the message is sent to Service Bus. This is the default value
* used when TimeToLive is not set on a message itself.
*
* @return the defaultMessageTimeToLive value.
*/
public Duration getDefaultMessageTimeToLive() {
return this.defaultMessageTimeToLive;
}
/**
* Set the defaultMessageTimeToLive property: ISO 8601 default message timespan to live value. This is the duration
* after which the message expires, starting from when the message is sent to Service Bus. This is the default value
* used when TimeToLive is not set on a message itself.
*
* @param defaultMessageTimeToLive the defaultMessageTimeToLive value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setDefaultMessageTimeToLive(Duration defaultMessageTimeToLive) {
this.defaultMessageTimeToLive = defaultMessageTimeToLive;
return this;
}
/**
* Get the deadLetteringOnMessageExpiration property: A value that indicates whether this queue has dead letter
* support when a message expires.
*
* @return the deadLetteringOnMessageExpiration value.
*/
public boolean deadLetteringOnMessageExpiration() {
return this.deadLetteringOnMessageExpiration;
}
/**
* Set the deadLetteringOnMessageExpiration property: A value that indicates whether this queue has dead letter
* support when a message expires.
*
* @param deadLetteringOnMessageExpiration the deadLetteringOnMessageExpiration value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setDeadLetteringOnMessageExpiration(boolean deadLetteringOnMessageExpiration) {
this.deadLetteringOnMessageExpiration = deadLetteringOnMessageExpiration;
return this;
}
/**
* Get the duplicateDetectionHistoryTimeWindow property: ISO 8601 timeSpan structure that defines the duration of
* the duplicate detection history. The default value is 10 minutes.
*
* @return the duplicateDetectionHistoryTimeWindow value.
*/
public Duration getDuplicateDetectionHistoryTimeWindow() {
return this.duplicateDetectionHistoryTimeWindow;
}
/**
* Set the duplicateDetectionHistoryTimeWindow property: ISO 8601 timeSpan structure that defines the duration of
* the duplicate detection history. The default value is 10 minutes.
*
* @param duplicateDetectionHistoryTimeWindow the duplicateDetectionHistoryTimeWindow value to set.
*
* @return the CreateQueueOptions object itself.
*/
/**
* Get the enableBatchedOperations property: Value that indicates whether server-side batched operations are
* enabled.
*
* @return the enableBatchedOperations value.
*/
public boolean enableBatchedOperations() {
return this.enableBatchedOperations;
}
/**
* Set the enableBatchedOperations property: Value that indicates whether server-side batched operations are
* enabled.
*
* @param enableBatchedOperations the enableBatchedOperations value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setEnableBatchedOperations(boolean enableBatchedOperations) {
this.enableBatchedOperations = enableBatchedOperations;
return this;
}
/**
* Get the enablePartitioning property: A value that indicates whether the queue is to be partitioned across
* multiple message brokers.
*
* @return the enablePartitioning value.
*/
public boolean enablePartitioning() {
return this.enablePartitioning;
}
/**
* Set the enablePartitioning property: A value that indicates whether the queue is to be partitioned across
* multiple message brokers.
*
* @param enablePartitioning the enablePartitioning value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setEnablePartitioning(boolean enablePartitioning) {
this.enablePartitioning = enablePartitioning;
return this;
}
/**
* Get the forwardTo property: The name of the recipient entity to which all the messages sent to the queue are
* forwarded to.
*
* @return the forwardTo value.
*/
public String getForwardTo() {
return this.forwardTo;
}
/**
* Set the forwardTo property: The name of the recipient entity to which all the messages sent to the queue are
* forwarded to.
*
* @param forwardTo the forwardTo value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setForwardTo(String forwardTo) {
this.forwardTo = forwardTo;
return this;
}
/**
* Get the forwardDeadLetteredMessagesTo property: The name of the recipient entity to which all the dead-lettered
* messages of this queue are forwarded to.
*
* @return the forwardDeadLetteredMessagesTo value.
*/
public String getForwardDeadLetteredMessagesTo() {
return this.forwardDeadLetteredMessagesTo;
}
/**
* Set the forwardDeadLetteredMessagesTo property: The name of the recipient entity to which all the dead-lettered
* messages of this queue are forwarded to.
*
* @param forwardDeadLetteredMessagesTo the forwardDeadLetteredMessagesTo value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setForwardDeadLetteredMessagesTo(String forwardDeadLetteredMessagesTo) {
this.forwardDeadLetteredMessagesTo = forwardDeadLetteredMessagesTo;
return this;
}
/**
* Get the lockDuration property: ISO 8601 timespan duration of a peek-lock; that is, the amount of time that the
* message is locked for other receivers. The maximum value for LockDuration is 5 minutes; the default value is 1
* minute.
*
* @return the lockDuration value.
*/
public Duration getLockDuration() {
return this.lockDuration;
}
/**
* Set the lockDuration property: ISO 8601 timespan duration of a peek-lock; that is, the amount of time that the
* message is locked for other receivers. The maximum value for LockDuration is 5 minutes; the default value is 1
* minute.
*
* @param lockDuration the lockDuration value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setLockDuration(Duration lockDuration) {
this.lockDuration = lockDuration;
return this;
}
/**
* Get the maxDeliveryCount property: The maximum delivery count. A message is automatically deadlettered after this
* number of deliveries. Default value is 10.
*
* @return the maxDeliveryCount value.
*/
public int getMaxDeliveryCount() {
return this.maxDeliveryCount;
}
/**
* Set the maxDeliveryCount property: The maximum delivery count. A message is automatically deadlettered after this
* number of deliveries. Default value is 10.
*
* @param maxDeliveryCount the maxDeliveryCount value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setMaxDeliveryCount(int maxDeliveryCount) {
this.maxDeliveryCount = maxDeliveryCount;
return this;
}
/**
* Get the maxSizeInMegabytes property: The maximum size of the queue in megabytes, which is the size of memory
* allocated for the queue.
*
* @return the maxSizeInMegabytes value.
*/
public long getMaxSizeInMegabytes() {
return this.maxSizeInMegabytes;
}
/**
* Set the maxSizeInMegabytes property: The maximum size of the queue in megabytes, which is the size of memory
* allocated for the queue.
*
* @param maxSizeInMegabytes the maxSizeInMegabytes value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setMaxSizeInMegabytes(int maxSizeInMegabytes) {
this.maxSizeInMegabytes = maxSizeInMegabytes;
return this;
}
/**
* Get the requiresDuplicateDetection property: A value indicating if this queue requires duplicate detection.
*
* @return the requiresDuplicateDetection value.
*/
public boolean requiresDuplicateDetection() {
return this.requiresDuplicateDetection;
}
/**
* Set the requiresDuplicateDetection property: A value indicating if this queue requires duplicate detection.
*
* @param requiresDuplicateDetection the requiresDuplicateDetection value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setRequiresDuplicateDetection(boolean requiresDuplicateDetection) {
this.requiresDuplicateDetection = requiresDuplicateDetection;
return this;
}
/**
* Get the requiresSession property: A value that indicates whether the queue supports the concept of sessions.
*
* @return the requiresSession value.
*/
public boolean requiresSession() {
return this.requiresSession;
}
/**
* Set the requiresSession property: A value that indicates whether the queue supports the concept of sessions.
*
* @param requiresSession the requiresSession value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setRequiresSession(boolean requiresSession) {
this.requiresSession = requiresSession;
return this;
}
/**
* Get the status property: Status of a Service Bus resource.
*
* @return the status value.
*/
public EntityStatus getStatus() {
return this.status;
}
/**
* Set the status property: Status of a Service Bus resource.
*
* @param status the status value to set.
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setStatus(EntityStatus status) {
this.status = status;
return this;
}
/**
* Get the userMetadata property: Custom metdata that user can associate with the description. Max length is 1024
* chars.
*
* @return the userMetadata value.
*/
public String getUserMetadata() {
return this.userMetadata;
}
/**
* Set the userMetadata property: Custom metdata that user can associate with the description. Max length is 1024
* chars.
*
* @param userMetadata the userMetadata value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setUserMetadata(String userMetadata) {
this.userMetadata = userMetadata;
return this;
}
} |
Yes. I try to do as little client validation if the service can do it. No value is === "use the default service value". It's not an invalid value. | public CreateQueueOptions setDuplicateDetectionHistoryTimeWindow(Duration duplicateDetectionHistoryTimeWindow) {
this.duplicateDetectionHistoryTimeWindow = duplicateDetectionHistoryTimeWindow;
return this;
} | this.duplicateDetectionHistoryTimeWindow = duplicateDetectionHistoryTimeWindow; | public CreateQueueOptions setDuplicateDetectionHistoryTimeWindow(Duration duplicateDetectionHistoryTimeWindow) {
this.duplicateDetectionHistoryTimeWindow = duplicateDetectionHistoryTimeWindow;
return this;
} | class CreateQueueOptions {
private final String name;
private Duration autoDeleteOnIdle;
private Duration defaultMessageTimeToLive;
private boolean deadLetteringOnMessageExpiration;
private Duration duplicateDetectionHistoryTimeWindow;
private boolean enableBatchedOperations;
private boolean enablePartitioning;
private String forwardTo;
private String forwardDeadLetteredMessagesTo;
private Duration lockDuration;
private int maxDeliveryCount;
private int maxSizeInMegabytes;
private boolean requiresDuplicateDetection;
private boolean requiresSession;
private String userMetadata;
private EntityStatus status;
/**
* Creates an instance with the name of the queue. Default values for the queue are populated. The properties
* populated with defaults are:
*
* <ul>
* <li>{@link
* <li>{@link
* <li>{@link
* detection is disabled.</li>
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* </ul>
*
* @param queueName Name of the queue.
*
* @throws NullPointerException if {@code queueName} is a null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
*/
public CreateQueueOptions(String queueName) {
Objects.requireNonNull(queueName, "'queueName' cannot be null.");
if (queueName.isEmpty()) {
ClientLogger logger = new ClientLogger(CreateQueueOptions.class);
throw logger.logThrowableAsError(new IllegalArgumentException("Queue name cannot be empty."));
}
this.name = queueName;
this.autoDeleteOnIdle = MAX_DURATION;
this.defaultMessageTimeToLive = MAX_DURATION;
this.duplicateDetectionHistoryTimeWindow = DEFAULT_DUPLICATE_DETECTION_DURATION;
this.enableBatchedOperations = true;
this.enablePartitioning = false;
this.lockDuration = DEFAULT_LOCK_DURATION;
this.maxDeliveryCount = DEFAULT_MAX_DELIVERY_COUNT;
this.maxSizeInMegabytes = DEFAULT_QUEUE_SIZE;
this.requiresDuplicateDetection = false;
this.requiresSession = false;
this.deadLetteringOnMessageExpiration = false;
this.status = EntityStatus.ACTIVE;
}
/**
* Initializes a new instance based on the specified {@link QueueProperties} instance. This is useful for creating a
* new queue based on the properties of an existing queue.
*
* @param queue Existing queue to create options with.
*/
public CreateQueueOptions(QueueProperties queue) {
Objects.requireNonNull(queue, "'queue' cannot be null.");
Objects.requireNonNull(queue.getName(), "Queue name cannot be null.");
if (queue.getName().isEmpty()) {
final ClientLogger logger = new ClientLogger(CreateQueueOptions.class);
throw logger.logExceptionAsError(new IllegalArgumentException("Queue name cannot be empty."));
}
this.name = queue.getName();
this.autoDeleteOnIdle = queue.getAutoDeleteOnIdle();
this.defaultMessageTimeToLive = queue.getDefaultMessageTimeToLive();
this.deadLetteringOnMessageExpiration = queue.deadLetteringOnMessageExpiration() != null
? queue.deadLetteringOnMessageExpiration()
: false;
this.duplicateDetectionHistoryTimeWindow = queue.getDuplicateDetectionHistoryTimeWindow() != null
? queue.getDuplicateDetectionHistoryTimeWindow()
: DEFAULT_DUPLICATE_DETECTION_DURATION;
this.enableBatchedOperations = queue.enableBatchedOperations() != null
? queue.enableBatchedOperations()
: false;
this.enablePartitioning = queue.enablePartitioning() != null
? queue.enablePartitioning()
: false;
this.forwardTo = queue.getForwardTo();
this.forwardDeadLetteredMessagesTo = queue.getForwardDeadLetteredMessagesTo();
this.lockDuration = queue.getLockDuration();
this.maxDeliveryCount = queue.getMaxDeliveryCount() != null
? queue.getMaxDeliveryCount()
: DEFAULT_MAX_DELIVERY_COUNT;
this.maxSizeInMegabytes = queue.getMaxSizeInMegabytes() != null
? queue.getMaxSizeInMegabytes()
: DEFAULT_QUEUE_SIZE;
this.requiresDuplicateDetection = queue.requiresDuplicateDetection() != null
? queue.requiresDuplicateDetection()
: false;
this.requiresSession = queue.requiresSession() != null
? queue.requiresSession()
: false;
this.status = queue.getStatus();
this.userMetadata = queue.getUserMetadata();
}
/**
* Gets the name of the queue.
*
* @return The name of the queue.
*/
public String getName() {
return name;
}
/**
* Get the autoDeleteOnIdle property: ISO 8601 timeSpan idle interval after which the queue is automatically
* deleted. The minimum duration is 5 minutes.
*
* @return the autoDeleteOnIdle value.
*/
public Duration getAutoDeleteOnIdle() {
return this.autoDeleteOnIdle;
}
/**
* Set the autoDeleteOnIdle property: ISO 8601 timeSpan idle interval after which the queue is automatically
* deleted. The minimum duration is 5 minutes.
*
* @param autoDeleteOnIdle the autoDeleteOnIdle value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setAutoDeleteOnIdle(Duration autoDeleteOnIdle) {
this.autoDeleteOnIdle = autoDeleteOnIdle;
return this;
}
/**
* Get the defaultMessageTimeToLive property: ISO 8601 default message timespan to live value. This is the duration
* after which the message expires, starting from when the message is sent to Service Bus. This is the default value
* used when TimeToLive is not set on a message itself.
*
* @return the defaultMessageTimeToLive value.
*/
public Duration getDefaultMessageTimeToLive() {
return this.defaultMessageTimeToLive;
}
/**
* Set the defaultMessageTimeToLive property: ISO 8601 default message timespan to live value. This is the duration
* after which the message expires, starting from when the message is sent to Service Bus. This is the default value
* used when TimeToLive is not set on a message itself.
*
* @param defaultMessageTimeToLive the defaultMessageTimeToLive value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setDefaultMessageTimeToLive(Duration defaultMessageTimeToLive) {
this.defaultMessageTimeToLive = defaultMessageTimeToLive;
return this;
}
/**
* Get the deadLetteringOnMessageExpiration property: A value that indicates whether this queue has dead letter
* support when a message expires.
*
* @return the deadLetteringOnMessageExpiration value.
*/
public boolean deadLetteringOnMessageExpiration() {
return this.deadLetteringOnMessageExpiration;
}
/**
* Set the deadLetteringOnMessageExpiration property: A value that indicates whether this queue has dead letter
* support when a message expires.
*
* @param deadLetteringOnMessageExpiration the deadLetteringOnMessageExpiration value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setDeadLetteringOnMessageExpiration(boolean deadLetteringOnMessageExpiration) {
this.deadLetteringOnMessageExpiration = deadLetteringOnMessageExpiration;
return this;
}
/**
* Get the duplicateDetectionHistoryTimeWindow property: ISO 8601 timeSpan structure that defines the duration of
* the duplicate detection history. The default value is 10 minutes.
*
* @return the duplicateDetectionHistoryTimeWindow value.
*/
public Duration getDuplicateDetectionHistoryTimeWindow() {
return this.duplicateDetectionHistoryTimeWindow;
}
/**
* Set the duplicateDetectionHistoryTimeWindow property: ISO 8601 timeSpan structure that defines the duration of
* the duplicate detection history. The default value is 10 minutes.
*
* @param duplicateDetectionHistoryTimeWindow the duplicateDetectionHistoryTimeWindow value to set.
*
* @return the CreateQueueOptions object itself.
*/
/**
* Get the enableBatchedOperations property: Value that indicates whether server-side batched operations are
* enabled.
*
* @return the enableBatchedOperations value.
*/
public boolean enableBatchedOperations() {
return this.enableBatchedOperations;
}
/**
* Set the enableBatchedOperations property: Value that indicates whether server-side batched operations are
* enabled.
*
* @param enableBatchedOperations the enableBatchedOperations value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setEnableBatchedOperations(boolean enableBatchedOperations) {
this.enableBatchedOperations = enableBatchedOperations;
return this;
}
/**
* Get the enablePartitioning property: A value that indicates whether the queue is to be partitioned across
* multiple message brokers.
*
* @return the enablePartitioning value.
*/
public boolean enablePartitioning() {
return this.enablePartitioning;
}
/**
* Set the enablePartitioning property: A value that indicates whether the queue is to be partitioned across
* multiple message brokers.
*
* @param enablePartitioning the enablePartitioning value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setEnablePartitioning(boolean enablePartitioning) {
this.enablePartitioning = enablePartitioning;
return this;
}
/**
* Get the forwardTo property: The name of the recipient entity to which all the messages sent to the queue are
* forwarded to.
*
* @return the forwardTo value.
*/
public String getForwardTo() {
return this.forwardTo;
}
/**
* Set the forwardTo property: The name of the recipient entity to which all the messages sent to the queue are
* forwarded to.
*
* @param forwardTo the forwardTo value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setForwardTo(String forwardTo) {
this.forwardTo = forwardTo;
return this;
}
/**
* Get the forwardDeadLetteredMessagesTo property: The name of the recipient entity to which all the dead-lettered
* messages of this queue are forwarded to.
*
* @return the forwardDeadLetteredMessagesTo value.
*/
public String getForwardDeadLetteredMessagesTo() {
return this.forwardDeadLetteredMessagesTo;
}
/**
* Set the forwardDeadLetteredMessagesTo property: The name of the recipient entity to which all the dead-lettered
* messages of this queue are forwarded to.
*
* @param forwardDeadLetteredMessagesTo the forwardDeadLetteredMessagesTo value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setForwardDeadLetteredMessagesTo(String forwardDeadLetteredMessagesTo) {
this.forwardDeadLetteredMessagesTo = forwardDeadLetteredMessagesTo;
return this;
}
/**
* Get the lockDuration property: ISO 8601 timespan duration of a peek-lock; that is, the amount of time that the
* message is locked for other receivers. The maximum value for LockDuration is 5 minutes; the default value is 1
* minute.
*
* @return the lockDuration value.
*/
public Duration getLockDuration() {
return this.lockDuration;
}
/**
* Set the lockDuration property: ISO 8601 timespan duration of a peek-lock; that is, the amount of time that the
* message is locked for other receivers. The maximum value for LockDuration is 5 minutes; the default value is 1
* minute.
*
* @param lockDuration the lockDuration value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setLockDuration(Duration lockDuration) {
this.lockDuration = lockDuration;
return this;
}
/**
* Get the maxDeliveryCount property: The maximum delivery count. A message is automatically deadlettered after this
* number of deliveries. Default value is 10.
*
* @return the maxDeliveryCount value.
*/
public int getMaxDeliveryCount() {
return this.maxDeliveryCount;
}
/**
* Set the maxDeliveryCount property: The maximum delivery count. A message is automatically deadlettered after this
* number of deliveries. Default value is 10.
*
* @param maxDeliveryCount the maxDeliveryCount value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setMaxDeliveryCount(int maxDeliveryCount) {
this.maxDeliveryCount = maxDeliveryCount;
return this;
}
/**
* Get the maxSizeInMegabytes property: The maximum size of the queue in megabytes, which is the size of memory
* allocated for the queue.
*
* @return the maxSizeInMegabytes value.
*/
public int getMaxSizeInMegabytes() {
return this.maxSizeInMegabytes;
}
/**
* Set the maxSizeInMegabytes property: The maximum size of the queue in megabytes, which is the size of memory
* allocated for the queue.
*
* @param maxSizeInMegabytes the maxSizeInMegabytes value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setMaxSizeInMegabytes(int maxSizeInMegabytes) {
this.maxSizeInMegabytes = maxSizeInMegabytes;
return this;
}
/**
* Get the requiresDuplicateDetection property: A value indicating if this queue requires duplicate detection.
*
* @return the requiresDuplicateDetection value.
*/
public boolean requiresDuplicateDetection() {
return this.requiresDuplicateDetection;
}
/**
* Set the requiresDuplicateDetection property: A value indicating if this queue requires duplicate detection.
*
* @param requiresDuplicateDetection the requiresDuplicateDetection value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setRequiresDuplicateDetection(boolean requiresDuplicateDetection) {
this.requiresDuplicateDetection = requiresDuplicateDetection;
return this;
}
/**
* Get the requiresSession property: A value that indicates whether the queue supports the concept of sessions.
*
* @return the requiresSession value.
*/
public boolean requiresSession() {
return this.requiresSession;
}
/**
* Set the requiresSession property: A value that indicates whether the queue supports the concept of sessions.
*
* @param requiresSession the requiresSession value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setRequiresSession(boolean requiresSession) {
this.requiresSession = requiresSession;
return this;
}
/**
* Get the status property: Status of a Service Bus resource.
*
* @return the status value.
*/
public EntityStatus getStatus() {
return this.status;
}
/**
* Set the status property: Status of a Service Bus resource.
*
* @param status the status value to set.
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setStatus(EntityStatus status) {
this.status = status;
return this;
}
/**
* Get the userMetadata property: Custom metdata that user can associate with the description. Max length is 1024
* chars.
*
* @return the userMetadata value.
*/
public String getUserMetadata() {
return this.userMetadata;
}
/**
* Set the userMetadata property: Custom metdata that user can associate with the description. Max length is 1024
* chars.
*
* @param userMetadata the userMetadata value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setUserMetadata(String userMetadata) {
this.userMetadata = userMetadata;
return this;
}
} | class CreateQueueOptions {
private final String name;
private Duration autoDeleteOnIdle;
private Duration defaultMessageTimeToLive;
private boolean deadLetteringOnMessageExpiration;
private Duration duplicateDetectionHistoryTimeWindow;
private boolean enableBatchedOperations;
private boolean enablePartitioning;
private String forwardTo;
private String forwardDeadLetteredMessagesTo;
private Duration lockDuration;
private int maxDeliveryCount;
private long maxSizeInMegabytes;
private boolean requiresDuplicateDetection;
private boolean requiresSession;
private String userMetadata;
private EntityStatus status;
/**
* Creates an instance with the name of the queue. Default values for the queue are populated. The properties
* populated with defaults are:
*
* <ul>
* <li>{@link
* <li>{@link
* <li>{@link
* detection is disabled.</li>
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* </ul>
*
* @param queueName Name of the queue.
*
* @throws NullPointerException if {@code queueName} is a null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
*/
public CreateQueueOptions(String queueName) {
Objects.requireNonNull(queueName, "'queueName' cannot be null.");
if (queueName.isEmpty()) {
ClientLogger logger = new ClientLogger(CreateQueueOptions.class);
throw logger.logThrowableAsError(new IllegalArgumentException("Queue name cannot be empty."));
}
this.name = queueName;
this.autoDeleteOnIdle = MAX_DURATION;
this.defaultMessageTimeToLive = MAX_DURATION;
this.duplicateDetectionHistoryTimeWindow = DEFAULT_DUPLICATE_DETECTION_DURATION;
this.enableBatchedOperations = true;
this.enablePartitioning = false;
this.lockDuration = DEFAULT_LOCK_DURATION;
this.maxDeliveryCount = DEFAULT_MAX_DELIVERY_COUNT;
this.maxSizeInMegabytes = DEFAULT_QUEUE_SIZE;
this.requiresDuplicateDetection = false;
this.requiresSession = false;
this.deadLetteringOnMessageExpiration = false;
this.status = EntityStatus.ACTIVE;
}
/**
* Initializes a new instance based on the specified {@link QueueProperties} instance. This is useful for creating a
* new queue based on the properties of an existing queue.
*
* @param queue Existing queue to create options with.
*/
public CreateQueueOptions(QueueProperties queue) {
Objects.requireNonNull(queue, "'queue' cannot be null.");
Objects.requireNonNull(queue.getName(), "Queue name cannot be null.");
if (queue.getName().isEmpty()) {
final ClientLogger logger = new ClientLogger(CreateQueueOptions.class);
throw logger.logExceptionAsError(new IllegalArgumentException("Queue name cannot be empty."));
}
this.name = queue.getName();
this.autoDeleteOnIdle = queue.getAutoDeleteOnIdle();
this.defaultMessageTimeToLive = queue.getDefaultMessageTimeToLive();
this.deadLetteringOnMessageExpiration = queue.isDeadLetteringOnMessageExpiration();
this.duplicateDetectionHistoryTimeWindow = queue.getDuplicateDetectionHistoryTimeWindow() != null
? queue.getDuplicateDetectionHistoryTimeWindow()
: DEFAULT_DUPLICATE_DETECTION_DURATION;
this.enableBatchedOperations = queue.enableBatchedOperations();
this.enablePartitioning = queue.enablePartitioning();
this.forwardTo = queue.getForwardTo();
this.forwardDeadLetteredMessagesTo = queue.getForwardDeadLetteredMessagesTo();
this.lockDuration = queue.getLockDuration();
this.maxDeliveryCount = queue.getMaxDeliveryCount();
this.maxSizeInMegabytes = queue.getMaxSizeInMegabytes();
this.requiresDuplicateDetection = queue.requiresDuplicateDetection();
this.requiresSession = queue.requiresSession();
this.status = queue.getStatus();
this.userMetadata = queue.getUserMetadata();
}
/**
* Gets the name of the queue.
*
* @return The name of the queue.
*/
public String getName() {
return name;
}
/**
* Get the autoDeleteOnIdle property: ISO 8601 timeSpan idle interval after which the queue is automatically
* deleted. The minimum duration is 5 minutes.
*
* @return the autoDeleteOnIdle value.
*/
public Duration getAutoDeleteOnIdle() {
return this.autoDeleteOnIdle;
}
/**
* Set the autoDeleteOnIdle property: ISO 8601 timeSpan idle interval after which the queue is automatically
* deleted. The minimum duration is 5 minutes.
*
* @param autoDeleteOnIdle the autoDeleteOnIdle value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setAutoDeleteOnIdle(Duration autoDeleteOnIdle) {
this.autoDeleteOnIdle = autoDeleteOnIdle;
return this;
}
/**
* Get the defaultMessageTimeToLive property: ISO 8601 default message timespan to live value. This is the duration
* after which the message expires, starting from when the message is sent to Service Bus. This is the default value
* used when TimeToLive is not set on a message itself.
*
* @return the defaultMessageTimeToLive value.
*/
public Duration getDefaultMessageTimeToLive() {
return this.defaultMessageTimeToLive;
}
/**
* Set the defaultMessageTimeToLive property: ISO 8601 default message timespan to live value. This is the duration
* after which the message expires, starting from when the message is sent to Service Bus. This is the default value
* used when TimeToLive is not set on a message itself.
*
* @param defaultMessageTimeToLive the defaultMessageTimeToLive value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setDefaultMessageTimeToLive(Duration defaultMessageTimeToLive) {
this.defaultMessageTimeToLive = defaultMessageTimeToLive;
return this;
}
/**
* Get the deadLetteringOnMessageExpiration property: A value that indicates whether this queue has dead letter
* support when a message expires.
*
* @return the deadLetteringOnMessageExpiration value.
*/
public boolean deadLetteringOnMessageExpiration() {
return this.deadLetteringOnMessageExpiration;
}
/**
* Set the deadLetteringOnMessageExpiration property: A value that indicates whether this queue has dead letter
* support when a message expires.
*
* @param deadLetteringOnMessageExpiration the deadLetteringOnMessageExpiration value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setDeadLetteringOnMessageExpiration(boolean deadLetteringOnMessageExpiration) {
this.deadLetteringOnMessageExpiration = deadLetteringOnMessageExpiration;
return this;
}
/**
* Get the duplicateDetectionHistoryTimeWindow property: ISO 8601 timeSpan structure that defines the duration of
* the duplicate detection history. The default value is 10 minutes.
*
* @return the duplicateDetectionHistoryTimeWindow value.
*/
public Duration getDuplicateDetectionHistoryTimeWindow() {
return this.duplicateDetectionHistoryTimeWindow;
}
/**
* Set the duplicateDetectionHistoryTimeWindow property: ISO 8601 timeSpan structure that defines the duration of
* the duplicate detection history. The default value is 10 minutes.
*
* @param duplicateDetectionHistoryTimeWindow the duplicateDetectionHistoryTimeWindow value to set.
*
* @return the CreateQueueOptions object itself.
*/
/**
* Get the enableBatchedOperations property: Value that indicates whether server-side batched operations are
* enabled.
*
* @return the enableBatchedOperations value.
*/
public boolean enableBatchedOperations() {
return this.enableBatchedOperations;
}
/**
* Set the enableBatchedOperations property: Value that indicates whether server-side batched operations are
* enabled.
*
* @param enableBatchedOperations the enableBatchedOperations value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setEnableBatchedOperations(boolean enableBatchedOperations) {
this.enableBatchedOperations = enableBatchedOperations;
return this;
}
/**
* Get the enablePartitioning property: A value that indicates whether the queue is to be partitioned across
* multiple message brokers.
*
* @return the enablePartitioning value.
*/
public boolean enablePartitioning() {
return this.enablePartitioning;
}
/**
* Set the enablePartitioning property: A value that indicates whether the queue is to be partitioned across
* multiple message brokers.
*
* @param enablePartitioning the enablePartitioning value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setEnablePartitioning(boolean enablePartitioning) {
this.enablePartitioning = enablePartitioning;
return this;
}
/**
* Get the forwardTo property: The name of the recipient entity to which all the messages sent to the queue are
* forwarded to.
*
* @return the forwardTo value.
*/
public String getForwardTo() {
return this.forwardTo;
}
/**
* Set the forwardTo property: The name of the recipient entity to which all the messages sent to the queue are
* forwarded to.
*
* @param forwardTo the forwardTo value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setForwardTo(String forwardTo) {
this.forwardTo = forwardTo;
return this;
}
/**
* Get the forwardDeadLetteredMessagesTo property: The name of the recipient entity to which all the dead-lettered
* messages of this queue are forwarded to.
*
* @return the forwardDeadLetteredMessagesTo value.
*/
public String getForwardDeadLetteredMessagesTo() {
return this.forwardDeadLetteredMessagesTo;
}
/**
* Set the forwardDeadLetteredMessagesTo property: The name of the recipient entity to which all the dead-lettered
* messages of this queue are forwarded to.
*
* @param forwardDeadLetteredMessagesTo the forwardDeadLetteredMessagesTo value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setForwardDeadLetteredMessagesTo(String forwardDeadLetteredMessagesTo) {
this.forwardDeadLetteredMessagesTo = forwardDeadLetteredMessagesTo;
return this;
}
/**
* Get the lockDuration property: ISO 8601 timespan duration of a peek-lock; that is, the amount of time that the
* message is locked for other receivers. The maximum value for LockDuration is 5 minutes; the default value is 1
* minute.
*
* @return the lockDuration value.
*/
public Duration getLockDuration() {
return this.lockDuration;
}
/**
* Set the lockDuration property: ISO 8601 timespan duration of a peek-lock; that is, the amount of time that the
* message is locked for other receivers. The maximum value for LockDuration is 5 minutes; the default value is 1
* minute.
*
* @param lockDuration the lockDuration value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setLockDuration(Duration lockDuration) {
this.lockDuration = lockDuration;
return this;
}
/**
* Get the maxDeliveryCount property: The maximum delivery count. A message is automatically deadlettered after this
* number of deliveries. Default value is 10.
*
* @return the maxDeliveryCount value.
*/
public int getMaxDeliveryCount() {
return this.maxDeliveryCount;
}
/**
* Set the maxDeliveryCount property: The maximum delivery count. A message is automatically deadlettered after this
* number of deliveries. Default value is 10.
*
* @param maxDeliveryCount the maxDeliveryCount value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setMaxDeliveryCount(int maxDeliveryCount) {
this.maxDeliveryCount = maxDeliveryCount;
return this;
}
/**
* Get the maxSizeInMegabytes property: The maximum size of the queue in megabytes, which is the size of memory
* allocated for the queue.
*
* @return the maxSizeInMegabytes value.
*/
public long getMaxSizeInMegabytes() {
return this.maxSizeInMegabytes;
}
/**
* Set the maxSizeInMegabytes property: The maximum size of the queue in megabytes, which is the size of memory
* allocated for the queue.
*
* @param maxSizeInMegabytes the maxSizeInMegabytes value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setMaxSizeInMegabytes(int maxSizeInMegabytes) {
this.maxSizeInMegabytes = maxSizeInMegabytes;
return this;
}
/**
* Get the requiresDuplicateDetection property: A value indicating if this queue requires duplicate detection.
*
* @return the requiresDuplicateDetection value.
*/
public boolean requiresDuplicateDetection() {
return this.requiresDuplicateDetection;
}
/**
* Set the requiresDuplicateDetection property: A value indicating if this queue requires duplicate detection.
*
* @param requiresDuplicateDetection the requiresDuplicateDetection value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setRequiresDuplicateDetection(boolean requiresDuplicateDetection) {
this.requiresDuplicateDetection = requiresDuplicateDetection;
return this;
}
/**
* Get the requiresSession property: A value that indicates whether the queue supports the concept of sessions.
*
* @return the requiresSession value.
*/
public boolean requiresSession() {
return this.requiresSession;
}
/**
* Set the requiresSession property: A value that indicates whether the queue supports the concept of sessions.
*
* @param requiresSession the requiresSession value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setRequiresSession(boolean requiresSession) {
this.requiresSession = requiresSession;
return this;
}
/**
* Get the status property: Status of a Service Bus resource.
*
* @return the status value.
*/
public EntityStatus getStatus() {
return this.status;
}
/**
* Set the status property: Status of a Service Bus resource.
*
* @param status the status value to set.
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setStatus(EntityStatus status) {
this.status = status;
return this;
}
/**
* Get the userMetadata property: Custom metdata that user can associate with the description. Max length is 1024
* chars.
*
* @return the userMetadata value.
*/
public String getUserMetadata() {
return this.userMetadata;
}
/**
* Set the userMetadata property: Custom metdata that user can associate with the description. Max length is 1024
* chars.
*
* @param userMetadata the userMetadata value to set.
*
* @return the CreateQueueOptions object itself.
*/
public CreateQueueOptions setUserMetadata(String userMetadata) {
this.userMetadata = userMetadata;
return this;
}
} |
Our guidelines say to do as little validation as possible and offset it to the service. I'd expect the service to do this validation and throw. | void createQueue() {
final String queueName = "some-queue";
final CreateQueueOptions expected = new CreateQueueOptions(queueName)
.setAutoDeleteOnIdle(Duration.ofSeconds(15))
.setDefaultMessageTimeToLive(Duration.ofSeconds(50))
.setDeadLetteringOnMessageExpiration(true)
.setDuplicateDetectionHistoryTimeWindow(Duration.ofSeconds(13))
.setEnableBatchedOperations(false)
.setEnablePartitioning(true)
.setForwardTo("Forward-To-This-Queue")
.setForwardDeadLetteredMessagesTo("Dead-Lettered-Forward-To")
.setLockDuration(Duration.ofSeconds(120))
.setMaxDeliveryCount(15)
.setMaxSizeInMegabytes(2048)
.setRequiresDuplicateDetection(true)
.setRequiresSession(true)
.setUserMetadata("Test-queue-Metadata")
.setStatus(EntityStatus.DISABLED);
final QueueProperties actual = EntityHelper.createQueue(expected);
assertEquals(expected.getName(), actual.getName());
assertEquals(expected.getAutoDeleteOnIdle(), actual.getAutoDeleteOnIdle());
assertEquals(expected.getDefaultMessageTimeToLive(), actual.getDefaultMessageTimeToLive());
assertEquals(expected.deadLetteringOnMessageExpiration(), actual.deadLetteringOnMessageExpiration());
assertEquals(expected.getDuplicateDetectionHistoryTimeWindow(), actual.getDuplicateDetectionHistoryTimeWindow());
assertEquals(expected.enableBatchedOperations(), actual.enableBatchedOperations());
assertEquals(expected.enablePartitioning(), actual.enablePartitioning());
assertEquals(expected.getForwardTo(), actual.getForwardTo());
assertEquals(expected.getForwardDeadLetteredMessagesTo(), actual.getForwardDeadLetteredMessagesTo());
assertEquals(expected.getLockDuration(), actual.getLockDuration());
assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount());
assertEquals(expected.requiresDuplicateDetection(), actual.requiresDuplicateDetection());
assertEquals(expected.requiresSession(), actual.requiresSession());
assertEquals(expected.getUserMetadata(), actual.getUserMetadata());
assertEquals(expected.getStatus(), actual.getStatus());
} | .setMaxSizeInMegabytes(2048) | void createQueue() {
final String queueName = "some-queue";
final CreateQueueOptions expected = new CreateQueueOptions(queueName)
.setAutoDeleteOnIdle(Duration.ofSeconds(15))
.setDefaultMessageTimeToLive(Duration.ofSeconds(50))
.setDeadLetteringOnMessageExpiration(true)
.setDuplicateDetectionHistoryTimeWindow(Duration.ofSeconds(13))
.setEnableBatchedOperations(false)
.setEnablePartitioning(true)
.setForwardTo("Forward-To-This-Queue")
.setForwardDeadLetteredMessagesTo("Dead-Lettered-Forward-To")
.setLockDuration(Duration.ofSeconds(120))
.setMaxDeliveryCount(15)
.setMaxSizeInMegabytes(2048)
.setRequiresDuplicateDetection(true)
.setRequiresSession(true)
.setUserMetadata("Test-queue-Metadata")
.setStatus(EntityStatus.DISABLED);
final QueueDescription actual = EntityHelper.getQueueDescription(expected);
assertEquals(expected.getAutoDeleteOnIdle(), actual.getAutoDeleteOnIdle());
assertEquals(expected.getDefaultMessageTimeToLive(), actual.getDefaultMessageTimeToLive());
assertEquals(expected.deadLetteringOnMessageExpiration(), actual.isDeadLetteringOnMessageExpiration());
assertEquals(expected.getDuplicateDetectionHistoryTimeWindow(), actual.getDuplicateDetectionHistoryTimeWindow());
assertEquals(expected.enableBatchedOperations(), actual.isEnableBatchedOperations());
assertEquals(expected.enablePartitioning(), actual.isEnablePartitioning());
assertEquals(expected.getForwardTo(), actual.getForwardTo());
assertEquals(expected.getForwardDeadLetteredMessagesTo(), actual.getForwardDeadLetteredMessagesTo());
assertEquals(expected.getLockDuration(), actual.getLockDuration());
assertEquals(expected.getMaxDeliveryCount(), actual.getMaxDeliveryCount());
assertEquals(expected.requiresDuplicateDetection(), actual.isRequiresDuplicateDetection());
assertEquals(expected.requiresSession(), actual.isRequiresSession());
assertEquals(expected.getUserMetadata(), actual.getUserMetadata());
assertEquals(expected.getStatus(), actual.getStatus());
} | class EntityHelperTest {
@Test
@Test
void setQueueName() {
final String newName = "I'm a new name";
final CreateQueueOptions options = new CreateQueueOptions("some name");
final QueueProperties properties = EntityHelper.createQueue(options);
EntityHelper.setQueueName(properties, newName);
assertEquals(newName, properties.getName());
}
} | class EntityHelperTest {
@Test
@Test
void setQueueName() {
final String newName = "I'm a new name";
final CreateQueueOptions options = new CreateQueueOptions("some name");
final QueueProperties properties = EntityHelper.toModel(EntityHelper.getQueueDescription(options));
EntityHelper.setQueueName(properties, newName);
assertEquals(newName, properties.getName());
}
} |
negative value check ? | public CreateSubscriptionOptions setMaxDeliveryCount(int maxDeliveryCount) {
this.maxDeliveryCount = maxDeliveryCount;
return this;
} | return this; | public CreateSubscriptionOptions setMaxDeliveryCount(int maxDeliveryCount) {
this.maxDeliveryCount = maxDeliveryCount;
return this;
} | class CreateSubscriptionOptions {
private final String topicName;
private final String subscriptionName;
private Duration lockDuration;
private boolean requiresSession;
private Duration defaultMessageTimeToLive;
private boolean deadLetteringOnMessageExpiration;
private boolean deadLetteringOnFilterEvaluationExceptions;
private int maxDeliveryCount;
private boolean enableBatchedOperations;
private EntityStatus status;
private String forwardTo;
private String userMetadata;
private String forwardDeadLetteredMessagesTo;
private Duration autoDeleteOnIdle;
/**
* Creates an instance with the name of the subscription and its associated topic. Default values for the
* subscription are populated. The properties populated with defaults are:
*
* <ul>
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* </ul>
*
* @param topicName Name of the topic associated with this subscription.
* @param subscriptionName Name of the subscription.
*
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
*/
public CreateSubscriptionOptions(String topicName, String subscriptionName) {
final ClientLogger logger = new ClientLogger(CreateSubscriptionOptions.class);
if (topicName == null) {
throw logger.logExceptionAsError(new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
throw logger.logExceptionAsError(new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
}
this.topicName = topicName;
this.subscriptionName = subscriptionName;
this.autoDeleteOnIdle = MAX_DURATION;
this.deadLetteringOnMessageExpiration = false;
this.deadLetteringOnFilterEvaluationExceptions = true;
this.defaultMessageTimeToLive = MAX_DURATION;
this.enableBatchedOperations = true;
this.lockDuration = DEFAULT_LOCK_DURATION;
this.maxDeliveryCount = 10;
this.requiresSession = false;
this.status = EntityStatus.ACTIVE;
}
/**
* Initializes a new instance based on the specified {@link SubscriptionProperties} instance. This is useful for
* creating a new queue based on the properties of an existing subscription.
*
* @param subscription Existing subscription to create options with.
*/
public CreateSubscriptionOptions(SubscriptionProperties subscription) {
Objects.requireNonNull(subscription, "'subscription' cannot be null.");
Objects.requireNonNull(subscription.getTopicName(), "Topic name cannot be null.");
Objects.requireNonNull(subscription.getSubscriptionName(), "Subscription name cannot be null.");
this.topicName = subscription.getTopicName();
this.subscriptionName = subscription.getSubscriptionName();
this.autoDeleteOnIdle = subscription.getAutoDeleteOnIdle();
this.deadLetteringOnMessageExpiration = subscription.deadLetteringOnMessageExpiration() != null
? subscription.deadLetteringOnMessageExpiration()
: false;
this.defaultMessageTimeToLive = subscription.getDefaultMessageTimeToLive();
this.enableBatchedOperations = subscription.enableBatchedOperations() != null
? subscription.enableBatchedOperations()
: false;
this.forwardTo = subscription.getForwardTo();
this.forwardDeadLetteredMessagesTo = subscription.getForwardDeadLetteredMessagesTo();
this.lockDuration = subscription.getLockDuration();
this.maxDeliveryCount = subscription.getMaxDeliveryCount() != null
? subscription.getMaxDeliveryCount()
: DEFAULT_MAX_DELIVERY_COUNT;
this.requiresSession = subscription.requiresSession() != null
? subscription.requiresSession()
: false;
this.status = subscription.getStatus();
this.userMetadata = subscription.getUserMetadata();
}
/**
* Gets the name of the topic under which subscription exists.
*
* @return The name of the topic under which subscription exists.
*/
public String getTopicName() {
return topicName;
}
/**
* Gets the name of the subscription.
*
* @return The name of the subscription.
*/
public String getSubscriptionName() {
return subscriptionName;
}
/**
* Get the lockDuration property: ISO 8601 timespan duration of a peek-lock; that is, the amount of time that the
* message is locked for other receivers. The maximum value for LockDuration is 5 minutes; the default value is 1
* minute.
*
* @return the lockDuration value.
*/
public Duration getLockDuration() {
return this.lockDuration;
}
/**
* Set the lockDuration property: ISO 8601 timespan duration of a peek-lock; that is, the amount of time that the
* message is locked for other receivers. The maximum value for LockDuration is 5 minutes; the default value is 1
* minute.
*
* @param lockDuration the lockDuration value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setLockDuration(Duration lockDuration) {
this.lockDuration = lockDuration;
return this;
}
/**
* Get the requiresSession property: A value that indicates whether the queue supports the concept of sessions.
*
* @return the requiresSession value.
*/
public boolean requiresSession() {
return this.requiresSession;
}
/**
* Set the requiresSession property: A value that indicates whether the queue supports the concept of sessions.
*
* @param requiresSession the requiresSession value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setRequiresSession(boolean requiresSession) {
this.requiresSession = requiresSession;
return this;
}
/**
* Get the defaultMessageTimeToLive property: ISO 8601 default message timespan to live value. This is the duration
* after which the message expires, starting from when the message is sent to Service Bus. This is the default value
* used when TimeToLive is not set on a message itself.
*
* @return the defaultMessageTimeToLive value.
*/
public Duration getDefaultMessageTimeToLive() {
return this.defaultMessageTimeToLive;
}
/**
* Set the defaultMessageTimeToLive property: ISO 8601 default message timespan to live value. This is the duration
* after which the message expires, starting from when the message is sent to Service Bus. This is the default value
* used when TimeToLive is not set on a message itself.
*
* @param defaultMessageTimeToLive the defaultMessageTimeToLive value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setDefaultMessageTimeToLive(Duration defaultMessageTimeToLive) {
this.defaultMessageTimeToLive = defaultMessageTimeToLive;
return this;
}
/**
* Get the deadLetteringOnMessageExpiration property: A value that indicates whether this subscription has dead
* letter support when a message expires.
*
* @return the deadLetteringOnMessageExpiration value.
*/
public boolean deadLetteringOnMessageExpiration() {
return this.deadLetteringOnMessageExpiration;
}
/**
* Set the deadLetteringOnMessageExpiration property: A value that indicates whether this subscription has dead
* letter support when a message expires.
*
* @param deadLetteringOnMessageExpiration the deadLetteringOnMessageExpiration value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setDeadLetteringOnMessageExpiration(boolean deadLetteringOnMessageExpiration) {
this.deadLetteringOnMessageExpiration = deadLetteringOnMessageExpiration;
return this;
}
/**
* Get the deadLetteringOnFilterEvaluationExceptions property: A value that indicates whether this subscription has
* dead letter support when a message expires.
*
* @return the deadLetteringOnFilterEvaluationExceptions value.
*/
public boolean enableDeadLetteringOnFilterEvaluationExceptions() {
return this.deadLetteringOnFilterEvaluationExceptions;
}
/**
* Set the deadLetteringOnFilterEvaluationExceptions property: A value that indicates whether this subscription has
* dead letter support when a message expires.
*
* @param deadLetteringOnFilterEvaluationExceptions the deadLetteringOnFilterEvaluationExceptions value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setEnableDeadLetteringOnFilterEvaluationExceptions(
boolean deadLetteringOnFilterEvaluationExceptions) {
this.deadLetteringOnFilterEvaluationExceptions = deadLetteringOnFilterEvaluationExceptions;
return this;
}
/**
* Get the maxDeliveryCount property: The maximum delivery count. A message is automatically deadlettered after this
* number of deliveries. Default value is 10.
*
* @return the maxDeliveryCount value.
*/
public int getMaxDeliveryCount() {
return this.maxDeliveryCount;
}
/**
* Set the maxDeliveryCount property: The maximum delivery count. A message is automatically deadlettered after this
* number of deliveries. Default value is 10.
*
* @param maxDeliveryCount the maxDeliveryCount value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
/**
* Get the enableBatchedOperations property: Value that indicates whether server-side batched operations are
* enabled.
*
* @return the enableBatchedOperations value.
*/
public boolean enableBatchedOperations() {
return this.enableBatchedOperations;
}
/**
* Set the enableBatchedOperations property: Value that indicates whether server-side batched operations are
* enabled.
*
* @param enableBatchedOperations the enableBatchedOperations value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setEnableBatchedOperations(boolean enableBatchedOperations) {
this.enableBatchedOperations = enableBatchedOperations;
return this;
}
/**
* Get the status property: Status of a Service Bus resource.
*
* @return the status value.
*/
public EntityStatus getStatus() {
return this.status;
}
/**
* Set the status property: Status of a Service Bus resource.
*
* @param status the status value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setStatus(EntityStatus status) {
this.status = status;
return this;
}
/**
* Get the forwardTo property: The name of the recipient entity to which all the messages sent to the subscription
* are forwarded to.
*
* @return the forwardTo value.
*/
public String getForwardTo() {
return this.forwardTo;
}
/**
* Set the forwardTo property: The name of the recipient entity to which all the messages sent to the subscription
* are forwarded to.
*
* @param forwardTo the forwardTo value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setForwardTo(String forwardTo) {
this.forwardTo = forwardTo;
return this;
}
/**
* Get the userMetadata property: Metadata associated with the subscription. Maximum number of characters is 1024.
*
* @return the userMetadata value.
*/
public String getUserMetadata() {
return this.userMetadata;
}
/**
* Set the userMetadata property: Metadata associated with the subscription. Maximum number of characters is 1024.
*
* @param userMetadata the userMetadata value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setUserMetadata(String userMetadata) {
this.userMetadata = userMetadata;
return this;
}
/**
* Get the forwardDeadLetteredMessagesTo property: The name of the recipient entity to which all the messages sent
* to the subscription are forwarded to.
*
* @return the forwardDeadLetteredMessagesTo value.
*/
public String getForwardDeadLetteredMessagesTo() {
return this.forwardDeadLetteredMessagesTo;
}
/**
* Set the forwardDeadLetteredMessagesTo property: The name of the recipient entity to which all the messages sent
* to the subscription are forwarded to.
*
* @param forwardDeadLetteredMessagesTo the forwardDeadLetteredMessagesTo value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setForwardDeadLetteredMessagesTo(String forwardDeadLetteredMessagesTo) {
this.forwardDeadLetteredMessagesTo = forwardDeadLetteredMessagesTo;
return this;
}
/**
* Get the autoDeleteOnIdle property: ISO 8601 timeSpan idle interval after which the subscription is automatically
* deleted. The minimum duration is 5 minutes.
*
* @return the autoDeleteOnIdle value.
*/
public Duration getAutoDeleteOnIdle() {
return this.autoDeleteOnIdle;
}
/**
* Set the autoDeleteOnIdle property: ISO 8601 timeSpan idle interval after which the subscription is automatically
* deleted. The minimum duration is 5 minutes.
*
* @param autoDeleteOnIdle the autoDeleteOnIdle value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setAutoDeleteOnIdle(Duration autoDeleteOnIdle) {
this.autoDeleteOnIdle = autoDeleteOnIdle;
return this;
}
} | class CreateSubscriptionOptions {
private final String topicName;
private final String subscriptionName;
private Duration autoDeleteOnIdle;
private Duration defaultMessageTimeToLive;
private boolean deadLetteringOnMessageExpiration;
private boolean deadLetteringOnFilterEvaluationExceptions;
private boolean enableBatchedOperations;
private String forwardTo;
private String forwardDeadLetteredMessagesTo;
private EntityStatus status;
private Duration lockDuration;
private int maxDeliveryCount;
private boolean requiresSession;
private String userMetadata;
/**
* Creates an instance with the name of the subscription and its associated topic. Default values for the
* subscription are populated. The properties populated with defaults are:
*
* <ul>
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* <li>{@link
* </ul>
*
* @param topicName Name of the topic associated with this subscription.
* @param subscriptionName Name of the subscription.
*
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
*/
public CreateSubscriptionOptions(String topicName, String subscriptionName) {
final ClientLogger logger = new ClientLogger(CreateSubscriptionOptions.class);
if (topicName == null) {
throw logger.logExceptionAsError(new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
throw logger.logExceptionAsError(new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
}
this.topicName = topicName;
this.subscriptionName = subscriptionName;
this.autoDeleteOnIdle = MAX_DURATION;
this.deadLetteringOnMessageExpiration = false;
this.deadLetteringOnFilterEvaluationExceptions = true;
this.defaultMessageTimeToLive = MAX_DURATION;
this.enableBatchedOperations = true;
this.lockDuration = DEFAULT_LOCK_DURATION;
this.maxDeliveryCount = 10;
this.requiresSession = false;
this.status = EntityStatus.ACTIVE;
}
/**
* Initializes a new instance based on the specified {@link SubscriptionProperties} instance. This is useful for
* creating a new subscription based on the properties of an existing subscription.
*
* @param subscription Existing subscription to create options with.
*/
public CreateSubscriptionOptions(SubscriptionProperties subscription) {
Objects.requireNonNull(subscription, "'subscription' cannot be null.");
Objects.requireNonNull(subscription.getTopicName(), "Topic name cannot be null.");
Objects.requireNonNull(subscription.getSubscriptionName(), "Subscription name cannot be null.");
this.topicName = subscription.getTopicName();
this.subscriptionName = subscription.getSubscriptionName();
this.autoDeleteOnIdle = subscription.getAutoDeleteOnIdle();
this.deadLetteringOnMessageExpiration = subscription.deadLetteringOnMessageExpiration();
this.deadLetteringOnFilterEvaluationExceptions = subscription.enableDeadLetteringOnFilterEvaluationExceptions();
this.defaultMessageTimeToLive = subscription.getDefaultMessageTimeToLive();
this.enableBatchedOperations = subscription.enableBatchedOperations();
this.forwardTo = subscription.getForwardTo();
this.forwardDeadLetteredMessagesTo = subscription.getForwardDeadLetteredMessagesTo();
this.lockDuration = subscription.getLockDuration();
this.maxDeliveryCount = subscription.getMaxDeliveryCount();
this.requiresSession = subscription.requiresSession();
this.status = subscription.getStatus();
this.userMetadata = subscription.getUserMetadata();
}
/**
* Gets the name of the topic under which subscription exists.
*
* @return The name of the topic under which subscription exists.
*/
public String getTopicName() {
return topicName;
}
/**
* Gets the name of the subscription.
*
* @return The name of the subscription.
*/
public String getSubscriptionName() {
return subscriptionName;
}
/**
* Get the lockDuration property: ISO 8601 timespan duration of a peek-lock; that is, the amount of time that the
* message is locked for other receivers. The maximum value for LockDuration is 5 minutes; the default value is 1
* minute.
*
* @return the lockDuration value.
*/
public Duration getLockDuration() {
return this.lockDuration;
}
/**
* Set the lockDuration property: ISO 8601 timespan duration of a peek-lock; that is, the amount of time that the
* message is locked for other receivers. The maximum value for LockDuration is 5 minutes; the default value is 1
* minute.
*
* @param lockDuration the lockDuration value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setLockDuration(Duration lockDuration) {
this.lockDuration = lockDuration;
return this;
}
/**
* Get the requiresSession property: A value that indicates whether the queue supports the concept of sessions.
*
* @return the requiresSession value.
*/
public boolean requiresSession() {
return this.requiresSession;
}
/**
* Set the requiresSession property: A value that indicates whether the queue supports the concept of sessions.
*
* @param requiresSession the requiresSession value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setRequiresSession(boolean requiresSession) {
this.requiresSession = requiresSession;
return this;
}
/**
* Get the defaultMessageTimeToLive property: ISO 8601 default message timespan to live value. This is the duration
* after which the message expires, starting from when the message is sent to Service Bus. This is the default value
* used when TimeToLive is not set on a message itself.
*
* @return the defaultMessageTimeToLive value.
*/
public Duration getDefaultMessageTimeToLive() {
return this.defaultMessageTimeToLive;
}
/**
* Set the defaultMessageTimeToLive property: ISO 8601 default message timespan to live value. This is the duration
* after which the message expires, starting from when the message is sent to Service Bus. This is the default value
* used when TimeToLive is not set on a message itself.
*
* @param defaultMessageTimeToLive the defaultMessageTimeToLive value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setDefaultMessageTimeToLive(Duration defaultMessageTimeToLive) {
this.defaultMessageTimeToLive = defaultMessageTimeToLive;
return this;
}
/**
* Get the deadLetteringOnMessageExpiration property: A value that indicates whether this subscription has dead
* letter support when a message expires.
*
* @return the deadLetteringOnMessageExpiration value.
*/
public boolean deadLetteringOnMessageExpiration() {
return this.deadLetteringOnMessageExpiration;
}
/**
* Set the deadLetteringOnMessageExpiration property: A value that indicates whether this subscription has dead
* letter support when a message expires.
*
* @param deadLetteringOnMessageExpiration the deadLetteringOnMessageExpiration value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setDeadLetteringOnMessageExpiration(boolean deadLetteringOnMessageExpiration) {
this.deadLetteringOnMessageExpiration = deadLetteringOnMessageExpiration;
return this;
}
/**
* Get the deadLetteringOnFilterEvaluationExceptions property: A value that indicates whether this subscription has
* dead letter support when a message expires.
*
* @return the deadLetteringOnFilterEvaluationExceptions value.
*/
public boolean enableDeadLetteringOnFilterEvaluationExceptions() {
return this.deadLetteringOnFilterEvaluationExceptions;
}
/**
* Set the deadLetteringOnFilterEvaluationExceptions property: A value that indicates whether this subscription has
* dead letter support when a message expires.
*
* @param deadLetteringOnFilterEvaluationExceptions the deadLetteringOnFilterEvaluationExceptions value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setEnableDeadLetteringOnFilterEvaluationExceptions(
boolean deadLetteringOnFilterEvaluationExceptions) {
this.deadLetteringOnFilterEvaluationExceptions = deadLetteringOnFilterEvaluationExceptions;
return this;
}
/**
* Get the maxDeliveryCount property: The maximum delivery count. A message is automatically deadlettered after this
* number of deliveries. Default value is 10.
*
* @return the maxDeliveryCount value.
*/
public int getMaxDeliveryCount() {
return this.maxDeliveryCount;
}
/**
* Set the maxDeliveryCount property: The maximum delivery count. A message is automatically deadlettered after this
* number of deliveries. Default value is 10.
*
* @param maxDeliveryCount the maxDeliveryCount value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
/**
* Get the enableBatchedOperations property: Value that indicates whether server-side batched operations are
* enabled.
*
* @return the enableBatchedOperations value.
*/
public boolean enableBatchedOperations() {
return this.enableBatchedOperations;
}
/**
* Set the enableBatchedOperations property: Value that indicates whether server-side batched operations are
* enabled.
*
* @param enableBatchedOperations the enableBatchedOperations value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setEnableBatchedOperations(boolean enableBatchedOperations) {
this.enableBatchedOperations = enableBatchedOperations;
return this;
}
/**
* Get the status property: Status of a Service Bus resource.
*
* @return the status value.
*/
public EntityStatus getStatus() {
return this.status;
}
/**
* Set the status property: Status of a Service Bus resource.
*
* @param status the status value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setStatus(EntityStatus status) {
this.status = status;
return this;
}
/**
* Get the forwardTo property: The name of the recipient entity to which all the messages sent to the subscription
* are forwarded to.
*
* @return the forwardTo value.
*/
public String getForwardTo() {
return this.forwardTo;
}
/**
* Set the forwardTo property: The name of the recipient entity to which all the messages sent to the subscription
* are forwarded to.
*
* @param forwardTo the forwardTo value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setForwardTo(String forwardTo) {
this.forwardTo = forwardTo;
return this;
}
/**
* Get the userMetadata property: Metadata associated with the subscription. Maximum number of characters is 1024.
*
* @return the userMetadata value.
*/
public String getUserMetadata() {
return this.userMetadata;
}
/**
* Set the userMetadata property: Metadata associated with the subscription. Maximum number of characters is 1024.
*
* @param userMetadata the userMetadata value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setUserMetadata(String userMetadata) {
this.userMetadata = userMetadata;
return this;
}
/**
* Get the forwardDeadLetteredMessagesTo property: The name of the recipient entity to which all the messages sent
* to the subscription are forwarded to.
*
* @return the forwardDeadLetteredMessagesTo value.
*/
public String getForwardDeadLetteredMessagesTo() {
return this.forwardDeadLetteredMessagesTo;
}
/**
* Set the forwardDeadLetteredMessagesTo property: The name of the recipient entity to which all the messages sent
* to the subscription are forwarded to.
*
* @param forwardDeadLetteredMessagesTo the forwardDeadLetteredMessagesTo value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setForwardDeadLetteredMessagesTo(String forwardDeadLetteredMessagesTo) {
this.forwardDeadLetteredMessagesTo = forwardDeadLetteredMessagesTo;
return this;
}
/**
* Get the autoDeleteOnIdle property: ISO 8601 timeSpan idle interval after which the subscription is automatically
* deleted. The minimum duration is 5 minutes.
*
* @return the autoDeleteOnIdle value.
*/
public Duration getAutoDeleteOnIdle() {
return this.autoDeleteOnIdle;
}
/**
* Set the autoDeleteOnIdle property: ISO 8601 timeSpan idle interval after which the subscription is automatically
* deleted. The minimum duration is 5 minutes.
*
* @param autoDeleteOnIdle the autoDeleteOnIdle value to set.
*
* @return the CreateSubscriptionOptions object itself.
*/
public CreateSubscriptionOptions setAutoDeleteOnIdle(Duration autoDeleteOnIdle) {
this.autoDeleteOnIdle = autoDeleteOnIdle;
return this;
}
} |
Do we need to collect this into a list if we're doing anything on the output? | private void renewOwnership(Map<String, PartitionOwnership> partitionOwnershipMap) {
checkpointStore.claimOwnership(partitionPumpManager.getPartitionPumps().keySet()
.stream()
.filter(
partitionId -> partitionOwnershipMap.containsKey(partitionId) && partitionOwnershipMap.get(partitionId)
.equals(this.ownerId))
.map(partitionId -> createPartitionOwnershipRequest(partitionOwnershipMap, partitionId))
.collect(Collectors.toList()))
.subscribe(ignored -> {
},
ex -> {
logger.error("Error renewing partition ownership", ex);
isLoadBalancerRunning.set(false);
},
() -> isLoadBalancerRunning.set(false));
} | .collect(Collectors.toList())) | private void renewOwnership(Map<String, PartitionOwnership> partitionOwnershipMap) {
checkpointStore.claimOwnership(partitionPumpManager.getPartitionPumps().keySet()
.stream()
.filter(
partitionId -> partitionOwnershipMap.containsKey(partitionId) && partitionOwnershipMap.get(partitionId)
.getOwnerId().equals(this.ownerId))
.map(partitionId -> createPartitionOwnershipRequest(partitionOwnershipMap, partitionId))
.collect(Collectors.toList()))
.subscribe(ignored -> { },
ex -> {
logger.error("Error renewing partition ownership", ex);
isLoadBalancerRunning.set(false);
},
() -> isLoadBalancerRunning.set(false));
} | class PartitionBasedLoadBalancer {
private static final Random RANDOM = new Random();
private final ClientLogger logger = new ClientLogger(PartitionBasedLoadBalancer.class);
private final String eventHubName;
private final String consumerGroupName;
private final CheckpointStore checkpointStore;
private final EventHubAsyncClient eventHubAsyncClient;
private final String ownerId;
private final long inactiveTimeLimitInSeconds;
private final PartitionPumpManager partitionPumpManager;
private final String fullyQualifiedNamespace;
private final Consumer<ErrorContext> processError;
private final PartitionContext partitionAgnosticContext;
private final AtomicBoolean isLoadBalancerRunning = new AtomicBoolean();
/**
* Creates an instance of PartitionBasedLoadBalancer for the given Event Hub name and consumer group.
*
* @param checkpointStore The partition manager that this load balancer will use to read/update ownership details.
* @param eventHubAsyncClient The asynchronous Event Hub client used to consume events.
* @param eventHubName The Event Hub name the {@link EventProcessorClient} is associated with.
* @param consumerGroupName The consumer group name the {@link EventProcessorClient} is associated with.
* @param ownerId The identifier of the {@link EventProcessorClient} that owns this load balancer.
* @param inactiveTimeLimitInSeconds The time in seconds to wait for an update on an ownership record before
* assuming the owner of the partition is inactive.
* @param partitionPumpManager The partition pump manager that keeps track of all EventHubConsumers and partitions
* that this {@link EventProcessorClient} is processing.
* @param processError The callback that will be called when an error occurs while running the load balancer.
*/
PartitionBasedLoadBalancer(final CheckpointStore checkpointStore,
final EventHubAsyncClient eventHubAsyncClient, final String fullyQualifiedNamespace,
final String eventHubName, final String consumerGroupName, final String ownerId,
final long inactiveTimeLimitInSeconds, final PartitionPumpManager partitionPumpManager,
final Consumer<ErrorContext> processError) {
this.checkpointStore = checkpointStore;
this.eventHubAsyncClient = eventHubAsyncClient;
this.fullyQualifiedNamespace = fullyQualifiedNamespace;
this.eventHubName = eventHubName;
this.consumerGroupName = consumerGroupName;
this.ownerId = ownerId;
this.inactiveTimeLimitInSeconds = inactiveTimeLimitInSeconds;
this.partitionPumpManager = partitionPumpManager;
this.processError = processError;
this.partitionAgnosticContext = new PartitionContext(fullyQualifiedNamespace, eventHubName,
consumerGroupName, "NONE");
}
/**
* This is the main method responsible for load balancing. This method is expected to be invoked by the {@link
* EventProcessorClient} periodically. Every call to this method will result in this {@link EventProcessorClient}
* owning <b>at most one</b> new partition.
* <p>
* The load is considered balanced when no active EventProcessor owns 2 partitions more than any other active
* EventProcessor. Given that each invocation to this method results in ownership claim of at most one partition,
* this algorithm converges gradually towards a steady state.
* </p>
* When a new partition is claimed, this method is also responsible for starting a partition pump that creates an
* {@link EventHubConsumerAsyncClient} for processing events from that partition.
*/
void loadBalance() {
if (!isLoadBalancerRunning.compareAndSet(false, true)) {
logger.info("Load balancer already running");
return;
}
logger.info("Starting load balancer for {}", this.ownerId);
/*
* Retrieve current partition ownership details from the datastore.
*/
final Mono<Map<String, PartitionOwnership>> partitionOwnershipMono = checkpointStore
.listOwnership(fullyQualifiedNamespace, eventHubName, consumerGroupName)
.timeout(Duration.ofMinutes(1))
.collectMap(PartitionOwnership::getPartitionId, Function.identity());
/*
* Retrieve the list of partition ids from the Event Hub.
*/
final Mono<List<String>> partitionsMono = eventHubAsyncClient
.getPartitionIds()
.timeout(Duration.ofMinutes(1))
.collectList();
Mono.zip(partitionOwnershipMono, partitionsMono)
.flatMap(this::loadBalance)
.subscribe(ignored -> { },
ex -> {
logger.warning(Messages.LOAD_BALANCING_FAILED, ex.getMessage(), ex);
ErrorContext errorContext = new ErrorContext(partitionAgnosticContext, ex);
processError.accept(errorContext);
isLoadBalancerRunning.set(false);
}, () -> logger.info("Load balancing completed successfully"));
}
/*
* This method works with the given partition ownership details and Event Hub partitions to evaluate whether the
* current Event Processor should take on the responsibility of processing more partitions.
*/
private Mono<Void> loadBalance(final Tuple2<Map<String, PartitionOwnership>, List<String>> tuple) {
return Mono.fromRunnable(() -> {
Map<String, PartitionOwnership> partitionOwnershipMap = tuple.getT1();
List<String> partitionIds = tuple.getT2();
if (CoreUtils.isNullOrEmpty(partitionIds)) {
throw logger.logExceptionAsError(Exceptions.propagate(
new IllegalStateException("There are no partitions in Event Hub " + eventHubName)));
}
int numberOfPartitions = partitionIds.size();
logger.info("CheckpointStore returned {} ownership records", partitionOwnershipMap.size());
logger.info("Event Hubs service returned {} partitions", numberOfPartitions);
if (!isValid(partitionOwnershipMap)) {
throw logger.logExceptionAsError(Exceptions.propagate(
new IllegalStateException("Invalid partitionOwnership data from CheckpointStore")));
}
/*
* Remove all partitions' ownership that have not been modified for a configuration period of time. This
* means that the previous EventProcessor that owned the partition is probably down and the partition is now
* eligible to be claimed by other EventProcessors.
*/
Map<String, PartitionOwnership> activePartitionOwnershipMap = removeInactivePartitionOwnerships(
partitionOwnershipMap);
logger.info("Number of active ownership records {}", activePartitionOwnershipMap.size());
/*
* Create a map of owner id and a list of partitions it owns
*/
Map<String, List<PartitionOwnership>> ownerPartitionMap = activePartitionOwnershipMap.values()
.stream()
.collect(
Collectors.groupingBy(PartitionOwnership::getOwnerId, mapping(Function.identity(), toList())));
ownerPartitionMap.putIfAbsent(this.ownerId, new ArrayList<>());
logger.verbose("Current partition distribution {}", format(ownerPartitionMap));
if (CoreUtils.isNullOrEmpty(activePartitionOwnershipMap)) {
/*
* If the active partition ownership map is empty, this is the first time an event processor is
* running or all Event Processors are down for this Event Hub, consumer group combination. All
* partitions in this Event Hub are available to claim. Choose a random partition to claim ownership.
*/
claimOwnership(partitionOwnershipMap, ownerPartitionMap,
partitionIds.get(RANDOM.nextInt(numberOfPartitions)));
return;
}
/*
* Find the minimum number of partitions every event processor should own when the load is
* evenly distributed.
*/
int numberOfActiveEventProcessors = ownerPartitionMap.size();
logger.info("Number of active event processors {}", ownerPartitionMap.size());
int minPartitionsPerEventProcessor = numberOfPartitions / numberOfActiveEventProcessors;
/*
* If the number of partitions in Event Hub is not evenly divisible by number of active event processors,
* a few Event Processors may own 1 additional partition than the minimum when the load is balanced.
* Calculate the number of event processors that can own additional partition.
*/
int numberOfEventProcessorsWithAdditionalPartition = numberOfPartitions % numberOfActiveEventProcessors;
logger.info("Expected min partitions per event processor = {}, expected number of event "
+ "processors with additional partition = {}", minPartitionsPerEventProcessor,
numberOfEventProcessorsWithAdditionalPartition);
if (isLoadBalanced(minPartitionsPerEventProcessor, numberOfEventProcessorsWithAdditionalPartition,
ownerPartitionMap)) {
logger.info("Load is balanced with this event processor owning {} partitions",
ownerPartitionMap.get(ownerId).size());
renewOwnership(partitionOwnershipMap);
return;
}
if (!shouldOwnMorePartitions(minPartitionsPerEventProcessor, ownerPartitionMap)) {
logger.info("This event processor owns {} partitions and shouldn't own more",
ownerPartitionMap.get(ownerId).size());
renewOwnership(partitionOwnershipMap);
return;
}
logger.info(
"Load is unbalanced and this event processor owns {} partitions and should own more partitions",
ownerPartitionMap.get(ownerId).size());
/*
* If some partitions are unclaimed, this could be because an event processor is down and
* it's partitions are now available for others to own or because event processors are just
* starting up and gradually claiming partitions to own or new partitions were added to Event Hub.
* Find any partition that is not actively owned and claim it.
*
* OR
*
* Find a partition to steal from another event processor. Pick the event processor that has owns the
* highest number of partitions.
*/
String partitionToClaim = partitionIds.parallelStream()
.filter(partitionId -> !activePartitionOwnershipMap.containsKey(partitionId))
.findAny()
.orElseGet(() -> {
logger.info("No unclaimed partitions, stealing from another event processor");
return findPartitionToSteal(ownerPartitionMap);
});
claimOwnership(partitionOwnershipMap, ownerPartitionMap, partitionToClaim);
});
}
private String format(Map<String, List<PartitionOwnership>> ownerPartitionMap) {
return ownerPartitionMap.entrySet()
.stream()
.map(entry -> {
StringBuilder sb = new StringBuilder();
sb.append(entry.getKey()).append("=[");
sb.append(entry.getValue().stream().map(po -> po.getPartitionId()).collect(Collectors.joining(",")));
sb.append("]");
return sb.toString();
}).collect(Collectors.joining(";"));
}
/*
* Check if partition ownership data is valid before proceeding with load balancing.
*/
private boolean isValid(final Map<String, PartitionOwnership> partitionOwnershipMap) {
return partitionOwnershipMap.values()
.stream()
.noneMatch(partitionOwnership -> {
return partitionOwnership.getEventHubName() == null
|| !partitionOwnership.getEventHubName().equals(this.eventHubName)
|| partitionOwnership.getConsumerGroup() == null
|| !partitionOwnership.getConsumerGroup().equals(this.consumerGroupName)
|| partitionOwnership.getPartitionId() == null
|| partitionOwnership.getLastModifiedTime() == null
|| partitionOwnership.getETag() == null;
});
}
/*
* Find the event processor that owns the maximum number of partitions and steal a random partition
* from it.
*/
private String findPartitionToSteal(final Map<String, List<PartitionOwnership>> ownerPartitionMap) {
Map.Entry<String, List<PartitionOwnership>> ownerWithMaxPartitions = ownerPartitionMap.entrySet()
.stream()
.max(Comparator.comparingInt(entry -> entry.getValue().size()))
.get();
int numberOfPartitions = ownerWithMaxPartitions.getValue().size();
logger.info("Owner id {} owns {} partitions, stealing a partition from it", ownerWithMaxPartitions.getKey(),
numberOfPartitions);
return ownerWithMaxPartitions.getValue().get(RANDOM.nextInt(numberOfPartitions)).getPartitionId();
}
/*
* When the load is balanced, all active event processors own at least {@code minPartitionsPerEventProcessor}
* and only {@code numberOfEventProcessorsWithAdditionalPartition} event processors will own 1 additional
* partition.
*/
private boolean isLoadBalanced(final int minPartitionsPerEventProcessor,
final int numberOfEventProcessorsWithAdditionalPartition,
final Map<String, List<PartitionOwnership>> ownerPartitionMap) {
int count = 0;
for (List<PartitionOwnership> partitionOwnership : ownerPartitionMap.values()) {
int numberOfPartitions = partitionOwnership.size();
if (numberOfPartitions < minPartitionsPerEventProcessor
|| numberOfPartitions > minPartitionsPerEventProcessor + 1) {
return false;
}
if (numberOfPartitions == minPartitionsPerEventProcessor + 1) {
count++;
}
}
return count == numberOfEventProcessorsWithAdditionalPartition;
}
/*
* This method is called after determining that the load is not balanced. This method will evaluate
* if the current event processor should own more partitions. Specifically, this method returns true if the
* current event processor owns less than the minimum number of partitions or if it owns the minimum number
* and no other event processor owns lesser number of partitions than this event processor.
*/
private boolean shouldOwnMorePartitions(final int minPartitionsPerEventProcessor,
final Map<String, List<PartitionOwnership>> ownerPartitionMap) {
int numberOfPartitionsOwned = ownerPartitionMap.get(this.ownerId).size();
int leastPartitionsOwnedByAnyEventProcessor =
ownerPartitionMap.values().stream().min(Comparator.comparingInt(List::size)).get().size();
return numberOfPartitionsOwned < minPartitionsPerEventProcessor
|| numberOfPartitionsOwned == leastPartitionsOwnedByAnyEventProcessor;
}
/*
* This method will create a new map of partition id and PartitionOwnership containing only those partitions
* that are actively owned. All entries in the original map returned by CheckpointStore that haven't been
* modified for a duration of time greater than the allowed inactivity time limit are assumed to be owned by
* dead event processors. These will not be included in the map returned by this method.
*/
private Map<String, PartitionOwnership> removeInactivePartitionOwnerships(
final Map<String, PartitionOwnership> partitionOwnershipMap) {
return partitionOwnershipMap
.entrySet()
.stream()
.filter(entry -> {
return (System.currentTimeMillis() - entry.getValue().getLastModifiedTime() < TimeUnit.SECONDS
.toMillis(inactiveTimeLimitInSeconds))
&& !CoreUtils.isNullOrEmpty(entry.getValue().getOwnerId());
}).collect(Collectors.toMap(Entry::getKey, Entry::getValue));
}
private void claimOwnership(final Map<String, PartitionOwnership> partitionOwnershipMap, Map<String,
List<PartitionOwnership>> ownerPartitionsMap, final String partitionIdToClaim) {
logger.info("Attempting to claim ownership of partition {}", partitionIdToClaim);
PartitionOwnership ownershipRequest = createPartitionOwnershipRequest(partitionOwnershipMap,
partitionIdToClaim);
List<PartitionOwnership> partitionsToClaim = new ArrayList<>();
partitionsToClaim.add(ownershipRequest);
partitionsToClaim.addAll(partitionPumpManager.getPartitionPumps()
.keySet()
.stream()
.filter(
partitionId -> partitionOwnershipMap.containsKey(partitionId) && partitionOwnershipMap.get(partitionId)
.equals(this.ownerId))
.map(partitionId -> createPartitionOwnershipRequest(partitionOwnershipMap, partitionId))
.collect(Collectors.toList()));
checkpointStore
.claimOwnership(partitionsToClaim)
.timeout(Duration.ofMinutes(1))
.doOnNext(partitionOwnership -> logger.info("Successfully claimed ownership of partition {}",
partitionOwnership.getPartitionId()))
.doOnError(ex -> logger
.warning(Messages.FAILED_TO_CLAIM_OWNERSHIP, ownershipRequest.getPartitionId(),
ex.getMessage(), ex))
.collectList()
.zipWhen(ownershipList -> checkpointStore.listCheckpoints(fullyQualifiedNamespace, eventHubName,
consumerGroupName)
.collectMap(checkpoint -> checkpoint.getPartitionId(), Function.identity()))
.subscribe(ownedPartitionCheckpointsTuple -> {
ownedPartitionCheckpointsTuple.getT1()
.stream()
.forEach(po -> partitionPumpManager.startPartitionPump(po,
ownedPartitionCheckpointsTuple.getT2().get(po.getPartitionId())));
},
ex -> {
logger.warning("Error while listing checkpoints", ex);
ErrorContext errorContext = new ErrorContext(partitionAgnosticContext, ex);
processError.accept(errorContext);
isLoadBalancerRunning.set(false);
throw logger.logExceptionAsError(new IllegalStateException("Error while listing checkpoints", ex));
},
() -> isLoadBalancerRunning.set(false));
}
private PartitionOwnership createPartitionOwnershipRequest(
final Map<String, PartitionOwnership> partitionOwnershipMap,
final String partitionIdToClaim) {
PartitionOwnership previousPartitionOwnership = partitionOwnershipMap.get(partitionIdToClaim);
PartitionOwnership partitionOwnershipRequest = new PartitionOwnership()
.setFullyQualifiedNamespace(this.fullyQualifiedNamespace)
.setOwnerId(this.ownerId)
.setPartitionId(partitionIdToClaim)
.setConsumerGroup(this.consumerGroupName)
.setEventHubName(this.eventHubName)
.setETag(previousPartitionOwnership == null ? null : previousPartitionOwnership.getETag());
return partitionOwnershipRequest;
}
} | class PartitionBasedLoadBalancer {
private static final Random RANDOM = new Random();
private final ClientLogger logger = new ClientLogger(PartitionBasedLoadBalancer.class);
private final String eventHubName;
private final String consumerGroupName;
private final CheckpointStore checkpointStore;
private final EventHubAsyncClient eventHubAsyncClient;
private final String ownerId;
private final long inactiveTimeLimitInSeconds;
private final PartitionPumpManager partitionPumpManager;
private final String fullyQualifiedNamespace;
private final Consumer<ErrorContext> processError;
private final PartitionContext partitionAgnosticContext;
private final AtomicBoolean isLoadBalancerRunning = new AtomicBoolean();
/**
* Creates an instance of PartitionBasedLoadBalancer for the given Event Hub name and consumer group.
*
* @param checkpointStore The partition manager that this load balancer will use to read/update ownership details.
* @param eventHubAsyncClient The asynchronous Event Hub client used to consume events.
* @param eventHubName The Event Hub name the {@link EventProcessorClient} is associated with.
* @param consumerGroupName The consumer group name the {@link EventProcessorClient} is associated with.
* @param ownerId The identifier of the {@link EventProcessorClient} that owns this load balancer.
* @param inactiveTimeLimitInSeconds The time in seconds to wait for an update on an ownership record before
* assuming the owner of the partition is inactive.
* @param partitionPumpManager The partition pump manager that keeps track of all EventHubConsumers and partitions
* that this {@link EventProcessorClient} is processing.
* @param processError The callback that will be called when an error occurs while running the load balancer.
*/
PartitionBasedLoadBalancer(final CheckpointStore checkpointStore,
final EventHubAsyncClient eventHubAsyncClient, final String fullyQualifiedNamespace,
final String eventHubName, final String consumerGroupName, final String ownerId,
final long inactiveTimeLimitInSeconds, final PartitionPumpManager partitionPumpManager,
final Consumer<ErrorContext> processError) {
this.checkpointStore = checkpointStore;
this.eventHubAsyncClient = eventHubAsyncClient;
this.fullyQualifiedNamespace = fullyQualifiedNamespace;
this.eventHubName = eventHubName;
this.consumerGroupName = consumerGroupName;
this.ownerId = ownerId;
this.inactiveTimeLimitInSeconds = inactiveTimeLimitInSeconds;
this.partitionPumpManager = partitionPumpManager;
this.processError = processError;
this.partitionAgnosticContext = new PartitionContext(fullyQualifiedNamespace, eventHubName,
consumerGroupName, "NONE");
}
/**
* This is the main method responsible for load balancing. This method is expected to be invoked by the {@link
* EventProcessorClient} periodically. Every call to this method will result in this {@link EventProcessorClient}
* owning <b>at most one</b> new partition.
* <p>
* The load is considered balanced when no active EventProcessor owns 2 partitions more than any other active
* EventProcessor. Given that each invocation to this method results in ownership claim of at most one partition,
* this algorithm converges gradually towards a steady state.
* </p>
* When a new partition is claimed, this method is also responsible for starting a partition pump that creates an
* {@link EventHubConsumerAsyncClient} for processing events from that partition.
*/
void loadBalance() {
if (!isLoadBalancerRunning.compareAndSet(false, true)) {
logger.info("Load balancer already running");
return;
}
logger.info("Starting load balancer for {}", this.ownerId);
/*
* Retrieve current partition ownership details from the datastore.
*/
final Mono<Map<String, PartitionOwnership>> partitionOwnershipMono = checkpointStore
.listOwnership(fullyQualifiedNamespace, eventHubName, consumerGroupName)
.timeout(Duration.ofMinutes(1))
.collectMap(PartitionOwnership::getPartitionId, Function.identity());
/*
* Retrieve the list of partition ids from the Event Hub.
*/
final Mono<List<String>> partitionsMono = eventHubAsyncClient
.getPartitionIds()
.timeout(Duration.ofMinutes(1))
.collectList();
Mono.zip(partitionOwnershipMono, partitionsMono)
.flatMap(this::loadBalance)
.subscribe(ignored -> { },
ex -> {
logger.warning(Messages.LOAD_BALANCING_FAILED, ex.getMessage(), ex);
ErrorContext errorContext = new ErrorContext(partitionAgnosticContext, ex);
processError.accept(errorContext);
isLoadBalancerRunning.set(false);
}, () -> logger.info("Load balancing completed successfully"));
}
/*
* This method works with the given partition ownership details and Event Hub partitions to evaluate whether the
* current Event Processor should take on the responsibility of processing more partitions.
*/
private Mono<Void> loadBalance(final Tuple2<Map<String, PartitionOwnership>, List<String>> tuple) {
return Mono.fromRunnable(() -> {
Map<String, PartitionOwnership> partitionOwnershipMap = tuple.getT1();
List<String> partitionIds = tuple.getT2();
if (CoreUtils.isNullOrEmpty(partitionIds)) {
throw logger.logExceptionAsError(Exceptions.propagate(
new IllegalStateException("There are no partitions in Event Hub " + eventHubName)));
}
int numberOfPartitions = partitionIds.size();
logger.info("CheckpointStore returned {} ownership records", partitionOwnershipMap.size());
logger.info("Event Hubs service returned {} partitions", numberOfPartitions);
if (!isValid(partitionOwnershipMap)) {
throw logger.logExceptionAsError(Exceptions.propagate(
new IllegalStateException("Invalid partitionOwnership data from CheckpointStore")));
}
/*
* Remove all partitions' ownership that have not been modified for a configuration period of time. This
* means that the previous EventProcessor that owned the partition is probably down and the partition is now
* eligible to be claimed by other EventProcessors.
*/
Map<String, PartitionOwnership> activePartitionOwnershipMap = removeInactivePartitionOwnerships(
partitionOwnershipMap);
logger.info("Number of active ownership records {}", activePartitionOwnershipMap.size());
/*
* Create a map of owner id and a list of partitions it owns
*/
Map<String, List<PartitionOwnership>> ownerPartitionMap = activePartitionOwnershipMap.values()
.stream()
.collect(
Collectors.groupingBy(PartitionOwnership::getOwnerId, mapping(Function.identity(), toList())));
ownerPartitionMap.putIfAbsent(this.ownerId, new ArrayList<>());
logger.verbose("Current partition distribution {}", format(ownerPartitionMap));
if (CoreUtils.isNullOrEmpty(activePartitionOwnershipMap)) {
/*
* If the active partition ownership map is empty, this is the first time an event processor is
* running or all Event Processors are down for this Event Hub, consumer group combination. All
* partitions in this Event Hub are available to claim. Choose a random partition to claim ownership.
*/
claimOwnership(partitionOwnershipMap, ownerPartitionMap,
partitionIds.get(RANDOM.nextInt(numberOfPartitions)));
return;
}
/*
* Find the minimum number of partitions every event processor should own when the load is
* evenly distributed.
*/
int numberOfActiveEventProcessors = ownerPartitionMap.size();
logger.info("Number of active event processors {}", ownerPartitionMap.size());
int minPartitionsPerEventProcessor = numberOfPartitions / numberOfActiveEventProcessors;
/*
* If the number of partitions in Event Hub is not evenly divisible by number of active event processors,
* a few Event Processors may own 1 additional partition than the minimum when the load is balanced.
* Calculate the number of event processors that can own additional partition.
*/
int numberOfEventProcessorsWithAdditionalPartition = numberOfPartitions % numberOfActiveEventProcessors;
logger.info("Expected min partitions per event processor = {}, expected number of event "
+ "processors with additional partition = {}", minPartitionsPerEventProcessor,
numberOfEventProcessorsWithAdditionalPartition);
if (isLoadBalanced(minPartitionsPerEventProcessor, numberOfEventProcessorsWithAdditionalPartition,
ownerPartitionMap)) {
logger.info("Load is balanced with this event processor owning {} partitions",
ownerPartitionMap.get(ownerId).size());
renewOwnership(partitionOwnershipMap);
return;
}
if (!shouldOwnMorePartitions(minPartitionsPerEventProcessor, ownerPartitionMap)) {
logger.info("This event processor owns {} partitions and shouldn't own more",
ownerPartitionMap.get(ownerId).size());
renewOwnership(partitionOwnershipMap);
return;
}
logger.info(
"Load is unbalanced and this event processor owns {} partitions and should own more partitions",
ownerPartitionMap.get(ownerId).size());
/*
* If some partitions are unclaimed, this could be because an event processor is down and
* it's partitions are now available for others to own or because event processors are just
* starting up and gradually claiming partitions to own or new partitions were added to Event Hub.
* Find any partition that is not actively owned and claim it.
*
* OR
*
* Find a partition to steal from another event processor. Pick the event processor that has owns the
* highest number of partitions.
*/
String partitionToClaim = partitionIds.parallelStream()
.filter(partitionId -> !activePartitionOwnershipMap.containsKey(partitionId))
.findAny()
.orElseGet(() -> {
logger.info("No unclaimed partitions, stealing from another event processor");
return findPartitionToSteal(ownerPartitionMap);
});
claimOwnership(partitionOwnershipMap, ownerPartitionMap, partitionToClaim);
});
}
private String format(Map<String, List<PartitionOwnership>> ownerPartitionMap) {
return ownerPartitionMap.entrySet()
.stream()
.map(entry -> {
StringBuilder sb = new StringBuilder();
sb.append(entry.getKey()).append("=[");
sb.append(entry.getValue().stream().map(po -> po.getPartitionId()).collect(Collectors.joining(",")));
sb.append("]");
return sb.toString();
}).collect(Collectors.joining(";"));
}
/*
* Check if partition ownership data is valid before proceeding with load balancing.
*/
private boolean isValid(final Map<String, PartitionOwnership> partitionOwnershipMap) {
return partitionOwnershipMap.values()
.stream()
.noneMatch(partitionOwnership -> {
return partitionOwnership.getEventHubName() == null
|| !partitionOwnership.getEventHubName().equals(this.eventHubName)
|| partitionOwnership.getConsumerGroup() == null
|| !partitionOwnership.getConsumerGroup().equals(this.consumerGroupName)
|| partitionOwnership.getPartitionId() == null
|| partitionOwnership.getLastModifiedTime() == null
|| partitionOwnership.getETag() == null;
});
}
/*
* Find the event processor that owns the maximum number of partitions and steal a random partition
* from it.
*/
private String findPartitionToSteal(final Map<String, List<PartitionOwnership>> ownerPartitionMap) {
Map.Entry<String, List<PartitionOwnership>> ownerWithMaxPartitions = ownerPartitionMap.entrySet()
.stream()
.max(Comparator.comparingInt(entry -> entry.getValue().size()))
.get();
int numberOfPartitions = ownerWithMaxPartitions.getValue().size();
logger.info("Owner id {} owns {} partitions, stealing a partition from it", ownerWithMaxPartitions.getKey(),
numberOfPartitions);
return ownerWithMaxPartitions.getValue().get(RANDOM.nextInt(numberOfPartitions)).getPartitionId();
}
/*
* When the load is balanced, all active event processors own at least {@code minPartitionsPerEventProcessor}
* and only {@code numberOfEventProcessorsWithAdditionalPartition} event processors will own 1 additional
* partition.
*/
private boolean isLoadBalanced(final int minPartitionsPerEventProcessor,
final int numberOfEventProcessorsWithAdditionalPartition,
final Map<String, List<PartitionOwnership>> ownerPartitionMap) {
int count = 0;
for (List<PartitionOwnership> partitionOwnership : ownerPartitionMap.values()) {
int numberOfPartitions = partitionOwnership.size();
if (numberOfPartitions < minPartitionsPerEventProcessor
|| numberOfPartitions > minPartitionsPerEventProcessor + 1) {
return false;
}
if (numberOfPartitions == minPartitionsPerEventProcessor + 1) {
count++;
}
}
return count == numberOfEventProcessorsWithAdditionalPartition;
}
/*
* This method is called after determining that the load is not balanced. This method will evaluate
* if the current event processor should own more partitions. Specifically, this method returns true if the
* current event processor owns less than the minimum number of partitions or if it owns the minimum number
* and no other event processor owns lesser number of partitions than this event processor.
*/
private boolean shouldOwnMorePartitions(final int minPartitionsPerEventProcessor,
final Map<String, List<PartitionOwnership>> ownerPartitionMap) {
int numberOfPartitionsOwned = ownerPartitionMap.get(this.ownerId).size();
int leastPartitionsOwnedByAnyEventProcessor =
ownerPartitionMap.values().stream().min(Comparator.comparingInt(List::size)).get().size();
return numberOfPartitionsOwned < minPartitionsPerEventProcessor
|| numberOfPartitionsOwned == leastPartitionsOwnedByAnyEventProcessor;
}
/*
* This method will create a new map of partition id and PartitionOwnership containing only those partitions
* that are actively owned. All entries in the original map returned by CheckpointStore that haven't been
* modified for a duration of time greater than the allowed inactivity time limit are assumed to be owned by
* dead event processors. These will not be included in the map returned by this method.
*/
private Map<String, PartitionOwnership> removeInactivePartitionOwnerships(
final Map<String, PartitionOwnership> partitionOwnershipMap) {
return partitionOwnershipMap
.entrySet()
.stream()
.filter(entry -> {
return (System.currentTimeMillis() - entry.getValue().getLastModifiedTime() < TimeUnit.SECONDS
.toMillis(inactiveTimeLimitInSeconds))
&& !CoreUtils.isNullOrEmpty(entry.getValue().getOwnerId());
}).collect(Collectors.toMap(Entry::getKey, Entry::getValue));
}
private void claimOwnership(final Map<String, PartitionOwnership> partitionOwnershipMap, Map<String,
List<PartitionOwnership>> ownerPartitionsMap, final String partitionIdToClaim) {
logger.info("Attempting to claim ownership of partition {}", partitionIdToClaim);
PartitionOwnership ownershipRequest = createPartitionOwnershipRequest(partitionOwnershipMap,
partitionIdToClaim);
List<PartitionOwnership> partitionsToClaim = new ArrayList<>();
partitionsToClaim.add(ownershipRequest);
partitionsToClaim.addAll(partitionPumpManager.getPartitionPumps()
.keySet()
.stream()
.filter(
partitionId -> partitionOwnershipMap.containsKey(partitionId) && partitionOwnershipMap.get(partitionId)
.getOwnerId().equals(this.ownerId))
.map(partitionId -> createPartitionOwnershipRequest(partitionOwnershipMap, partitionId))
.collect(Collectors.toList()));
checkpointStore
.claimOwnership(partitionsToClaim)
.timeout(Duration.ofMinutes(1))
.doOnNext(partitionOwnership -> logger.info("Successfully claimed ownership of partition {}",
partitionOwnership.getPartitionId()))
.doOnError(ex -> logger
.warning(Messages.FAILED_TO_CLAIM_OWNERSHIP, ownershipRequest.getPartitionId(),
ex.getMessage(), ex))
.collectList()
.zipWhen(ownershipList -> checkpointStore.listCheckpoints(fullyQualifiedNamespace, eventHubName,
consumerGroupName)
.collectMap(checkpoint -> checkpoint.getPartitionId(), Function.identity()))
.subscribe(ownedPartitionCheckpointsTuple -> {
ownedPartitionCheckpointsTuple.getT1()
.stream()
.forEach(po -> partitionPumpManager.startPartitionPump(po,
ownedPartitionCheckpointsTuple.getT2().get(po.getPartitionId())));
},
ex -> {
logger.warning("Error while listing checkpoints", ex);
ErrorContext errorContext = new ErrorContext(partitionAgnosticContext, ex);
processError.accept(errorContext);
isLoadBalancerRunning.set(false);
throw logger.logExceptionAsError(new IllegalStateException("Error while listing checkpoints", ex));
},
() -> isLoadBalancerRunning.set(false));
}
private PartitionOwnership createPartitionOwnershipRequest(
final Map<String, PartitionOwnership> partitionOwnershipMap,
final String partitionIdToClaim) {
PartitionOwnership previousPartitionOwnership = partitionOwnershipMap.get(partitionIdToClaim);
PartitionOwnership partitionOwnershipRequest = new PartitionOwnership()
.setFullyQualifiedNamespace(this.fullyQualifiedNamespace)
.setOwnerId(this.ownerId)
.setPartitionId(partitionIdToClaim)
.setConsumerGroup(this.consumerGroupName)
.setEventHubName(this.eventHubName)
.setETag(previousPartitionOwnership == null ? null : previousPartitionOwnership.getETag());
return partitionOwnershipRequest;
}
} |
Is it possible to have a test for this? 🤔 | private Mono<Void> loadBalance(final Tuple2<Map<String, PartitionOwnership>, List<String>> tuple) {
return Mono.fromRunnable(() -> {
Map<String, PartitionOwnership> partitionOwnershipMap = tuple.getT1();
List<String> partitionIds = tuple.getT2();
if (CoreUtils.isNullOrEmpty(partitionIds)) {
throw logger.logExceptionAsError(Exceptions.propagate(
new IllegalStateException("There are no partitions in Event Hub " + eventHubName)));
}
int numberOfPartitions = partitionIds.size();
logger.info("CheckpointStore returned {} ownership records", partitionOwnershipMap.size());
logger.info("Event Hubs service returned {} partitions", numberOfPartitions);
if (!isValid(partitionOwnershipMap)) {
throw logger.logExceptionAsError(Exceptions.propagate(
new IllegalStateException("Invalid partitionOwnership data from CheckpointStore")));
}
/*
* Remove all partitions' ownership that have not been modified for a configuration period of time. This
* means that the previous EventProcessor that owned the partition is probably down and the partition is now
* eligible to be claimed by other EventProcessors.
*/
Map<String, PartitionOwnership> activePartitionOwnershipMap = removeInactivePartitionOwnerships(
partitionOwnershipMap);
logger.info("Number of active ownership records {}", activePartitionOwnershipMap.size());
/*
* Create a map of owner id and a list of partitions it owns
*/
Map<String, List<PartitionOwnership>> ownerPartitionMap = activePartitionOwnershipMap.values()
.stream()
.collect(
Collectors.groupingBy(PartitionOwnership::getOwnerId, mapping(Function.identity(), toList())));
ownerPartitionMap.putIfAbsent(this.ownerId, new ArrayList<>());
logger.verbose("Current partition distribution {}", format(ownerPartitionMap));
if (CoreUtils.isNullOrEmpty(activePartitionOwnershipMap)) {
/*
* If the active partition ownership map is empty, this is the first time an event processor is
* running or all Event Processors are down for this Event Hub, consumer group combination. All
* partitions in this Event Hub are available to claim. Choose a random partition to claim ownership.
*/
claimOwnership(partitionOwnershipMap, ownerPartitionMap,
partitionIds.get(RANDOM.nextInt(numberOfPartitions)));
return;
}
/*
* Find the minimum number of partitions every event processor should own when the load is
* evenly distributed.
*/
int numberOfActiveEventProcessors = ownerPartitionMap.size();
logger.info("Number of active event processors {}", ownerPartitionMap.size());
int minPartitionsPerEventProcessor = numberOfPartitions / numberOfActiveEventProcessors;
/*
* If the number of partitions in Event Hub is not evenly divisible by number of active event processors,
* a few Event Processors may own 1 additional partition than the minimum when the load is balanced.
* Calculate the number of event processors that can own additional partition.
*/
int numberOfEventProcessorsWithAdditionalPartition = numberOfPartitions % numberOfActiveEventProcessors;
logger.info("Expected min partitions per event processor = {}, expected number of event "
+ "processors with additional partition = {}", minPartitionsPerEventProcessor,
numberOfEventProcessorsWithAdditionalPartition);
if (isLoadBalanced(minPartitionsPerEventProcessor, numberOfEventProcessorsWithAdditionalPartition,
ownerPartitionMap)) {
logger.info("Load is balanced with this event processor owning {} partitions",
ownerPartitionMap.get(ownerId).size());
renewOwnership(partitionOwnershipMap);
return;
}
if (!shouldOwnMorePartitions(minPartitionsPerEventProcessor, ownerPartitionMap)) {
logger.info("This event processor owns {} partitions and shouldn't own more",
ownerPartitionMap.get(ownerId).size());
renewOwnership(partitionOwnershipMap);
return;
}
logger.info(
"Load is unbalanced and this event processor owns {} partitions and should own more partitions",
ownerPartitionMap.get(ownerId).size());
/*
* If some partitions are unclaimed, this could be because an event processor is down and
* it's partitions are now available for others to own or because event processors are just
* starting up and gradually claiming partitions to own or new partitions were added to Event Hub.
* Find any partition that is not actively owned and claim it.
*
* OR
*
* Find a partition to steal from another event processor. Pick the event processor that has owns the
* highest number of partitions.
*/
String partitionToClaim = partitionIds.parallelStream()
.filter(partitionId -> !activePartitionOwnershipMap.containsKey(partitionId))
.findAny()
.orElseGet(() -> {
logger.info("No unclaimed partitions, stealing from another event processor");
return findPartitionToSteal(ownerPartitionMap);
});
claimOwnership(partitionOwnershipMap, ownerPartitionMap, partitionToClaim);
});
} | renewOwnership(partitionOwnershipMap); | private Mono<Void> loadBalance(final Tuple2<Map<String, PartitionOwnership>, List<String>> tuple) {
return Mono.fromRunnable(() -> {
Map<String, PartitionOwnership> partitionOwnershipMap = tuple.getT1();
List<String> partitionIds = tuple.getT2();
if (CoreUtils.isNullOrEmpty(partitionIds)) {
throw logger.logExceptionAsError(Exceptions.propagate(
new IllegalStateException("There are no partitions in Event Hub " + eventHubName)));
}
int numberOfPartitions = partitionIds.size();
logger.info("CheckpointStore returned {} ownership records", partitionOwnershipMap.size());
logger.info("Event Hubs service returned {} partitions", numberOfPartitions);
if (!isValid(partitionOwnershipMap)) {
throw logger.logExceptionAsError(Exceptions.propagate(
new IllegalStateException("Invalid partitionOwnership data from CheckpointStore")));
}
/*
* Remove all partitions' ownership that have not been modified for a configuration period of time. This
* means that the previous EventProcessor that owned the partition is probably down and the partition is now
* eligible to be claimed by other EventProcessors.
*/
Map<String, PartitionOwnership> activePartitionOwnershipMap = removeInactivePartitionOwnerships(
partitionOwnershipMap);
logger.info("Number of active ownership records {}", activePartitionOwnershipMap.size());
/*
* Create a map of owner id and a list of partitions it owns
*/
Map<String, List<PartitionOwnership>> ownerPartitionMap = activePartitionOwnershipMap.values()
.stream()
.collect(
Collectors.groupingBy(PartitionOwnership::getOwnerId, mapping(Function.identity(), toList())));
ownerPartitionMap.putIfAbsent(this.ownerId, new ArrayList<>());
logger.verbose("Current partition distribution {}", format(ownerPartitionMap));
if (CoreUtils.isNullOrEmpty(activePartitionOwnershipMap)) {
/*
* If the active partition ownership map is empty, this is the first time an event processor is
* running or all Event Processors are down for this Event Hub, consumer group combination. All
* partitions in this Event Hub are available to claim. Choose a random partition to claim ownership.
*/
claimOwnership(partitionOwnershipMap, ownerPartitionMap,
partitionIds.get(RANDOM.nextInt(numberOfPartitions)));
return;
}
/*
* Find the minimum number of partitions every event processor should own when the load is
* evenly distributed.
*/
int numberOfActiveEventProcessors = ownerPartitionMap.size();
logger.info("Number of active event processors {}", ownerPartitionMap.size());
int minPartitionsPerEventProcessor = numberOfPartitions / numberOfActiveEventProcessors;
/*
* If the number of partitions in Event Hub is not evenly divisible by number of active event processors,
* a few Event Processors may own 1 additional partition than the minimum when the load is balanced.
* Calculate the number of event processors that can own additional partition.
*/
int numberOfEventProcessorsWithAdditionalPartition = numberOfPartitions % numberOfActiveEventProcessors;
logger.info("Expected min partitions per event processor = {}, expected number of event "
+ "processors with additional partition = {}", minPartitionsPerEventProcessor,
numberOfEventProcessorsWithAdditionalPartition);
if (isLoadBalanced(minPartitionsPerEventProcessor, numberOfEventProcessorsWithAdditionalPartition,
ownerPartitionMap)) {
logger.info("Load is balanced with this event processor owning {} partitions",
ownerPartitionMap.get(ownerId).size());
renewOwnership(partitionOwnershipMap);
return;
}
if (!shouldOwnMorePartitions(minPartitionsPerEventProcessor, ownerPartitionMap)) {
logger.info("This event processor owns {} partitions and shouldn't own more",
ownerPartitionMap.get(ownerId).size());
renewOwnership(partitionOwnershipMap);
return;
}
logger.info(
"Load is unbalanced and this event processor owns {} partitions and should own more partitions",
ownerPartitionMap.get(ownerId).size());
/*
* If some partitions are unclaimed, this could be because an event processor is down and
* it's partitions are now available for others to own or because event processors are just
* starting up and gradually claiming partitions to own or new partitions were added to Event Hub.
* Find any partition that is not actively owned and claim it.
*
* OR
*
* Find a partition to steal from another event processor. Pick the event processor that has owns the
* highest number of partitions.
*/
String partitionToClaim = partitionIds.parallelStream()
.filter(partitionId -> !activePartitionOwnershipMap.containsKey(partitionId))
.findAny()
.orElseGet(() -> {
logger.info("No unclaimed partitions, stealing from another event processor");
return findPartitionToSteal(ownerPartitionMap);
});
claimOwnership(partitionOwnershipMap, ownerPartitionMap, partitionToClaim);
});
} | class PartitionBasedLoadBalancer {
private static final Random RANDOM = new Random();
private final ClientLogger logger = new ClientLogger(PartitionBasedLoadBalancer.class);
private final String eventHubName;
private final String consumerGroupName;
private final CheckpointStore checkpointStore;
private final EventHubAsyncClient eventHubAsyncClient;
private final String ownerId;
private final long inactiveTimeLimitInSeconds;
private final PartitionPumpManager partitionPumpManager;
private final String fullyQualifiedNamespace;
private final Consumer<ErrorContext> processError;
private final PartitionContext partitionAgnosticContext;
private final AtomicBoolean isLoadBalancerRunning = new AtomicBoolean();
/**
* Creates an instance of PartitionBasedLoadBalancer for the given Event Hub name and consumer group.
*
* @param checkpointStore The partition manager that this load balancer will use to read/update ownership details.
* @param eventHubAsyncClient The asynchronous Event Hub client used to consume events.
* @param eventHubName The Event Hub name the {@link EventProcessorClient} is associated with.
* @param consumerGroupName The consumer group name the {@link EventProcessorClient} is associated with.
* @param ownerId The identifier of the {@link EventProcessorClient} that owns this load balancer.
* @param inactiveTimeLimitInSeconds The time in seconds to wait for an update on an ownership record before
* assuming the owner of the partition is inactive.
* @param partitionPumpManager The partition pump manager that keeps track of all EventHubConsumers and partitions
* that this {@link EventProcessorClient} is processing.
* @param processError The callback that will be called when an error occurs while running the load balancer.
*/
PartitionBasedLoadBalancer(final CheckpointStore checkpointStore,
final EventHubAsyncClient eventHubAsyncClient, final String fullyQualifiedNamespace,
final String eventHubName, final String consumerGroupName, final String ownerId,
final long inactiveTimeLimitInSeconds, final PartitionPumpManager partitionPumpManager,
final Consumer<ErrorContext> processError) {
this.checkpointStore = checkpointStore;
this.eventHubAsyncClient = eventHubAsyncClient;
this.fullyQualifiedNamespace = fullyQualifiedNamespace;
this.eventHubName = eventHubName;
this.consumerGroupName = consumerGroupName;
this.ownerId = ownerId;
this.inactiveTimeLimitInSeconds = inactiveTimeLimitInSeconds;
this.partitionPumpManager = partitionPumpManager;
this.processError = processError;
this.partitionAgnosticContext = new PartitionContext(fullyQualifiedNamespace, eventHubName,
consumerGroupName, "NONE");
}
/**
* This is the main method responsible for load balancing. This method is expected to be invoked by the {@link
* EventProcessorClient} periodically. Every call to this method will result in this {@link EventProcessorClient}
* owning <b>at most one</b> new partition.
* <p>
* The load is considered balanced when no active EventProcessor owns 2 partitions more than any other active
* EventProcessor. Given that each invocation to this method results in ownership claim of at most one partition,
* this algorithm converges gradually towards a steady state.
* </p>
* When a new partition is claimed, this method is also responsible for starting a partition pump that creates an
* {@link EventHubConsumerAsyncClient} for processing events from that partition.
*/
void loadBalance() {
if (!isLoadBalancerRunning.compareAndSet(false, true)) {
logger.info("Load balancer already running");
return;
}
logger.info("Starting load balancer for {}", this.ownerId);
/*
* Retrieve current partition ownership details from the datastore.
*/
final Mono<Map<String, PartitionOwnership>> partitionOwnershipMono = checkpointStore
.listOwnership(fullyQualifiedNamespace, eventHubName, consumerGroupName)
.timeout(Duration.ofMinutes(1))
.collectMap(PartitionOwnership::getPartitionId, Function.identity());
/*
* Retrieve the list of partition ids from the Event Hub.
*/
final Mono<List<String>> partitionsMono = eventHubAsyncClient
.getPartitionIds()
.timeout(Duration.ofMinutes(1))
.collectList();
Mono.zip(partitionOwnershipMono, partitionsMono)
.flatMap(this::loadBalance)
.subscribe(ignored -> { },
ex -> {
logger.warning(Messages.LOAD_BALANCING_FAILED, ex.getMessage(), ex);
ErrorContext errorContext = new ErrorContext(partitionAgnosticContext, ex);
processError.accept(errorContext);
isLoadBalancerRunning.set(false);
}, () -> logger.info("Load balancing completed successfully"));
}
/*
* This method works with the given partition ownership details and Event Hub partitions to evaluate whether the
* current Event Processor should take on the responsibility of processing more partitions.
*/
private void renewOwnership(Map<String, PartitionOwnership> partitionOwnershipMap) {
checkpointStore.claimOwnership(partitionPumpManager.getPartitionPumps().keySet()
.stream()
.filter(
partitionId -> partitionOwnershipMap.containsKey(partitionId) && partitionOwnershipMap.get(partitionId)
.equals(this.ownerId))
.map(partitionId -> createPartitionOwnershipRequest(partitionOwnershipMap, partitionId))
.collect(Collectors.toList()))
.subscribe(ignored -> {
},
ex -> {
logger.error("Error renewing partition ownership", ex);
isLoadBalancerRunning.set(false);
},
() -> isLoadBalancerRunning.set(false));
}
private String format(Map<String, List<PartitionOwnership>> ownerPartitionMap) {
return ownerPartitionMap.entrySet()
.stream()
.map(entry -> {
StringBuilder sb = new StringBuilder();
sb.append(entry.getKey()).append("=[");
sb.append(entry.getValue().stream().map(po -> po.getPartitionId()).collect(Collectors.joining(",")));
sb.append("]");
return sb.toString();
}).collect(Collectors.joining(";"));
}
/*
* Check if partition ownership data is valid before proceeding with load balancing.
*/
private boolean isValid(final Map<String, PartitionOwnership> partitionOwnershipMap) {
return partitionOwnershipMap.values()
.stream()
.noneMatch(partitionOwnership -> {
return partitionOwnership.getEventHubName() == null
|| !partitionOwnership.getEventHubName().equals(this.eventHubName)
|| partitionOwnership.getConsumerGroup() == null
|| !partitionOwnership.getConsumerGroup().equals(this.consumerGroupName)
|| partitionOwnership.getPartitionId() == null
|| partitionOwnership.getLastModifiedTime() == null
|| partitionOwnership.getETag() == null;
});
}
/*
* Find the event processor that owns the maximum number of partitions and steal a random partition
* from it.
*/
private String findPartitionToSteal(final Map<String, List<PartitionOwnership>> ownerPartitionMap) {
Map.Entry<String, List<PartitionOwnership>> ownerWithMaxPartitions = ownerPartitionMap.entrySet()
.stream()
.max(Comparator.comparingInt(entry -> entry.getValue().size()))
.get();
int numberOfPartitions = ownerWithMaxPartitions.getValue().size();
logger.info("Owner id {} owns {} partitions, stealing a partition from it", ownerWithMaxPartitions.getKey(),
numberOfPartitions);
return ownerWithMaxPartitions.getValue().get(RANDOM.nextInt(numberOfPartitions)).getPartitionId();
}
/*
* When the load is balanced, all active event processors own at least {@code minPartitionsPerEventProcessor}
* and only {@code numberOfEventProcessorsWithAdditionalPartition} event processors will own 1 additional
* partition.
*/
private boolean isLoadBalanced(final int minPartitionsPerEventProcessor,
final int numberOfEventProcessorsWithAdditionalPartition,
final Map<String, List<PartitionOwnership>> ownerPartitionMap) {
int count = 0;
for (List<PartitionOwnership> partitionOwnership : ownerPartitionMap.values()) {
int numberOfPartitions = partitionOwnership.size();
if (numberOfPartitions < minPartitionsPerEventProcessor
|| numberOfPartitions > minPartitionsPerEventProcessor + 1) {
return false;
}
if (numberOfPartitions == minPartitionsPerEventProcessor + 1) {
count++;
}
}
return count == numberOfEventProcessorsWithAdditionalPartition;
}
/*
* This method is called after determining that the load is not balanced. This method will evaluate
* if the current event processor should own more partitions. Specifically, this method returns true if the
* current event processor owns less than the minimum number of partitions or if it owns the minimum number
* and no other event processor owns lesser number of partitions than this event processor.
*/
private boolean shouldOwnMorePartitions(final int minPartitionsPerEventProcessor,
final Map<String, List<PartitionOwnership>> ownerPartitionMap) {
int numberOfPartitionsOwned = ownerPartitionMap.get(this.ownerId).size();
int leastPartitionsOwnedByAnyEventProcessor =
ownerPartitionMap.values().stream().min(Comparator.comparingInt(List::size)).get().size();
return numberOfPartitionsOwned < minPartitionsPerEventProcessor
|| numberOfPartitionsOwned == leastPartitionsOwnedByAnyEventProcessor;
}
/*
* This method will create a new map of partition id and PartitionOwnership containing only those partitions
* that are actively owned. All entries in the original map returned by CheckpointStore that haven't been
* modified for a duration of time greater than the allowed inactivity time limit are assumed to be owned by
* dead event processors. These will not be included in the map returned by this method.
*/
private Map<String, PartitionOwnership> removeInactivePartitionOwnerships(
final Map<String, PartitionOwnership> partitionOwnershipMap) {
return partitionOwnershipMap
.entrySet()
.stream()
.filter(entry -> {
return (System.currentTimeMillis() - entry.getValue().getLastModifiedTime() < TimeUnit.SECONDS
.toMillis(inactiveTimeLimitInSeconds))
&& !CoreUtils.isNullOrEmpty(entry.getValue().getOwnerId());
}).collect(Collectors.toMap(Entry::getKey, Entry::getValue));
}
private void claimOwnership(final Map<String, PartitionOwnership> partitionOwnershipMap, Map<String,
List<PartitionOwnership>> ownerPartitionsMap, final String partitionIdToClaim) {
logger.info("Attempting to claim ownership of partition {}", partitionIdToClaim);
PartitionOwnership ownershipRequest = createPartitionOwnershipRequest(partitionOwnershipMap,
partitionIdToClaim);
List<PartitionOwnership> partitionsToClaim = new ArrayList<>();
partitionsToClaim.add(ownershipRequest);
partitionsToClaim.addAll(partitionPumpManager.getPartitionPumps()
.keySet()
.stream()
.filter(
partitionId -> partitionOwnershipMap.containsKey(partitionId) && partitionOwnershipMap.get(partitionId)
.equals(this.ownerId))
.map(partitionId -> createPartitionOwnershipRequest(partitionOwnershipMap, partitionId))
.collect(Collectors.toList()));
checkpointStore
.claimOwnership(partitionsToClaim)
.timeout(Duration.ofMinutes(1))
.doOnNext(partitionOwnership -> logger.info("Successfully claimed ownership of partition {}",
partitionOwnership.getPartitionId()))
.doOnError(ex -> logger
.warning(Messages.FAILED_TO_CLAIM_OWNERSHIP, ownershipRequest.getPartitionId(),
ex.getMessage(), ex))
.collectList()
.zipWhen(ownershipList -> checkpointStore.listCheckpoints(fullyQualifiedNamespace, eventHubName,
consumerGroupName)
.collectMap(checkpoint -> checkpoint.getPartitionId(), Function.identity()))
.subscribe(ownedPartitionCheckpointsTuple -> {
ownedPartitionCheckpointsTuple.getT1()
.stream()
.forEach(po -> partitionPumpManager.startPartitionPump(po,
ownedPartitionCheckpointsTuple.getT2().get(po.getPartitionId())));
},
ex -> {
logger.warning("Error while listing checkpoints", ex);
ErrorContext errorContext = new ErrorContext(partitionAgnosticContext, ex);
processError.accept(errorContext);
isLoadBalancerRunning.set(false);
throw logger.logExceptionAsError(new IllegalStateException("Error while listing checkpoints", ex));
},
() -> isLoadBalancerRunning.set(false));
}
private PartitionOwnership createPartitionOwnershipRequest(
final Map<String, PartitionOwnership> partitionOwnershipMap,
final String partitionIdToClaim) {
PartitionOwnership previousPartitionOwnership = partitionOwnershipMap.get(partitionIdToClaim);
PartitionOwnership partitionOwnershipRequest = new PartitionOwnership()
.setFullyQualifiedNamespace(this.fullyQualifiedNamespace)
.setOwnerId(this.ownerId)
.setPartitionId(partitionIdToClaim)
.setConsumerGroup(this.consumerGroupName)
.setEventHubName(this.eventHubName)
.setETag(previousPartitionOwnership == null ? null : previousPartitionOwnership.getETag());
return partitionOwnershipRequest;
}
} | class PartitionBasedLoadBalancer {
private static final Random RANDOM = new Random();
private final ClientLogger logger = new ClientLogger(PartitionBasedLoadBalancer.class);
private final String eventHubName;
private final String consumerGroupName;
private final CheckpointStore checkpointStore;
private final EventHubAsyncClient eventHubAsyncClient;
private final String ownerId;
private final long inactiveTimeLimitInSeconds;
private final PartitionPumpManager partitionPumpManager;
private final String fullyQualifiedNamespace;
private final Consumer<ErrorContext> processError;
private final PartitionContext partitionAgnosticContext;
private final AtomicBoolean isLoadBalancerRunning = new AtomicBoolean();
/**
* Creates an instance of PartitionBasedLoadBalancer for the given Event Hub name and consumer group.
*
* @param checkpointStore The partition manager that this load balancer will use to read/update ownership details.
* @param eventHubAsyncClient The asynchronous Event Hub client used to consume events.
* @param eventHubName The Event Hub name the {@link EventProcessorClient} is associated with.
* @param consumerGroupName The consumer group name the {@link EventProcessorClient} is associated with.
* @param ownerId The identifier of the {@link EventProcessorClient} that owns this load balancer.
* @param inactiveTimeLimitInSeconds The time in seconds to wait for an update on an ownership record before
* assuming the owner of the partition is inactive.
* @param partitionPumpManager The partition pump manager that keeps track of all EventHubConsumers and partitions
* that this {@link EventProcessorClient} is processing.
* @param processError The callback that will be called when an error occurs while running the load balancer.
*/
PartitionBasedLoadBalancer(final CheckpointStore checkpointStore,
final EventHubAsyncClient eventHubAsyncClient, final String fullyQualifiedNamespace,
final String eventHubName, final String consumerGroupName, final String ownerId,
final long inactiveTimeLimitInSeconds, final PartitionPumpManager partitionPumpManager,
final Consumer<ErrorContext> processError) {
this.checkpointStore = checkpointStore;
this.eventHubAsyncClient = eventHubAsyncClient;
this.fullyQualifiedNamespace = fullyQualifiedNamespace;
this.eventHubName = eventHubName;
this.consumerGroupName = consumerGroupName;
this.ownerId = ownerId;
this.inactiveTimeLimitInSeconds = inactiveTimeLimitInSeconds;
this.partitionPumpManager = partitionPumpManager;
this.processError = processError;
this.partitionAgnosticContext = new PartitionContext(fullyQualifiedNamespace, eventHubName,
consumerGroupName, "NONE");
}
/**
* This is the main method responsible for load balancing. This method is expected to be invoked by the {@link
* EventProcessorClient} periodically. Every call to this method will result in this {@link EventProcessorClient}
* owning <b>at most one</b> new partition.
* <p>
* The load is considered balanced when no active EventProcessor owns 2 partitions more than any other active
* EventProcessor. Given that each invocation to this method results in ownership claim of at most one partition,
* this algorithm converges gradually towards a steady state.
* </p>
* When a new partition is claimed, this method is also responsible for starting a partition pump that creates an
* {@link EventHubConsumerAsyncClient} for processing events from that partition.
*/
void loadBalance() {
if (!isLoadBalancerRunning.compareAndSet(false, true)) {
logger.info("Load balancer already running");
return;
}
logger.info("Starting load balancer for {}", this.ownerId);
/*
* Retrieve current partition ownership details from the datastore.
*/
final Mono<Map<String, PartitionOwnership>> partitionOwnershipMono = checkpointStore
.listOwnership(fullyQualifiedNamespace, eventHubName, consumerGroupName)
.timeout(Duration.ofMinutes(1))
.collectMap(PartitionOwnership::getPartitionId, Function.identity());
/*
* Retrieve the list of partition ids from the Event Hub.
*/
final Mono<List<String>> partitionsMono = eventHubAsyncClient
.getPartitionIds()
.timeout(Duration.ofMinutes(1))
.collectList();
Mono.zip(partitionOwnershipMono, partitionsMono)
.flatMap(this::loadBalance)
.subscribe(ignored -> { },
ex -> {
logger.warning(Messages.LOAD_BALANCING_FAILED, ex.getMessage(), ex);
ErrorContext errorContext = new ErrorContext(partitionAgnosticContext, ex);
processError.accept(errorContext);
isLoadBalancerRunning.set(false);
}, () -> logger.info("Load balancing completed successfully"));
}
/*
* This method works with the given partition ownership details and Event Hub partitions to evaluate whether the
* current Event Processor should take on the responsibility of processing more partitions.
*/
private void renewOwnership(Map<String, PartitionOwnership> partitionOwnershipMap) {
checkpointStore.claimOwnership(partitionPumpManager.getPartitionPumps().keySet()
.stream()
.filter(
partitionId -> partitionOwnershipMap.containsKey(partitionId) && partitionOwnershipMap.get(partitionId)
.getOwnerId().equals(this.ownerId))
.map(partitionId -> createPartitionOwnershipRequest(partitionOwnershipMap, partitionId))
.collect(Collectors.toList()))
.subscribe(ignored -> { },
ex -> {
logger.error("Error renewing partition ownership", ex);
isLoadBalancerRunning.set(false);
},
() -> isLoadBalancerRunning.set(false));
}
private String format(Map<String, List<PartitionOwnership>> ownerPartitionMap) {
return ownerPartitionMap.entrySet()
.stream()
.map(entry -> {
StringBuilder sb = new StringBuilder();
sb.append(entry.getKey()).append("=[");
sb.append(entry.getValue().stream().map(po -> po.getPartitionId()).collect(Collectors.joining(",")));
sb.append("]");
return sb.toString();
}).collect(Collectors.joining(";"));
}
/*
* Check if partition ownership data is valid before proceeding with load balancing.
*/
private boolean isValid(final Map<String, PartitionOwnership> partitionOwnershipMap) {
return partitionOwnershipMap.values()
.stream()
.noneMatch(partitionOwnership -> {
return partitionOwnership.getEventHubName() == null
|| !partitionOwnership.getEventHubName().equals(this.eventHubName)
|| partitionOwnership.getConsumerGroup() == null
|| !partitionOwnership.getConsumerGroup().equals(this.consumerGroupName)
|| partitionOwnership.getPartitionId() == null
|| partitionOwnership.getLastModifiedTime() == null
|| partitionOwnership.getETag() == null;
});
}
/*
* Find the event processor that owns the maximum number of partitions and steal a random partition
* from it.
*/
private String findPartitionToSteal(final Map<String, List<PartitionOwnership>> ownerPartitionMap) {
Map.Entry<String, List<PartitionOwnership>> ownerWithMaxPartitions = ownerPartitionMap.entrySet()
.stream()
.max(Comparator.comparingInt(entry -> entry.getValue().size()))
.get();
int numberOfPartitions = ownerWithMaxPartitions.getValue().size();
logger.info("Owner id {} owns {} partitions, stealing a partition from it", ownerWithMaxPartitions.getKey(),
numberOfPartitions);
return ownerWithMaxPartitions.getValue().get(RANDOM.nextInt(numberOfPartitions)).getPartitionId();
}
/*
* When the load is balanced, all active event processors own at least {@code minPartitionsPerEventProcessor}
* and only {@code numberOfEventProcessorsWithAdditionalPartition} event processors will own 1 additional
* partition.
*/
private boolean isLoadBalanced(final int minPartitionsPerEventProcessor,
final int numberOfEventProcessorsWithAdditionalPartition,
final Map<String, List<PartitionOwnership>> ownerPartitionMap) {
int count = 0;
for (List<PartitionOwnership> partitionOwnership : ownerPartitionMap.values()) {
int numberOfPartitions = partitionOwnership.size();
if (numberOfPartitions < minPartitionsPerEventProcessor
|| numberOfPartitions > minPartitionsPerEventProcessor + 1) {
return false;
}
if (numberOfPartitions == minPartitionsPerEventProcessor + 1) {
count++;
}
}
return count == numberOfEventProcessorsWithAdditionalPartition;
}
/*
* This method is called after determining that the load is not balanced. This method will evaluate
* if the current event processor should own more partitions. Specifically, this method returns true if the
* current event processor owns less than the minimum number of partitions or if it owns the minimum number
* and no other event processor owns lesser number of partitions than this event processor.
*/
private boolean shouldOwnMorePartitions(final int minPartitionsPerEventProcessor,
final Map<String, List<PartitionOwnership>> ownerPartitionMap) {
int numberOfPartitionsOwned = ownerPartitionMap.get(this.ownerId).size();
int leastPartitionsOwnedByAnyEventProcessor =
ownerPartitionMap.values().stream().min(Comparator.comparingInt(List::size)).get().size();
return numberOfPartitionsOwned < minPartitionsPerEventProcessor
|| numberOfPartitionsOwned == leastPartitionsOwnedByAnyEventProcessor;
}
/*
* This method will create a new map of partition id and PartitionOwnership containing only those partitions
* that are actively owned. All entries in the original map returned by CheckpointStore that haven't been
* modified for a duration of time greater than the allowed inactivity time limit are assumed to be owned by
* dead event processors. These will not be included in the map returned by this method.
*/
private Map<String, PartitionOwnership> removeInactivePartitionOwnerships(
final Map<String, PartitionOwnership> partitionOwnershipMap) {
return partitionOwnershipMap
.entrySet()
.stream()
.filter(entry -> {
return (System.currentTimeMillis() - entry.getValue().getLastModifiedTime() < TimeUnit.SECONDS
.toMillis(inactiveTimeLimitInSeconds))
&& !CoreUtils.isNullOrEmpty(entry.getValue().getOwnerId());
}).collect(Collectors.toMap(Entry::getKey, Entry::getValue));
}
private void claimOwnership(final Map<String, PartitionOwnership> partitionOwnershipMap, Map<String,
List<PartitionOwnership>> ownerPartitionsMap, final String partitionIdToClaim) {
logger.info("Attempting to claim ownership of partition {}", partitionIdToClaim);
PartitionOwnership ownershipRequest = createPartitionOwnershipRequest(partitionOwnershipMap,
partitionIdToClaim);
List<PartitionOwnership> partitionsToClaim = new ArrayList<>();
partitionsToClaim.add(ownershipRequest);
partitionsToClaim.addAll(partitionPumpManager.getPartitionPumps()
.keySet()
.stream()
.filter(
partitionId -> partitionOwnershipMap.containsKey(partitionId) && partitionOwnershipMap.get(partitionId)
.getOwnerId().equals(this.ownerId))
.map(partitionId -> createPartitionOwnershipRequest(partitionOwnershipMap, partitionId))
.collect(Collectors.toList()));
checkpointStore
.claimOwnership(partitionsToClaim)
.timeout(Duration.ofMinutes(1))
.doOnNext(partitionOwnership -> logger.info("Successfully claimed ownership of partition {}",
partitionOwnership.getPartitionId()))
.doOnError(ex -> logger
.warning(Messages.FAILED_TO_CLAIM_OWNERSHIP, ownershipRequest.getPartitionId(),
ex.getMessage(), ex))
.collectList()
.zipWhen(ownershipList -> checkpointStore.listCheckpoints(fullyQualifiedNamespace, eventHubName,
consumerGroupName)
.collectMap(checkpoint -> checkpoint.getPartitionId(), Function.identity()))
.subscribe(ownedPartitionCheckpointsTuple -> {
ownedPartitionCheckpointsTuple.getT1()
.stream()
.forEach(po -> partitionPumpManager.startPartitionPump(po,
ownedPartitionCheckpointsTuple.getT2().get(po.getPartitionId())));
},
ex -> {
logger.warning("Error while listing checkpoints", ex);
ErrorContext errorContext = new ErrorContext(partitionAgnosticContext, ex);
processError.accept(errorContext);
isLoadBalancerRunning.set(false);
throw logger.logExceptionAsError(new IllegalStateException("Error while listing checkpoints", ex));
},
() -> isLoadBalancerRunning.set(false));
}
private PartitionOwnership createPartitionOwnershipRequest(
final Map<String, PartitionOwnership> partitionOwnershipMap,
final String partitionIdToClaim) {
PartitionOwnership previousPartitionOwnership = partitionOwnershipMap.get(partitionIdToClaim);
PartitionOwnership partitionOwnershipRequest = new PartitionOwnership()
.setFullyQualifiedNamespace(this.fullyQualifiedNamespace)
.setOwnerId(this.ownerId)
.setPartitionId(partitionIdToClaim)
.setConsumerGroup(this.consumerGroupName)
.setEventHubName(this.eventHubName)
.setETag(previousPartitionOwnership == null ? null : previousPartitionOwnership.getETag());
return partitionOwnershipRequest;
}
} |
As I mentioned before, here we create CosmosConfig instance with database name, can we use the same instance to create different cosmos template? see [secondaryReactiveCosmosTemplate](https://github.com/Azure/azure-sdk-for-java/pull/13756/files#diff-254b2abc35cb0feeba0f6eeb236386b9R109) and [secondaryReactiveCosmosTemplate1](https://github.com/Azure/azure-sdk-for-java/pull/13756/files#diff-254b2abc35cb0feeba0f6eeb236386b9R116), we use the same CosmosConfig instance | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.database(secondaryProperties.getDatabase())
.build();
} | .build(); | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.build();
} | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter, cosmosAuditingHandler);
}
} | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter, cosmosAuditingHandler);
}
} |
Customers can still use the same `cosmosConfig` instance. Since they will anyway pass the `databaseName` to create `CosmosTemplate` - which then picks up the database from `CosmosFactory` here : From `CosmosTemplate` constructor - `this.databaseName = cosmosFactory.getDatabaseName();` | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.database(secondaryProperties.getDatabase())
.build();
} | .build(); | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.build();
} | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter, cosmosAuditingHandler);
}
} | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter, cosmosAuditingHandler);
}
} |
it's ok, but I think it's a bit confusing, actually, database2 can use the same CosmosConfig instance which created with database1. so the CosmosConfig is not really directly related to the database name. @saragluna do you have any other ideas? | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.database(secondaryProperties.getDatabase())
.build();
} | .build(); | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.build();
} | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter, cosmosAuditingHandler);
}
} | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter, cosmosAuditingHandler);
}
} |
Yes, that is true. `CosmosConfig` is not directly related to the database name. In fact, I was also wondering, if we can completely get rid of `database` from `CosmosConfig` and customers can directly override the method `getDatabaseName()` from `CosmosConfigurationSupport` class. That's what spring-data-mongodb does. They don't have any config tied to the database. They only have `getDatabaseName()` in `MongoConfigurationSupport` class. However, it will not hurt to keep it in `CosmosConfig`, because of easiness of use. Having `database` in `CosmosConfig` provides the user ability to use the database from the `CosmosConfig` bean. What are your thoughts on this @zhoufenqin @saragluna | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.database(secondaryProperties.getDatabase())
.build();
} | .build(); | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.build();
} | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter, cosmosAuditingHandler);
}
} | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter, cosmosAuditingHandler);
}
} |
@kushagraThapar in my opinion, since `CosmosConfig` is not directly related to the database name so I vote for getting rid of it. Do you know in which case will the user try to get the database name? | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.database(secondaryProperties.getDatabase())
.build();
} | .build(); | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.build();
} | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter, cosmosAuditingHandler);
}
} | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter, cosmosAuditingHandler);
}
} |
@saragluna - in case of custom query execution. take a look at this example - https://github.com/kushagraThapar/azure-sdk-for-java/blob/update_cosmos_config_spring_data_cosmos/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageableAddressRepositoryIT.java#L165 So in that case, I think it will be much easier to Autowire the `CosmosConfig` bean. In the above specific case, do you know if customer can autowire `TestRepositoryConfig` bean somehow and get it from there ? | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.database(secondaryProperties.getDatabase())
.build();
} | .build(); | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.build();
} | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter, cosmosAuditingHandler);
}
} | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter, cosmosAuditingHandler);
}
} |
@saragluna - I did some more testing, and I found out that in above specific case, customer can get it from `CosmosFactory`. So I am good to remove `database` from `CosmosConfig` | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.database(secondaryProperties.getDatabase())
.build();
} | .build(); | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.build();
} | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter, cosmosAuditingHandler);
}
} | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter, cosmosAuditingHandler);
}
} |
This isn't reactive to have to create a new Mono operation everytime a message come in. How about a combination of `Flux.swithOnNext(publisher).takeUntil(notCancelled)` where a new item is emitted from the `publisher` if there is a next message? And for each item emitted, delay at an interval. So if the item is emitted, then cancel the emitter. | void next(ServiceBusReceivedMessageContext message) {
try {
if (timeoutBeforeNextMessageOperation != null && !timeoutBeforeNextMessageOperation.isDisposed()) {
timeoutBeforeNextMessageOperation.dispose();
}
emitter.next(message);
remaining.decrementAndGet();
timeoutBeforeNextMessageOperation = getShortTimeoutBetweenMessages();
} catch (Exception e) {
logger.warning("Exception occurred while publishing downstream.", e);
error(e);
}
} | if (timeoutBeforeNextMessageOperation != null && !timeoutBeforeNextMessageOperation.isDisposed()) { | void next(ServiceBusReceivedMessageContext message) {
try {
emitter.next(message);
messageReceivedSink.next(message);
remaining.decrementAndGet();
} catch (Exception e) {
logger.warning("Exception occurred while publishing downstream.", e);
error(e);
}
} | class SynchronousReceiveWork {
private final ClientLogger logger = new ClientLogger(SynchronousReceiveWork.class);
private final long id;
private final AtomicInteger remaining;
private final int numberToReceive;
private final Duration timeout;
private final FluxSink<ServiceBusReceivedMessageContext> emitter;
private boolean workTimedOut = false;
private boolean nextMessageTimedOut = false;
private boolean processingStarted;
private Disposable timeoutBeforeNextMessageOperation;
private volatile Throwable error = null;
/**
* Creates a new synchronous receive work.
*
* @param id Identifier for the work.
* @param numberToReceive Maximum number of events to receive.
* @param timeout Maximum duration to wait for {@code numberOfReceive} events.
* @param emitter Sink to publish received messages to.
*/
SynchronousReceiveWork(long id, int numberToReceive, Duration timeout,
FluxSink<ServiceBusReceivedMessageContext> emitter) {
this.id = id;
this.remaining = new AtomicInteger(numberToReceive);
this.numberToReceive = numberToReceive;
this.timeout = timeout;
this.emitter = emitter;
}
/**
* Gets the unique identifier for this work.
*
* @return The unique identifier for this work.
*/
long getId() {
return id;
}
/**
* Gets the maximum duration to wait for the work to complete.
*
* @return The duration to wait for the work to complete.
*/
Duration getTimeout() {
return timeout;
}
/**
* Gets the number of events to receive.
*
* @return The number of events to receive.
*/
int getNumberOfEvents() {
return numberToReceive;
}
/**
* @return remaining events to receive.
*/
int getRemaining() {
return remaining.get();
}
/**
* Gets whether or not the work item has reached a terminal state.
*
* @return {@code true} if all the events have been fetched, it has been cancelled, or an error occurred. {@code
* false} otherwise.
*/
boolean isTerminal() {
return emitter.isCancelled() || remaining.get() == 0 || error != null || workTimedOut || nextMessageTimedOut;
}
/**
* Publishes the next message to a downstream subscriber.
*
* @param message Event to publish downstream.
*/
/**
* Completes the publisher. If the publisher has encountered an error, or an error has occurred, it does nothing.
*/
void complete() {
logger.info("[{}]: Completing task.", id);
emitter.complete();
close();
}
/**
* Completes the publisher and sets the state to timeout.
*/
void timeout() {
logger.info("[{}]: Work timeout occurred. Completing the work.", id);
emitter.complete();
workTimedOut = true;
close();
}
/**
* Publishes an error downstream. This is a terminal step.
*
* @param error Error to publish downstream.
*/
void error(Throwable error) {
this.error = error;
emitter.error(error);
close();
}
/**
* Returns the error object.
* @return the error.
*/
Throwable getError() {
return this.error;
}
/**
* Indiate that processing is started for this work.
*/
void startedProcessing() {
this.processingStarted = true;
}
/**
*
* @return flag indicting that processing is started or not.
*/
boolean isProcessingStarted() {
return this.processingStarted;
}
private void close() {
if (timeoutBeforeNextMessageOperation != null && !timeoutBeforeNextMessageOperation.isDisposed()) {
timeoutBeforeNextMessageOperation.dispose();
}
}
/**
*
* @return {@link Disposable} for the timeout operation.
*/
private Disposable getShortTimeoutBetweenMessages() {
return Mono.delay(ServiceBusConstants.SHORT_TIMEOUT_BETWEEN_MESSAGES)
.subscribe(l -> {
timeoutNextMessage();
});
}
/**
* Completes the publisher and sets the state to timeout.
*/
private void timeoutNextMessage() {
logger.info("[{}]: Work timeout occurred due to next message not arriving in time. Completing the work.", id);
emitter.complete();
nextMessageTimedOut = true;
close();
}
} | class SynchronousReceiveWork implements AutoCloseable {
/* When we have received at-least one message and next message does not arrive in this time. The work will
complete.*/
private static final Duration TIMEOUT_BETWEEN_MESSAGES = Duration.ofMillis(1000);
private final ClientLogger logger = new ClientLogger(SynchronousReceiveWork.class);
private final long id;
private final AtomicInteger remaining;
private final int numberToReceive;
private final Duration timeout;
private final FluxSink<ServiceBusReceivedMessageContext> emitter;
private final FluxSink<ServiceBusReceivedMessageContext> messageReceivedSink;
private final DirectProcessor<ServiceBusReceivedMessageContext> emitterProcessor;
private final Disposable nextMessageSubscriber;
private boolean workTimedOut = false;
private boolean processingStarted;
private volatile Throwable error = null;
/**
* Creates a new synchronous receive work.
*
* @param id Identifier for the work.
* @param numberToReceive Maximum number of events to receive.
* @param timeout Maximum duration to wait for {@code numberOfReceive} events.
* @param emitter Sink to publish received messages to.
*/
SynchronousReceiveWork(long id, int numberToReceive, Duration timeout,
FluxSink<ServiceBusReceivedMessageContext> emitter) {
this.id = id;
this.remaining = new AtomicInteger(numberToReceive);
this.numberToReceive = numberToReceive;
this.timeout = timeout;
this.emitter = emitter;
emitterProcessor = DirectProcessor.create();
messageReceivedSink = emitterProcessor.sink();
nextMessageSubscriber = Flux.switchOnNext(emitterProcessor.map(messageContext ->
Flux.interval(TIMEOUT_BETWEEN_MESSAGES)))
.handle((delay, sink) -> {
logger.info("[{}]: Timeout between the messages occurred. Completing the work.", id);
sink.next(delay);
emitter.complete();
})
.subscribe();
}
/**
* Gets the unique identifier for this work.
*
* @return The unique identifier for this work.
*/
long getId() {
return id;
}
/**
* Gets the maximum duration to wait for the work to complete.
*
* @return The duration to wait for the work to complete.
*/
Duration getTimeout() {
return timeout;
}
/**
* Gets the number of events to receive.
*
* @return The number of events to receive.
*/
int getNumberOfEvents() {
return numberToReceive;
}
/**
* @return remaining events to receive.
*/
int getRemaining() {
return remaining.get();
}
/**
* Gets whether or not the work item has reached a terminal state.
*
* @return {@code true} if all the events have been fetched, it has been cancelled, or an error occurred. {@code
* false} otherwise.
*/
boolean isTerminal() {
return emitter.isCancelled() || remaining.get() == 0 || error != null || workTimedOut;
}
/**
* Publishes the next message to a downstream subscriber.
*
* @param message Event to publish downstream.
*/
/**
* Completes the publisher. If the publisher has encountered an error, or an error has occurred, it does nothing.
*/
void complete() {
logger.info("[{}]: Completing task.", id);
emitter.complete();
close();
}
/**
* Completes the publisher and sets the state to timeout.
*/
void timeout() {
logger.info("[{}]: Work timeout occurred. Completing the work.", id);
emitter.complete();
workTimedOut = true;
close();
}
/**
* Publishes an error downstream. This is a terminal step.
*
* @param error Error to publish downstream.
*/
void error(Throwable error) {
this.error = error;
emitter.error(error);
close();
}
/**
* Returns the error object.
* @return the error.
*/
Throwable getError() {
return this.error;
}
/**
* Indiate that processing is started for this work.
*/
void startedProcessing() {
this.processingStarted = true;
}
/**
*
* @return flag indicting that processing is started or not.
*/
boolean isProcessingStarted() {
return this.processingStarted;
}
@Override
public void close() {
if (!nextMessageSubscriber.isDisposed()) {
nextMessageSubscriber.dispose();
}
}
} |
is the null check necessary? Isn't this always set in the constructor. You can just call dispose. | public void close() {
if (nextMessageSubscriber != null && !nextMessageSubscriber.isDisposed()) {
nextMessageSubscriber.dispose();
}
} | if (nextMessageSubscriber != null && !nextMessageSubscriber.isDisposed()) { | public void close() {
if (!nextMessageSubscriber.isDisposed()) {
nextMessageSubscriber.dispose();
}
} | class SynchronousReceiveWork implements AutoCloseable {
/* When we have received at-least one message and next message does not arrive in this time. The work will
complete.*/
private static final Duration SHORT_TIMEOUT_BETWEEN_MESSAGES = Duration.ofMillis(1000);
private final ClientLogger logger = new ClientLogger(SynchronousReceiveWork.class);
private final long id;
private final AtomicInteger remaining;
private final int numberToReceive;
private final Duration timeout;
private final FluxSink<ServiceBusReceivedMessageContext> emitter;
private final FluxSink<ServiceBusReceivedMessageContext> messageReceivedSink;
private final Disposable nextMessageSubscriber;
private boolean workTimedOut = false;
private boolean processingStarted;
private volatile Throwable error = null;
/**
* Creates a new synchronous receive work.
*
* @param id Identifier for the work.
* @param numberToReceive Maximum number of events to receive.
* @param timeout Maximum duration to wait for {@code numberOfReceive} events.
* @param emitter Sink to publish received messages to.
*/
SynchronousReceiveWork(long id, int numberToReceive, Duration timeout,
FluxSink<ServiceBusReceivedMessageContext> emitter) {
this.id = id;
this.remaining = new AtomicInteger(numberToReceive);
this.numberToReceive = numberToReceive;
this.timeout = timeout;
this.emitter = emitter;
DirectProcessor<ServiceBusReceivedMessageContext> emitterProcessor = DirectProcessor.create();
messageReceivedSink = emitterProcessor.sink();
nextMessageSubscriber = Flux.switchOnNext(emitterProcessor.map(messageContext ->
Flux.interval(SHORT_TIMEOUT_BETWEEN_MESSAGES)))
.handle((delay, sink) -> {
logger.info("[{}]: Timeout between the messages occurred. Completing the work.", id);
sink.next(delay);
emitter.complete();
})
.subscribe();
}
/**
* Gets the unique identifier for this work.
*
* @return The unique identifier for this work.
*/
long getId() {
return id;
}
/**
* Gets the maximum duration to wait for the work to complete.
*
* @return The duration to wait for the work to complete.
*/
Duration getTimeout() {
return timeout;
}
/**
* Gets the number of events to receive.
*
* @return The number of events to receive.
*/
int getNumberOfEvents() {
return numberToReceive;
}
/**
* @return remaining events to receive.
*/
int getRemaining() {
return remaining.get();
}
/**
* Gets whether or not the work item has reached a terminal state.
*
* @return {@code true} if all the events have been fetched, it has been cancelled, or an error occurred. {@code
* false} otherwise.
*/
boolean isTerminal() {
return emitter.isCancelled() || remaining.get() == 0 || error != null || workTimedOut;
}
/**
* Publishes the next message to a downstream subscriber.
*
* @param message Event to publish downstream.
*/
void next(ServiceBusReceivedMessageContext message) {
try {
emitter.next(message);
messageReceivedSink.next(message);
remaining.decrementAndGet();
} catch (Exception e) {
logger.warning("Exception occurred while publishing downstream.", e);
error(e);
}
}
/**
* Completes the publisher. If the publisher has encountered an error, or an error has occurred, it does nothing.
*/
void complete() {
logger.info("[{}]: Completing task.", id);
emitter.complete();
close();
}
/**
* Completes the publisher and sets the state to timeout.
*/
void timeout() {
logger.info("[{}]: Work timeout occurred. Completing the work.", id);
emitter.complete();
workTimedOut = true;
close();
}
/**
* Publishes an error downstream. This is a terminal step.
*
* @param error Error to publish downstream.
*/
void error(Throwable error) {
this.error = error;
emitter.error(error);
close();
}
/**
* Returns the error object.
* @return the error.
*/
Throwable getError() {
return this.error;
}
/**
* Indiate that processing is started for this work.
*/
void startedProcessing() {
this.processingStarted = true;
}
/**
*
* @return flag indicting that processing is started or not.
*/
boolean isProcessingStarted() {
return this.processingStarted;
}
@Override
} | class SynchronousReceiveWork implements AutoCloseable {
/* When we have received at-least one message and next message does not arrive in this time. The work will
complete.*/
private static final Duration TIMEOUT_BETWEEN_MESSAGES = Duration.ofMillis(1000);
private final ClientLogger logger = new ClientLogger(SynchronousReceiveWork.class);
private final long id;
private final AtomicInteger remaining;
private final int numberToReceive;
private final Duration timeout;
private final FluxSink<ServiceBusReceivedMessageContext> emitter;
private final FluxSink<ServiceBusReceivedMessageContext> messageReceivedSink;
private final DirectProcessor<ServiceBusReceivedMessageContext> emitterProcessor;
private final Disposable nextMessageSubscriber;
private boolean workTimedOut = false;
private boolean processingStarted;
private volatile Throwable error = null;
/**
* Creates a new synchronous receive work.
*
* @param id Identifier for the work.
* @param numberToReceive Maximum number of events to receive.
* @param timeout Maximum duration to wait for {@code numberOfReceive} events.
* @param emitter Sink to publish received messages to.
*/
SynchronousReceiveWork(long id, int numberToReceive, Duration timeout,
FluxSink<ServiceBusReceivedMessageContext> emitter) {
this.id = id;
this.remaining = new AtomicInteger(numberToReceive);
this.numberToReceive = numberToReceive;
this.timeout = timeout;
this.emitter = emitter;
emitterProcessor = DirectProcessor.create();
messageReceivedSink = emitterProcessor.sink();
nextMessageSubscriber = Flux.switchOnNext(emitterProcessor.map(messageContext ->
Flux.interval(TIMEOUT_BETWEEN_MESSAGES)))
.handle((delay, sink) -> {
logger.info("[{}]: Timeout between the messages occurred. Completing the work.", id);
sink.next(delay);
emitter.complete();
})
.subscribe();
}
/**
* Gets the unique identifier for this work.
*
* @return The unique identifier for this work.
*/
long getId() {
return id;
}
/**
* Gets the maximum duration to wait for the work to complete.
*
* @return The duration to wait for the work to complete.
*/
Duration getTimeout() {
return timeout;
}
/**
* Gets the number of events to receive.
*
* @return The number of events to receive.
*/
int getNumberOfEvents() {
return numberToReceive;
}
/**
* @return remaining events to receive.
*/
int getRemaining() {
return remaining.get();
}
/**
* Gets whether or not the work item has reached a terminal state.
*
* @return {@code true} if all the events have been fetched, it has been cancelled, or an error occurred. {@code
* false} otherwise.
*/
boolean isTerminal() {
return emitter.isCancelled() || remaining.get() == 0 || error != null || workTimedOut;
}
/**
* Publishes the next message to a downstream subscriber.
*
* @param message Event to publish downstream.
*/
void next(ServiceBusReceivedMessageContext message) {
try {
emitter.next(message);
messageReceivedSink.next(message);
remaining.decrementAndGet();
} catch (Exception e) {
logger.warning("Exception occurred while publishing downstream.", e);
error(e);
}
}
/**
* Completes the publisher. If the publisher has encountered an error, or an error has occurred, it does nothing.
*/
void complete() {
logger.info("[{}]: Completing task.", id);
emitter.complete();
close();
}
/**
* Completes the publisher and sets the state to timeout.
*/
void timeout() {
logger.info("[{}]: Work timeout occurred. Completing the work.", id);
emitter.complete();
workTimedOut = true;
close();
}
/**
* Publishes an error downstream. This is a terminal step.
*
* @param error Error to publish downstream.
*/
void error(Throwable error) {
this.error = error;
emitter.error(error);
close();
}
/**
* Returns the error object.
* @return the error.
*/
Throwable getError() {
return this.error;
}
/**
* Indiate that processing is started for this work.
*/
void startedProcessing() {
this.processingStarted = true;
}
/**
*
* @return flag indicting that processing is started or not.
*/
boolean isProcessingStarted() {
return this.processingStarted;
}
@Override
} |
If you send another iteration, can we please use variable itself in logger for canUseMultipleWriteLocations , instead of true and false | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints();
if (this.sessionTokenRetryCount > endpoints.size()) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, going to retry on next location", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
} else {
if (this.sessionTokenRetryCount > 1) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, going to retry", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
}
}
} | logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount); | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints();
if (this.sessionTokenRetryCount > endpoints.size()) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, going to retry on next location", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
} else {
if (this.sessionTokenRetryCount > 1) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, going to retry", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
}
}
} | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointManager globalEndpointManager;
private final boolean enableEndpointDiscovery;
private int failoverRetryCount;
private int sessionTokenRetryCount;
private boolean isReadRequest;
private boolean canUseMultipleWriteLocations;
private URL locationEndpoint;
private RetryContext retryContext;
private CosmosResponseDiagnostics cosmosResponseDiagnostics;
private AtomicInteger cnt = new AtomicInteger(0);
public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager,
boolean enableEndpointDiscovery,
RetryOptions retryOptions) {
this.throttlingRetry = new ResourceThrottleRetryPolicy(
retryOptions.maxRetryAttemptsOnThrottledRequests(),
retryOptions.maxRetryWaitTimeInSeconds());
this.globalEndpointManager = globalEndpointManager;
this.failoverRetryCount = 0;
this.enableEndpointDiscovery = enableEndpointDiscovery;
this.sessionTokenRetryCount = 0;
this.canUseMultipleWriteLocations = false;
this.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics();
}
@Override
public Mono<ShouldRetryResult> shouldRetry(Exception e) {
logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:",
cnt.incrementAndGet(),
isReadRequest,
canUseMultipleWriteLocations,
e);
if (this.locationEndpoint == null) {
logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " +
"probably request creation failed due to invalid options, serialization setting, etc.");
return Mono.just(ShouldRetryResult.error(e));
}
this.retryContext = null;
CosmosClientException clientException = Utils.as(e, CosmosClientException.class);
if (clientException != null && clientException.cosmosResponseDiagnostics() != null) {
this.cosmosResponseDiagnostics = clientException.cosmosResponseDiagnostics();
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN))
{
logger.warn("Endpoint not writable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(false, true);
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) &&
this.isReadRequest)
{
logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(true, false);
}
if (WebExceptionUtility.isNetworkFailure(e)) {
if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) {
logger.warn("Endpoint not reachable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false);
} else {
logger.warn("Endpoint not reachable. Can't retry on write", e);
return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false);
}
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) {
return Mono.just(this.shouldRetryOnSessionNotAvailable());
}
return this.throttlingRetry.shouldRetry(e);
}
private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
Duration retryDelay = Duration.ZERO;
if (!this.isReadRequest) {
logger.debug("Failover happening. retryCount {}", this.failoverRetryCount);
if (this.failoverRetryCount > 1) {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
} else {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay)));
}
private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry()));
}
private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) {
this.failoverRetryCount++;
if (isReadRequest) {
logger.warn("marking the endpoint {} as unavailable for read", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint);
} else {
logger.warn("marking the endpoint {} as unavailable for write", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint);
}
return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh);
}
@Override
public void onBeforeSendRequest(RxDocumentServiceRequest request) {
this.isReadRequest = request.isReadOnlyRequest();
this.canUseMultipleWriteLocations = this.globalEndpointManager.CanUseMultipleWriteLocations(request);
if (request.requestContext != null) {
request.requestContext.cosmosResponseDiagnostics = this.cosmosResponseDiagnostics;
}
if (request.requestContext != null) {
request.requestContext.ClearRouteToLocation();
}
if (this.retryContext != null) {
request.requestContext.RouteToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations);
}
this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request);
if (request.requestContext != null) {
request.requestContext.RouteToLocation(this.locationEndpoint);
}
}
private class RetryContext {
public int retryCount;
public boolean retryRequestOnPreferredLocations;
public RetryContext(int retryCount,
boolean retryRequestOnPreferredLocations) {
this.retryCount = retryCount;
this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations;
}
}
} | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointManager globalEndpointManager;
private final boolean enableEndpointDiscovery;
private int failoverRetryCount;
private int sessionTokenRetryCount;
private boolean isReadRequest;
private boolean canUseMultipleWriteLocations;
private URL locationEndpoint;
private RetryContext retryContext;
private CosmosResponseDiagnostics cosmosResponseDiagnostics;
private AtomicInteger cnt = new AtomicInteger(0);
public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager,
boolean enableEndpointDiscovery,
RetryOptions retryOptions) {
this.throttlingRetry = new ResourceThrottleRetryPolicy(
retryOptions.maxRetryAttemptsOnThrottledRequests(),
retryOptions.maxRetryWaitTimeInSeconds());
this.globalEndpointManager = globalEndpointManager;
this.failoverRetryCount = 0;
this.enableEndpointDiscovery = enableEndpointDiscovery;
this.sessionTokenRetryCount = 0;
this.canUseMultipleWriteLocations = false;
this.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics();
}
@Override
public Mono<ShouldRetryResult> shouldRetry(Exception e) {
logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:",
cnt.incrementAndGet(),
isReadRequest,
canUseMultipleWriteLocations,
e);
if (this.locationEndpoint == null) {
logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " +
"probably request creation failed due to invalid options, serialization setting, etc.");
return Mono.just(ShouldRetryResult.error(e));
}
this.retryContext = null;
CosmosClientException clientException = Utils.as(e, CosmosClientException.class);
if (clientException != null && clientException.cosmosResponseDiagnostics() != null) {
this.cosmosResponseDiagnostics = clientException.cosmosResponseDiagnostics();
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN))
{
logger.warn("Endpoint not writable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(false, true);
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) &&
this.isReadRequest)
{
logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(true, false);
}
if (WebExceptionUtility.isNetworkFailure(e)) {
if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) {
logger.warn("Endpoint not reachable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false);
} else {
logger.warn("Endpoint not reachable. Can't retry on write", e);
return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false);
}
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) {
return Mono.just(this.shouldRetryOnSessionNotAvailable());
}
return this.throttlingRetry.shouldRetry(e);
}
private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
Duration retryDelay = Duration.ZERO;
if (!this.isReadRequest) {
logger.debug("Failover happening. retryCount {}", this.failoverRetryCount);
if (this.failoverRetryCount > 1) {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
} else {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay)));
}
private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry()));
}
private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) {
this.failoverRetryCount++;
if (isReadRequest) {
logger.warn("marking the endpoint {} as unavailable for read", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint);
} else {
logger.warn("marking the endpoint {} as unavailable for write", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint);
}
return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh);
}
@Override
public void onBeforeSendRequest(RxDocumentServiceRequest request) {
this.isReadRequest = request.isReadOnlyRequest();
this.canUseMultipleWriteLocations = this.globalEndpointManager.CanUseMultipleWriteLocations(request);
if (request.requestContext != null) {
request.requestContext.cosmosResponseDiagnostics = this.cosmosResponseDiagnostics;
}
if (request.requestContext != null) {
request.requestContext.ClearRouteToLocation();
}
if (this.retryContext != null) {
request.requestContext.RouteToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations);
}
this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request);
if (request.requestContext != null) {
request.requestContext.RouteToLocation(this.locationEndpoint);
}
}
private class RetryContext {
public int retryCount;
public boolean retryRequestOnPreferredLocations;
public RetryContext(int retryCount,
boolean retryRequestOnPreferredLocations) {
this.retryCount = retryCount;
this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations;
}
}
} |
what's the advantage? in the if branch the value is deterministic | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints();
if (this.sessionTokenRetryCount > endpoints.size()) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, going to retry on next location", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
} else {
if (this.sessionTokenRetryCount > 1) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, going to retry", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
}
}
} | logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount); | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints();
if (this.sessionTokenRetryCount > endpoints.size()) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, going to retry on next location", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
} else {
if (this.sessionTokenRetryCount > 1) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, going to retry", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
}
}
} | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointManager globalEndpointManager;
private final boolean enableEndpointDiscovery;
private int failoverRetryCount;
private int sessionTokenRetryCount;
private boolean isReadRequest;
private boolean canUseMultipleWriteLocations;
private URL locationEndpoint;
private RetryContext retryContext;
private CosmosResponseDiagnostics cosmosResponseDiagnostics;
private AtomicInteger cnt = new AtomicInteger(0);
public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager,
boolean enableEndpointDiscovery,
RetryOptions retryOptions) {
this.throttlingRetry = new ResourceThrottleRetryPolicy(
retryOptions.maxRetryAttemptsOnThrottledRequests(),
retryOptions.maxRetryWaitTimeInSeconds());
this.globalEndpointManager = globalEndpointManager;
this.failoverRetryCount = 0;
this.enableEndpointDiscovery = enableEndpointDiscovery;
this.sessionTokenRetryCount = 0;
this.canUseMultipleWriteLocations = false;
this.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics();
}
@Override
public Mono<ShouldRetryResult> shouldRetry(Exception e) {
logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:",
cnt.incrementAndGet(),
isReadRequest,
canUseMultipleWriteLocations,
e);
if (this.locationEndpoint == null) {
logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " +
"probably request creation failed due to invalid options, serialization setting, etc.");
return Mono.just(ShouldRetryResult.error(e));
}
this.retryContext = null;
CosmosClientException clientException = Utils.as(e, CosmosClientException.class);
if (clientException != null && clientException.cosmosResponseDiagnostics() != null) {
this.cosmosResponseDiagnostics = clientException.cosmosResponseDiagnostics();
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN))
{
logger.warn("Endpoint not writable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(false, true);
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) &&
this.isReadRequest)
{
logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(true, false);
}
if (WebExceptionUtility.isNetworkFailure(e)) {
if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) {
logger.warn("Endpoint not reachable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false);
} else {
logger.warn("Endpoint not reachable. Can't retry on write", e);
return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false);
}
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) {
return Mono.just(this.shouldRetryOnSessionNotAvailable());
}
return this.throttlingRetry.shouldRetry(e);
}
private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
Duration retryDelay = Duration.ZERO;
if (!this.isReadRequest) {
logger.debug("Failover happening. retryCount {}", this.failoverRetryCount);
if (this.failoverRetryCount > 1) {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
} else {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay)));
}
private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry()));
}
private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) {
this.failoverRetryCount++;
if (isReadRequest) {
logger.warn("marking the endpoint {} as unavailable for read", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint);
} else {
logger.warn("marking the endpoint {} as unavailable for write", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint);
}
return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh);
}
@Override
public void onBeforeSendRequest(RxDocumentServiceRequest request) {
this.isReadRequest = request.isReadOnlyRequest();
this.canUseMultipleWriteLocations = this.globalEndpointManager.CanUseMultipleWriteLocations(request);
if (request.requestContext != null) {
request.requestContext.cosmosResponseDiagnostics = this.cosmosResponseDiagnostics;
}
if (request.requestContext != null) {
request.requestContext.ClearRouteToLocation();
}
if (this.retryContext != null) {
request.requestContext.RouteToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations);
}
this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request);
if (request.requestContext != null) {
request.requestContext.RouteToLocation(this.locationEndpoint);
}
}
private class RetryContext {
public int retryCount;
public boolean retryRequestOnPreferredLocations;
public RetryContext(int retryCount,
boolean retryRequestOnPreferredLocations) {
this.retryCount = retryCount;
this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations;
}
}
} | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointManager globalEndpointManager;
private final boolean enableEndpointDiscovery;
private int failoverRetryCount;
private int sessionTokenRetryCount;
private boolean isReadRequest;
private boolean canUseMultipleWriteLocations;
private URL locationEndpoint;
private RetryContext retryContext;
private CosmosResponseDiagnostics cosmosResponseDiagnostics;
private AtomicInteger cnt = new AtomicInteger(0);
public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager,
boolean enableEndpointDiscovery,
RetryOptions retryOptions) {
this.throttlingRetry = new ResourceThrottleRetryPolicy(
retryOptions.maxRetryAttemptsOnThrottledRequests(),
retryOptions.maxRetryWaitTimeInSeconds());
this.globalEndpointManager = globalEndpointManager;
this.failoverRetryCount = 0;
this.enableEndpointDiscovery = enableEndpointDiscovery;
this.sessionTokenRetryCount = 0;
this.canUseMultipleWriteLocations = false;
this.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics();
}
@Override
public Mono<ShouldRetryResult> shouldRetry(Exception e) {
logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:",
cnt.incrementAndGet(),
isReadRequest,
canUseMultipleWriteLocations,
e);
if (this.locationEndpoint == null) {
logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " +
"probably request creation failed due to invalid options, serialization setting, etc.");
return Mono.just(ShouldRetryResult.error(e));
}
this.retryContext = null;
CosmosClientException clientException = Utils.as(e, CosmosClientException.class);
if (clientException != null && clientException.cosmosResponseDiagnostics() != null) {
this.cosmosResponseDiagnostics = clientException.cosmosResponseDiagnostics();
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN))
{
logger.warn("Endpoint not writable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(false, true);
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) &&
this.isReadRequest)
{
logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(true, false);
}
if (WebExceptionUtility.isNetworkFailure(e)) {
if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) {
logger.warn("Endpoint not reachable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false);
} else {
logger.warn("Endpoint not reachable. Can't retry on write", e);
return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false);
}
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) {
return Mono.just(this.shouldRetryOnSessionNotAvailable());
}
return this.throttlingRetry.shouldRetry(e);
}
private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
Duration retryDelay = Duration.ZERO;
if (!this.isReadRequest) {
logger.debug("Failover happening. retryCount {}", this.failoverRetryCount);
if (this.failoverRetryCount > 1) {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
} else {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay)));
}
private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry()));
}
private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) {
this.failoverRetryCount++;
if (isReadRequest) {
logger.warn("marking the endpoint {} as unavailable for read", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint);
} else {
logger.warn("marking the endpoint {} as unavailable for write", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint);
}
return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh);
}
@Override
public void onBeforeSendRequest(RxDocumentServiceRequest request) {
this.isReadRequest = request.isReadOnlyRequest();
this.canUseMultipleWriteLocations = this.globalEndpointManager.CanUseMultipleWriteLocations(request);
if (request.requestContext != null) {
request.requestContext.cosmosResponseDiagnostics = this.cosmosResponseDiagnostics;
}
if (request.requestContext != null) {
request.requestContext.ClearRouteToLocation();
}
if (this.retryContext != null) {
request.requestContext.RouteToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations);
}
this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request);
if (request.requestContext != null) {
request.requestContext.RouteToLocation(this.locationEndpoint);
}
}
private class RetryContext {
public int retryCount;
public boolean retryRequestOnPreferredLocations;
public RetryContext(int retryCount,
boolean retryRequestOnPreferredLocations) {
this.retryCount = retryCount;
this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations;
}
}
} |
Since these are specifically for Walmart, why not use DEBUG and not warn, since warning logs will be difficult to diagnose, as they are a lot. | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints();
if (this.sessionTokenRetryCount > endpoints.size()) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, going to retry on next location", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
} else {
if (this.sessionTokenRetryCount > 1) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, going to retry", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
}
}
} | logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false"); | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints();
if (this.sessionTokenRetryCount > endpoints.size()) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, going to retry on next location", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
} else {
if (this.sessionTokenRetryCount > 1) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, going to retry", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
}
}
} | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointManager globalEndpointManager;
private final boolean enableEndpointDiscovery;
private int failoverRetryCount;
private int sessionTokenRetryCount;
private boolean isReadRequest;
private boolean canUseMultipleWriteLocations;
private URL locationEndpoint;
private RetryContext retryContext;
private CosmosResponseDiagnostics cosmosResponseDiagnostics;
private AtomicInteger cnt = new AtomicInteger(0);
public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager,
boolean enableEndpointDiscovery,
RetryOptions retryOptions) {
this.throttlingRetry = new ResourceThrottleRetryPolicy(
retryOptions.maxRetryAttemptsOnThrottledRequests(),
retryOptions.maxRetryWaitTimeInSeconds());
this.globalEndpointManager = globalEndpointManager;
this.failoverRetryCount = 0;
this.enableEndpointDiscovery = enableEndpointDiscovery;
this.sessionTokenRetryCount = 0;
this.canUseMultipleWriteLocations = false;
this.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics();
}
@Override
public Mono<ShouldRetryResult> shouldRetry(Exception e) {
logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:",
cnt.incrementAndGet(),
isReadRequest,
canUseMultipleWriteLocations,
e);
if (this.locationEndpoint == null) {
logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " +
"probably request creation failed due to invalid options, serialization setting, etc.");
return Mono.just(ShouldRetryResult.error(e));
}
this.retryContext = null;
CosmosClientException clientException = Utils.as(e, CosmosClientException.class);
if (clientException != null && clientException.cosmosResponseDiagnostics() != null) {
this.cosmosResponseDiagnostics = clientException.cosmosResponseDiagnostics();
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN))
{
logger.warn("Endpoint not writable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(false, true);
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) &&
this.isReadRequest)
{
logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(true, false);
}
if (WebExceptionUtility.isNetworkFailure(e)) {
if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) {
logger.warn("Endpoint not reachable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false);
} else {
logger.warn("Endpoint not reachable. Can't retry on write", e);
return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false);
}
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) {
return Mono.just(this.shouldRetryOnSessionNotAvailable());
}
return this.throttlingRetry.shouldRetry(e);
}
private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
Duration retryDelay = Duration.ZERO;
if (!this.isReadRequest) {
logger.debug("Failover happening. retryCount {}", this.failoverRetryCount);
if (this.failoverRetryCount > 1) {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
} else {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay)));
}
private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry()));
}
private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) {
this.failoverRetryCount++;
if (isReadRequest) {
logger.warn("marking the endpoint {} as unavailable for read", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint);
} else {
logger.warn("marking the endpoint {} as unavailable for write", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint);
}
return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh);
}
@Override
public void onBeforeSendRequest(RxDocumentServiceRequest request) {
this.isReadRequest = request.isReadOnlyRequest();
this.canUseMultipleWriteLocations = this.globalEndpointManager.CanUseMultipleWriteLocations(request);
if (request.requestContext != null) {
request.requestContext.cosmosResponseDiagnostics = this.cosmosResponseDiagnostics;
}
if (request.requestContext != null) {
request.requestContext.ClearRouteToLocation();
}
if (this.retryContext != null) {
request.requestContext.RouteToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations);
}
this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request);
if (request.requestContext != null) {
request.requestContext.RouteToLocation(this.locationEndpoint);
}
}
private class RetryContext {
public int retryCount;
public boolean retryRequestOnPreferredLocations;
public RetryContext(int retryCount,
boolean retryRequestOnPreferredLocations) {
this.retryCount = retryCount;
this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations;
}
}
} | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointManager globalEndpointManager;
private final boolean enableEndpointDiscovery;
private int failoverRetryCount;
private int sessionTokenRetryCount;
private boolean isReadRequest;
private boolean canUseMultipleWriteLocations;
private URL locationEndpoint;
private RetryContext retryContext;
private CosmosResponseDiagnostics cosmosResponseDiagnostics;
private AtomicInteger cnt = new AtomicInteger(0);
public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager,
boolean enableEndpointDiscovery,
RetryOptions retryOptions) {
this.throttlingRetry = new ResourceThrottleRetryPolicy(
retryOptions.maxRetryAttemptsOnThrottledRequests(),
retryOptions.maxRetryWaitTimeInSeconds());
this.globalEndpointManager = globalEndpointManager;
this.failoverRetryCount = 0;
this.enableEndpointDiscovery = enableEndpointDiscovery;
this.sessionTokenRetryCount = 0;
this.canUseMultipleWriteLocations = false;
this.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics();
}
@Override
public Mono<ShouldRetryResult> shouldRetry(Exception e) {
logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:",
cnt.incrementAndGet(),
isReadRequest,
canUseMultipleWriteLocations,
e);
if (this.locationEndpoint == null) {
logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " +
"probably request creation failed due to invalid options, serialization setting, etc.");
return Mono.just(ShouldRetryResult.error(e));
}
this.retryContext = null;
CosmosClientException clientException = Utils.as(e, CosmosClientException.class);
if (clientException != null && clientException.cosmosResponseDiagnostics() != null) {
this.cosmosResponseDiagnostics = clientException.cosmosResponseDiagnostics();
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN))
{
logger.warn("Endpoint not writable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(false, true);
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) &&
this.isReadRequest)
{
logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(true, false);
}
if (WebExceptionUtility.isNetworkFailure(e)) {
if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) {
logger.warn("Endpoint not reachable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false);
} else {
logger.warn("Endpoint not reachable. Can't retry on write", e);
return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false);
}
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) {
return Mono.just(this.shouldRetryOnSessionNotAvailable());
}
return this.throttlingRetry.shouldRetry(e);
}
private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
Duration retryDelay = Duration.ZERO;
if (!this.isReadRequest) {
logger.debug("Failover happening. retryCount {}", this.failoverRetryCount);
if (this.failoverRetryCount > 1) {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
} else {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay)));
}
private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry()));
}
private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) {
this.failoverRetryCount++;
if (isReadRequest) {
logger.warn("marking the endpoint {} as unavailable for read", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint);
} else {
logger.warn("marking the endpoint {} as unavailable for write", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint);
}
return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh);
}
@Override
public void onBeforeSendRequest(RxDocumentServiceRequest request) {
this.isReadRequest = request.isReadOnlyRequest();
this.canUseMultipleWriteLocations = this.globalEndpointManager.CanUseMultipleWriteLocations(request);
if (request.requestContext != null) {
request.requestContext.cosmosResponseDiagnostics = this.cosmosResponseDiagnostics;
}
if (request.requestContext != null) {
request.requestContext.ClearRouteToLocation();
}
if (this.retryContext != null) {
request.requestContext.RouteToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations);
}
this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request);
if (request.requestContext != null) {
request.requestContext.RouteToLocation(this.locationEndpoint);
}
}
private class RetryContext {
public int retryCount;
public boolean retryRequestOnPreferredLocations;
public RetryContext(int retryCount,
boolean retryRequestOnPreferredLocations) {
this.retryCount = retryCount;
this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations;
}
}
} |
Same here. | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints();
if (this.sessionTokenRetryCount > endpoints.size()) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, going to retry on next location", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
} else {
if (this.sessionTokenRetryCount > 1) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, going to retry", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
}
}
} | logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount); | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints();
if (this.sessionTokenRetryCount > endpoints.size()) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, going to retry on next location", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
} else {
if (this.sessionTokenRetryCount > 1) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, going to retry", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
}
}
} | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointManager globalEndpointManager;
private final boolean enableEndpointDiscovery;
private int failoverRetryCount;
private int sessionTokenRetryCount;
private boolean isReadRequest;
private boolean canUseMultipleWriteLocations;
private URL locationEndpoint;
private RetryContext retryContext;
private CosmosResponseDiagnostics cosmosResponseDiagnostics;
private AtomicInteger cnt = new AtomicInteger(0);
public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager,
boolean enableEndpointDiscovery,
RetryOptions retryOptions) {
this.throttlingRetry = new ResourceThrottleRetryPolicy(
retryOptions.maxRetryAttemptsOnThrottledRequests(),
retryOptions.maxRetryWaitTimeInSeconds());
this.globalEndpointManager = globalEndpointManager;
this.failoverRetryCount = 0;
this.enableEndpointDiscovery = enableEndpointDiscovery;
this.sessionTokenRetryCount = 0;
this.canUseMultipleWriteLocations = false;
this.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics();
}
@Override
public Mono<ShouldRetryResult> shouldRetry(Exception e) {
logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:",
cnt.incrementAndGet(),
isReadRequest,
canUseMultipleWriteLocations,
e);
if (this.locationEndpoint == null) {
logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " +
"probably request creation failed due to invalid options, serialization setting, etc.");
return Mono.just(ShouldRetryResult.error(e));
}
this.retryContext = null;
CosmosClientException clientException = Utils.as(e, CosmosClientException.class);
if (clientException != null && clientException.cosmosResponseDiagnostics() != null) {
this.cosmosResponseDiagnostics = clientException.cosmosResponseDiagnostics();
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN))
{
logger.warn("Endpoint not writable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(false, true);
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) &&
this.isReadRequest)
{
logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(true, false);
}
if (WebExceptionUtility.isNetworkFailure(e)) {
if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) {
logger.warn("Endpoint not reachable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false);
} else {
logger.warn("Endpoint not reachable. Can't retry on write", e);
return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false);
}
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) {
return Mono.just(this.shouldRetryOnSessionNotAvailable());
}
return this.throttlingRetry.shouldRetry(e);
}
private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
Duration retryDelay = Duration.ZERO;
if (!this.isReadRequest) {
logger.debug("Failover happening. retryCount {}", this.failoverRetryCount);
if (this.failoverRetryCount > 1) {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
} else {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay)));
}
private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry()));
}
private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) {
this.failoverRetryCount++;
if (isReadRequest) {
logger.warn("marking the endpoint {} as unavailable for read", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint);
} else {
logger.warn("marking the endpoint {} as unavailable for write", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint);
}
return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh);
}
@Override
public void onBeforeSendRequest(RxDocumentServiceRequest request) {
this.isReadRequest = request.isReadOnlyRequest();
this.canUseMultipleWriteLocations = this.globalEndpointManager.CanUseMultipleWriteLocations(request);
if (request.requestContext != null) {
request.requestContext.cosmosResponseDiagnostics = this.cosmosResponseDiagnostics;
}
if (request.requestContext != null) {
request.requestContext.ClearRouteToLocation();
}
if (this.retryContext != null) {
request.requestContext.RouteToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations);
}
this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request);
if (request.requestContext != null) {
request.requestContext.RouteToLocation(this.locationEndpoint);
}
}
private class RetryContext {
public int retryCount;
public boolean retryRequestOnPreferredLocations;
public RetryContext(int retryCount,
boolean retryRequestOnPreferredLocations) {
this.retryCount = retryCount;
this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations;
}
}
} | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointManager globalEndpointManager;
private final boolean enableEndpointDiscovery;
private int failoverRetryCount;
private int sessionTokenRetryCount;
private boolean isReadRequest;
private boolean canUseMultipleWriteLocations;
private URL locationEndpoint;
private RetryContext retryContext;
private CosmosResponseDiagnostics cosmosResponseDiagnostics;
private AtomicInteger cnt = new AtomicInteger(0);
public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager,
boolean enableEndpointDiscovery,
RetryOptions retryOptions) {
this.throttlingRetry = new ResourceThrottleRetryPolicy(
retryOptions.maxRetryAttemptsOnThrottledRequests(),
retryOptions.maxRetryWaitTimeInSeconds());
this.globalEndpointManager = globalEndpointManager;
this.failoverRetryCount = 0;
this.enableEndpointDiscovery = enableEndpointDiscovery;
this.sessionTokenRetryCount = 0;
this.canUseMultipleWriteLocations = false;
this.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics();
}
@Override
public Mono<ShouldRetryResult> shouldRetry(Exception e) {
logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:",
cnt.incrementAndGet(),
isReadRequest,
canUseMultipleWriteLocations,
e);
if (this.locationEndpoint == null) {
logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " +
"probably request creation failed due to invalid options, serialization setting, etc.");
return Mono.just(ShouldRetryResult.error(e));
}
this.retryContext = null;
CosmosClientException clientException = Utils.as(e, CosmosClientException.class);
if (clientException != null && clientException.cosmosResponseDiagnostics() != null) {
this.cosmosResponseDiagnostics = clientException.cosmosResponseDiagnostics();
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN))
{
logger.warn("Endpoint not writable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(false, true);
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) &&
this.isReadRequest)
{
logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(true, false);
}
if (WebExceptionUtility.isNetworkFailure(e)) {
if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) {
logger.warn("Endpoint not reachable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false);
} else {
logger.warn("Endpoint not reachable. Can't retry on write", e);
return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false);
}
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) {
return Mono.just(this.shouldRetryOnSessionNotAvailable());
}
return this.throttlingRetry.shouldRetry(e);
}
private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
Duration retryDelay = Duration.ZERO;
if (!this.isReadRequest) {
logger.debug("Failover happening. retryCount {}", this.failoverRetryCount);
if (this.failoverRetryCount > 1) {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
} else {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay)));
}
private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry()));
}
private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) {
this.failoverRetryCount++;
if (isReadRequest) {
logger.warn("marking the endpoint {} as unavailable for read", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint);
} else {
logger.warn("marking the endpoint {} as unavailable for write", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint);
}
return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh);
}
@Override
public void onBeforeSendRequest(RxDocumentServiceRequest request) {
this.isReadRequest = request.isReadOnlyRequest();
this.canUseMultipleWriteLocations = this.globalEndpointManager.CanUseMultipleWriteLocations(request);
if (request.requestContext != null) {
request.requestContext.cosmosResponseDiagnostics = this.cosmosResponseDiagnostics;
}
if (request.requestContext != null) {
request.requestContext.ClearRouteToLocation();
}
if (this.retryContext != null) {
request.requestContext.RouteToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations);
}
this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request);
if (request.requestContext != null) {
request.requestContext.RouteToLocation(this.locationEndpoint);
}
}
private class RetryContext {
public int retryCount;
public boolean retryRequestOnPreferredLocations;
public RetryContext(int retryCount,
boolean retryRequestOnPreferredLocations) {
this.retryCount = retryCount;
this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations;
}
}
} |
Good point @simplynaveen20 | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints();
if (this.sessionTokenRetryCount > endpoints.size()) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, going to retry on next location", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
} else {
if (this.sessionTokenRetryCount > 1) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, going to retry", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
}
}
} | logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount); | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints();
if (this.sessionTokenRetryCount > endpoints.size()) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, going to retry on next location", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
} else {
if (this.sessionTokenRetryCount > 1) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, going to retry", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
}
}
} | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointManager globalEndpointManager;
private final boolean enableEndpointDiscovery;
private int failoverRetryCount;
private int sessionTokenRetryCount;
private boolean isReadRequest;
private boolean canUseMultipleWriteLocations;
private URL locationEndpoint;
private RetryContext retryContext;
private CosmosResponseDiagnostics cosmosResponseDiagnostics;
private AtomicInteger cnt = new AtomicInteger(0);
public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager,
boolean enableEndpointDiscovery,
RetryOptions retryOptions) {
this.throttlingRetry = new ResourceThrottleRetryPolicy(
retryOptions.maxRetryAttemptsOnThrottledRequests(),
retryOptions.maxRetryWaitTimeInSeconds());
this.globalEndpointManager = globalEndpointManager;
this.failoverRetryCount = 0;
this.enableEndpointDiscovery = enableEndpointDiscovery;
this.sessionTokenRetryCount = 0;
this.canUseMultipleWriteLocations = false;
this.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics();
}
@Override
public Mono<ShouldRetryResult> shouldRetry(Exception e) {
logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:",
cnt.incrementAndGet(),
isReadRequest,
canUseMultipleWriteLocations,
e);
if (this.locationEndpoint == null) {
logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " +
"probably request creation failed due to invalid options, serialization setting, etc.");
return Mono.just(ShouldRetryResult.error(e));
}
this.retryContext = null;
CosmosClientException clientException = Utils.as(e, CosmosClientException.class);
if (clientException != null && clientException.cosmosResponseDiagnostics() != null) {
this.cosmosResponseDiagnostics = clientException.cosmosResponseDiagnostics();
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN))
{
logger.warn("Endpoint not writable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(false, true);
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) &&
this.isReadRequest)
{
logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(true, false);
}
if (WebExceptionUtility.isNetworkFailure(e)) {
if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) {
logger.warn("Endpoint not reachable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false);
} else {
logger.warn("Endpoint not reachable. Can't retry on write", e);
return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false);
}
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) {
return Mono.just(this.shouldRetryOnSessionNotAvailable());
}
return this.throttlingRetry.shouldRetry(e);
}
private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
Duration retryDelay = Duration.ZERO;
if (!this.isReadRequest) {
logger.debug("Failover happening. retryCount {}", this.failoverRetryCount);
if (this.failoverRetryCount > 1) {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
} else {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay)));
}
private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry()));
}
private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) {
this.failoverRetryCount++;
if (isReadRequest) {
logger.warn("marking the endpoint {} as unavailable for read", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint);
} else {
logger.warn("marking the endpoint {} as unavailable for write", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint);
}
return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh);
}
@Override
public void onBeforeSendRequest(RxDocumentServiceRequest request) {
this.isReadRequest = request.isReadOnlyRequest();
this.canUseMultipleWriteLocations = this.globalEndpointManager.CanUseMultipleWriteLocations(request);
if (request.requestContext != null) {
request.requestContext.cosmosResponseDiagnostics = this.cosmosResponseDiagnostics;
}
if (request.requestContext != null) {
request.requestContext.ClearRouteToLocation();
}
if (this.retryContext != null) {
request.requestContext.RouteToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations);
}
this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request);
if (request.requestContext != null) {
request.requestContext.RouteToLocation(this.locationEndpoint);
}
}
private class RetryContext {
public int retryCount;
public boolean retryRequestOnPreferredLocations;
public RetryContext(int retryCount,
boolean retryRequestOnPreferredLocations) {
this.retryCount = retryCount;
this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations;
}
}
} | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointManager globalEndpointManager;
private final boolean enableEndpointDiscovery;
private int failoverRetryCount;
private int sessionTokenRetryCount;
private boolean isReadRequest;
private boolean canUseMultipleWriteLocations;
private URL locationEndpoint;
private RetryContext retryContext;
private CosmosResponseDiagnostics cosmosResponseDiagnostics;
private AtomicInteger cnt = new AtomicInteger(0);
public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager,
boolean enableEndpointDiscovery,
RetryOptions retryOptions) {
this.throttlingRetry = new ResourceThrottleRetryPolicy(
retryOptions.maxRetryAttemptsOnThrottledRequests(),
retryOptions.maxRetryWaitTimeInSeconds());
this.globalEndpointManager = globalEndpointManager;
this.failoverRetryCount = 0;
this.enableEndpointDiscovery = enableEndpointDiscovery;
this.sessionTokenRetryCount = 0;
this.canUseMultipleWriteLocations = false;
this.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics();
}
@Override
public Mono<ShouldRetryResult> shouldRetry(Exception e) {
logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:",
cnt.incrementAndGet(),
isReadRequest,
canUseMultipleWriteLocations,
e);
if (this.locationEndpoint == null) {
logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " +
"probably request creation failed due to invalid options, serialization setting, etc.");
return Mono.just(ShouldRetryResult.error(e));
}
this.retryContext = null;
CosmosClientException clientException = Utils.as(e, CosmosClientException.class);
if (clientException != null && clientException.cosmosResponseDiagnostics() != null) {
this.cosmosResponseDiagnostics = clientException.cosmosResponseDiagnostics();
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN))
{
logger.warn("Endpoint not writable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(false, true);
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) &&
this.isReadRequest)
{
logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(true, false);
}
if (WebExceptionUtility.isNetworkFailure(e)) {
if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) {
logger.warn("Endpoint not reachable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false);
} else {
logger.warn("Endpoint not reachable. Can't retry on write", e);
return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false);
}
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) {
return Mono.just(this.shouldRetryOnSessionNotAvailable());
}
return this.throttlingRetry.shouldRetry(e);
}
private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
Duration retryDelay = Duration.ZERO;
if (!this.isReadRequest) {
logger.debug("Failover happening. retryCount {}", this.failoverRetryCount);
if (this.failoverRetryCount > 1) {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
} else {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay)));
}
private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry()));
}
private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) {
this.failoverRetryCount++;
if (isReadRequest) {
logger.warn("marking the endpoint {} as unavailable for read", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint);
} else {
logger.warn("marking the endpoint {} as unavailable for write", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint);
}
return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh);
}
@Override
public void onBeforeSendRequest(RxDocumentServiceRequest request) {
this.isReadRequest = request.isReadOnlyRequest();
this.canUseMultipleWriteLocations = this.globalEndpointManager.CanUseMultipleWriteLocations(request);
if (request.requestContext != null) {
request.requestContext.cosmosResponseDiagnostics = this.cosmosResponseDiagnostics;
}
if (request.requestContext != null) {
request.requestContext.ClearRouteToLocation();
}
if (this.retryContext != null) {
request.requestContext.RouteToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations);
}
this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request);
if (request.requestContext != null) {
request.requestContext.RouteToLocation(this.locationEndpoint);
}
}
private class RetryContext {
public int retryCount;
public boolean retryRequestOnPreferredLocations;
public RetryContext(int retryCount,
boolean retryRequestOnPreferredLocations) {
this.retryCount = retryCount;
this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations;
}
}
} |
Same here - let's use the variable | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints();
if (this.sessionTokenRetryCount > endpoints.size()) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, going to retry on next location", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
} else {
if (this.sessionTokenRetryCount > 1) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, going to retry", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
}
}
} | logger.info("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, going to retry", sessionTokenRetryCount); | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints();
if (this.sessionTokenRetryCount > endpoints.size()) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, going to retry on next location", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
} else {
if (this.sessionTokenRetryCount > 1) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, going to retry", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
}
}
} | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointManager globalEndpointManager;
private final boolean enableEndpointDiscovery;
private int failoverRetryCount;
private int sessionTokenRetryCount;
private boolean isReadRequest;
private boolean canUseMultipleWriteLocations;
private URL locationEndpoint;
private RetryContext retryContext;
private CosmosResponseDiagnostics cosmosResponseDiagnostics;
private AtomicInteger cnt = new AtomicInteger(0);
public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager,
boolean enableEndpointDiscovery,
RetryOptions retryOptions) {
this.throttlingRetry = new ResourceThrottleRetryPolicy(
retryOptions.maxRetryAttemptsOnThrottledRequests(),
retryOptions.maxRetryWaitTimeInSeconds());
this.globalEndpointManager = globalEndpointManager;
this.failoverRetryCount = 0;
this.enableEndpointDiscovery = enableEndpointDiscovery;
this.sessionTokenRetryCount = 0;
this.canUseMultipleWriteLocations = false;
this.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics();
}
@Override
public Mono<ShouldRetryResult> shouldRetry(Exception e) {
logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:",
cnt.incrementAndGet(),
isReadRequest,
canUseMultipleWriteLocations,
e);
if (this.locationEndpoint == null) {
logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " +
"probably request creation failed due to invalid options, serialization setting, etc.");
return Mono.just(ShouldRetryResult.error(e));
}
this.retryContext = null;
CosmosClientException clientException = Utils.as(e, CosmosClientException.class);
if (clientException != null && clientException.cosmosResponseDiagnostics() != null) {
this.cosmosResponseDiagnostics = clientException.cosmosResponseDiagnostics();
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN))
{
logger.warn("Endpoint not writable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(false, true);
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) &&
this.isReadRequest)
{
logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(true, false);
}
if (WebExceptionUtility.isNetworkFailure(e)) {
if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) {
logger.warn("Endpoint not reachable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false);
} else {
logger.warn("Endpoint not reachable. Can't retry on write", e);
return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false);
}
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) {
return Mono.just(this.shouldRetryOnSessionNotAvailable());
}
return this.throttlingRetry.shouldRetry(e);
}
private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
Duration retryDelay = Duration.ZERO;
if (!this.isReadRequest) {
logger.debug("Failover happening. retryCount {}", this.failoverRetryCount);
if (this.failoverRetryCount > 1) {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
} else {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay)));
}
private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry()));
}
private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) {
this.failoverRetryCount++;
if (isReadRequest) {
logger.warn("marking the endpoint {} as unavailable for read", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint);
} else {
logger.warn("marking the endpoint {} as unavailable for write", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint);
}
return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh);
}
@Override
public void onBeforeSendRequest(RxDocumentServiceRequest request) {
this.isReadRequest = request.isReadOnlyRequest();
this.canUseMultipleWriteLocations = this.globalEndpointManager.CanUseMultipleWriteLocations(request);
if (request.requestContext != null) {
request.requestContext.cosmosResponseDiagnostics = this.cosmosResponseDiagnostics;
}
if (request.requestContext != null) {
request.requestContext.ClearRouteToLocation();
}
if (this.retryContext != null) {
request.requestContext.RouteToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations);
}
this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request);
if (request.requestContext != null) {
request.requestContext.RouteToLocation(this.locationEndpoint);
}
}
private class RetryContext {
public int retryCount;
public boolean retryRequestOnPreferredLocations;
public RetryContext(int retryCount,
boolean retryRequestOnPreferredLocations) {
this.retryCount = retryCount;
this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations;
}
}
} | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointManager globalEndpointManager;
private final boolean enableEndpointDiscovery;
private int failoverRetryCount;
private int sessionTokenRetryCount;
private boolean isReadRequest;
private boolean canUseMultipleWriteLocations;
private URL locationEndpoint;
private RetryContext retryContext;
private CosmosResponseDiagnostics cosmosResponseDiagnostics;
private AtomicInteger cnt = new AtomicInteger(0);
public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager,
boolean enableEndpointDiscovery,
RetryOptions retryOptions) {
this.throttlingRetry = new ResourceThrottleRetryPolicy(
retryOptions.maxRetryAttemptsOnThrottledRequests(),
retryOptions.maxRetryWaitTimeInSeconds());
this.globalEndpointManager = globalEndpointManager;
this.failoverRetryCount = 0;
this.enableEndpointDiscovery = enableEndpointDiscovery;
this.sessionTokenRetryCount = 0;
this.canUseMultipleWriteLocations = false;
this.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics();
}
@Override
public Mono<ShouldRetryResult> shouldRetry(Exception e) {
logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:",
cnt.incrementAndGet(),
isReadRequest,
canUseMultipleWriteLocations,
e);
if (this.locationEndpoint == null) {
logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " +
"probably request creation failed due to invalid options, serialization setting, etc.");
return Mono.just(ShouldRetryResult.error(e));
}
this.retryContext = null;
CosmosClientException clientException = Utils.as(e, CosmosClientException.class);
if (clientException != null && clientException.cosmosResponseDiagnostics() != null) {
this.cosmosResponseDiagnostics = clientException.cosmosResponseDiagnostics();
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN))
{
logger.warn("Endpoint not writable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(false, true);
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) &&
this.isReadRequest)
{
logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(true, false);
}
if (WebExceptionUtility.isNetworkFailure(e)) {
if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) {
logger.warn("Endpoint not reachable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false);
} else {
logger.warn("Endpoint not reachable. Can't retry on write", e);
return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false);
}
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) {
return Mono.just(this.shouldRetryOnSessionNotAvailable());
}
return this.throttlingRetry.shouldRetry(e);
}
private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
Duration retryDelay = Duration.ZERO;
if (!this.isReadRequest) {
logger.debug("Failover happening. retryCount {}", this.failoverRetryCount);
if (this.failoverRetryCount > 1) {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
} else {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay)));
}
private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry()));
}
private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) {
this.failoverRetryCount++;
if (isReadRequest) {
logger.warn("marking the endpoint {} as unavailable for read", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint);
} else {
logger.warn("marking the endpoint {} as unavailable for write", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint);
}
return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh);
}
@Override
public void onBeforeSendRequest(RxDocumentServiceRequest request) {
this.isReadRequest = request.isReadOnlyRequest();
this.canUseMultipleWriteLocations = this.globalEndpointManager.CanUseMultipleWriteLocations(request);
if (request.requestContext != null) {
request.requestContext.cosmosResponseDiagnostics = this.cosmosResponseDiagnostics;
}
if (request.requestContext != null) {
request.requestContext.ClearRouteToLocation();
}
if (this.retryContext != null) {
request.requestContext.RouteToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations);
}
this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request);
if (request.requestContext != null) {
request.requestContext.RouteToLocation(this.locationEndpoint);
}
}
private class RetryContext {
public int retryCount;
public boolean retryRequestOnPreferredLocations;
public RetryContext(int retryCount,
boolean retryRequestOnPreferredLocations) {
this.retryCount = retryCount;
this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations;
}
}
} |
DEBUG is not feasible. | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints();
if (this.sessionTokenRetryCount > endpoints.size()) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, going to retry on next location", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
} else {
if (this.sessionTokenRetryCount > 1) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, going to retry", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
}
}
} | logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false"); | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints();
if (this.sessionTokenRetryCount > endpoints.size()) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, going to retry on next location", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
} else {
if (this.sessionTokenRetryCount > 1) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, going to retry", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
}
}
} | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointManager globalEndpointManager;
private final boolean enableEndpointDiscovery;
private int failoverRetryCount;
private int sessionTokenRetryCount;
private boolean isReadRequest;
private boolean canUseMultipleWriteLocations;
private URL locationEndpoint;
private RetryContext retryContext;
private CosmosResponseDiagnostics cosmosResponseDiagnostics;
private AtomicInteger cnt = new AtomicInteger(0);
public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager,
boolean enableEndpointDiscovery,
RetryOptions retryOptions) {
this.throttlingRetry = new ResourceThrottleRetryPolicy(
retryOptions.maxRetryAttemptsOnThrottledRequests(),
retryOptions.maxRetryWaitTimeInSeconds());
this.globalEndpointManager = globalEndpointManager;
this.failoverRetryCount = 0;
this.enableEndpointDiscovery = enableEndpointDiscovery;
this.sessionTokenRetryCount = 0;
this.canUseMultipleWriteLocations = false;
this.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics();
}
@Override
public Mono<ShouldRetryResult> shouldRetry(Exception e) {
logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:",
cnt.incrementAndGet(),
isReadRequest,
canUseMultipleWriteLocations,
e);
if (this.locationEndpoint == null) {
logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " +
"probably request creation failed due to invalid options, serialization setting, etc.");
return Mono.just(ShouldRetryResult.error(e));
}
this.retryContext = null;
CosmosClientException clientException = Utils.as(e, CosmosClientException.class);
if (clientException != null && clientException.cosmosResponseDiagnostics() != null) {
this.cosmosResponseDiagnostics = clientException.cosmosResponseDiagnostics();
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN))
{
logger.warn("Endpoint not writable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(false, true);
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) &&
this.isReadRequest)
{
logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(true, false);
}
if (WebExceptionUtility.isNetworkFailure(e)) {
if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) {
logger.warn("Endpoint not reachable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false);
} else {
logger.warn("Endpoint not reachable. Can't retry on write", e);
return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false);
}
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) {
return Mono.just(this.shouldRetryOnSessionNotAvailable());
}
return this.throttlingRetry.shouldRetry(e);
}
private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
Duration retryDelay = Duration.ZERO;
if (!this.isReadRequest) {
logger.debug("Failover happening. retryCount {}", this.failoverRetryCount);
if (this.failoverRetryCount > 1) {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
} else {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay)));
}
private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry()));
}
private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) {
this.failoverRetryCount++;
if (isReadRequest) {
logger.warn("marking the endpoint {} as unavailable for read", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint);
} else {
logger.warn("marking the endpoint {} as unavailable for write", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint);
}
return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh);
}
@Override
public void onBeforeSendRequest(RxDocumentServiceRequest request) {
this.isReadRequest = request.isReadOnlyRequest();
this.canUseMultipleWriteLocations = this.globalEndpointManager.CanUseMultipleWriteLocations(request);
if (request.requestContext != null) {
request.requestContext.cosmosResponseDiagnostics = this.cosmosResponseDiagnostics;
}
if (request.requestContext != null) {
request.requestContext.ClearRouteToLocation();
}
if (this.retryContext != null) {
request.requestContext.RouteToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations);
}
this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request);
if (request.requestContext != null) {
request.requestContext.RouteToLocation(this.locationEndpoint);
}
}
private class RetryContext {
public int retryCount;
public boolean retryRequestOnPreferredLocations;
public RetryContext(int retryCount,
boolean retryRequestOnPreferredLocations) {
this.retryCount = retryCount;
this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations;
}
}
} | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointManager globalEndpointManager;
private final boolean enableEndpointDiscovery;
private int failoverRetryCount;
private int sessionTokenRetryCount;
private boolean isReadRequest;
private boolean canUseMultipleWriteLocations;
private URL locationEndpoint;
private RetryContext retryContext;
private CosmosResponseDiagnostics cosmosResponseDiagnostics;
private AtomicInteger cnt = new AtomicInteger(0);
public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager,
boolean enableEndpointDiscovery,
RetryOptions retryOptions) {
this.throttlingRetry = new ResourceThrottleRetryPolicy(
retryOptions.maxRetryAttemptsOnThrottledRequests(),
retryOptions.maxRetryWaitTimeInSeconds());
this.globalEndpointManager = globalEndpointManager;
this.failoverRetryCount = 0;
this.enableEndpointDiscovery = enableEndpointDiscovery;
this.sessionTokenRetryCount = 0;
this.canUseMultipleWriteLocations = false;
this.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics();
}
@Override
public Mono<ShouldRetryResult> shouldRetry(Exception e) {
logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:",
cnt.incrementAndGet(),
isReadRequest,
canUseMultipleWriteLocations,
e);
if (this.locationEndpoint == null) {
logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " +
"probably request creation failed due to invalid options, serialization setting, etc.");
return Mono.just(ShouldRetryResult.error(e));
}
this.retryContext = null;
CosmosClientException clientException = Utils.as(e, CosmosClientException.class);
if (clientException != null && clientException.cosmosResponseDiagnostics() != null) {
this.cosmosResponseDiagnostics = clientException.cosmosResponseDiagnostics();
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN))
{
logger.warn("Endpoint not writable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(false, true);
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) &&
this.isReadRequest)
{
logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(true, false);
}
if (WebExceptionUtility.isNetworkFailure(e)) {
if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) {
logger.warn("Endpoint not reachable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false);
} else {
logger.warn("Endpoint not reachable. Can't retry on write", e);
return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false);
}
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) {
return Mono.just(this.shouldRetryOnSessionNotAvailable());
}
return this.throttlingRetry.shouldRetry(e);
}
private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
Duration retryDelay = Duration.ZERO;
if (!this.isReadRequest) {
logger.debug("Failover happening. retryCount {}", this.failoverRetryCount);
if (this.failoverRetryCount > 1) {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
} else {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay)));
}
private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry()));
}
private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) {
this.failoverRetryCount++;
if (isReadRequest) {
logger.warn("marking the endpoint {} as unavailable for read", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint);
} else {
logger.warn("marking the endpoint {} as unavailable for write", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint);
}
return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh);
}
@Override
public void onBeforeSendRequest(RxDocumentServiceRequest request) {
this.isReadRequest = request.isReadOnlyRequest();
this.canUseMultipleWriteLocations = this.globalEndpointManager.CanUseMultipleWriteLocations(request);
if (request.requestContext != null) {
request.requestContext.cosmosResponseDiagnostics = this.cosmosResponseDiagnostics;
}
if (request.requestContext != null) {
request.requestContext.ClearRouteToLocation();
}
if (this.retryContext != null) {
request.requestContext.RouteToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations);
}
this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request);
if (request.requestContext != null) {
request.requestContext.RouteToLocation(this.locationEndpoint);
}
}
private class RetryContext {
public int retryCount;
public boolean retryRequestOnPreferredLocations;
public RetryContext(int retryCount,
boolean retryRequestOnPreferredLocations) {
this.retryCount = retryCount;
this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations;
}
}
} |
DEBUG is not feasible. | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints();
if (this.sessionTokenRetryCount > endpoints.size()) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, going to retry on next location", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
} else {
if (this.sessionTokenRetryCount > 1) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, going to retry", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
}
}
} | logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount); | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints();
if (this.sessionTokenRetryCount > endpoints.size()) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, going to retry on next location", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
} else {
if (this.sessionTokenRetryCount > 1) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, going to retry", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
}
}
} | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointManager globalEndpointManager;
private final boolean enableEndpointDiscovery;
private int failoverRetryCount;
private int sessionTokenRetryCount;
private boolean isReadRequest;
private boolean canUseMultipleWriteLocations;
private URL locationEndpoint;
private RetryContext retryContext;
private CosmosResponseDiagnostics cosmosResponseDiagnostics;
private AtomicInteger cnt = new AtomicInteger(0);
public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager,
boolean enableEndpointDiscovery,
RetryOptions retryOptions) {
this.throttlingRetry = new ResourceThrottleRetryPolicy(
retryOptions.maxRetryAttemptsOnThrottledRequests(),
retryOptions.maxRetryWaitTimeInSeconds());
this.globalEndpointManager = globalEndpointManager;
this.failoverRetryCount = 0;
this.enableEndpointDiscovery = enableEndpointDiscovery;
this.sessionTokenRetryCount = 0;
this.canUseMultipleWriteLocations = false;
this.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics();
}
@Override
public Mono<ShouldRetryResult> shouldRetry(Exception e) {
logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:",
cnt.incrementAndGet(),
isReadRequest,
canUseMultipleWriteLocations,
e);
if (this.locationEndpoint == null) {
logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " +
"probably request creation failed due to invalid options, serialization setting, etc.");
return Mono.just(ShouldRetryResult.error(e));
}
this.retryContext = null;
CosmosClientException clientException = Utils.as(e, CosmosClientException.class);
if (clientException != null && clientException.cosmosResponseDiagnostics() != null) {
this.cosmosResponseDiagnostics = clientException.cosmosResponseDiagnostics();
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN))
{
logger.warn("Endpoint not writable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(false, true);
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) &&
this.isReadRequest)
{
logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(true, false);
}
if (WebExceptionUtility.isNetworkFailure(e)) {
if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) {
logger.warn("Endpoint not reachable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false);
} else {
logger.warn("Endpoint not reachable. Can't retry on write", e);
return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false);
}
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) {
return Mono.just(this.shouldRetryOnSessionNotAvailable());
}
return this.throttlingRetry.shouldRetry(e);
}
private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
Duration retryDelay = Duration.ZERO;
if (!this.isReadRequest) {
logger.debug("Failover happening. retryCount {}", this.failoverRetryCount);
if (this.failoverRetryCount > 1) {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
} else {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay)));
}
private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry()));
}
private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) {
this.failoverRetryCount++;
if (isReadRequest) {
logger.warn("marking the endpoint {} as unavailable for read", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint);
} else {
logger.warn("marking the endpoint {} as unavailable for write", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint);
}
return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh);
}
@Override
public void onBeforeSendRequest(RxDocumentServiceRequest request) {
this.isReadRequest = request.isReadOnlyRequest();
this.canUseMultipleWriteLocations = this.globalEndpointManager.CanUseMultipleWriteLocations(request);
if (request.requestContext != null) {
request.requestContext.cosmosResponseDiagnostics = this.cosmosResponseDiagnostics;
}
if (request.requestContext != null) {
request.requestContext.ClearRouteToLocation();
}
if (this.retryContext != null) {
request.requestContext.RouteToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations);
}
this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request);
if (request.requestContext != null) {
request.requestContext.RouteToLocation(this.locationEndpoint);
}
}
private class RetryContext {
public int retryCount;
public boolean retryRequestOnPreferredLocations;
public RetryContext(int retryCount,
boolean retryRequestOnPreferredLocations) {
this.retryCount = retryCount;
this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations;
}
}
} | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointManager globalEndpointManager;
private final boolean enableEndpointDiscovery;
private int failoverRetryCount;
private int sessionTokenRetryCount;
private boolean isReadRequest;
private boolean canUseMultipleWriteLocations;
private URL locationEndpoint;
private RetryContext retryContext;
private CosmosResponseDiagnostics cosmosResponseDiagnostics;
private AtomicInteger cnt = new AtomicInteger(0);
public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager,
boolean enableEndpointDiscovery,
RetryOptions retryOptions) {
this.throttlingRetry = new ResourceThrottleRetryPolicy(
retryOptions.maxRetryAttemptsOnThrottledRequests(),
retryOptions.maxRetryWaitTimeInSeconds());
this.globalEndpointManager = globalEndpointManager;
this.failoverRetryCount = 0;
this.enableEndpointDiscovery = enableEndpointDiscovery;
this.sessionTokenRetryCount = 0;
this.canUseMultipleWriteLocations = false;
this.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics();
}
@Override
public Mono<ShouldRetryResult> shouldRetry(Exception e) {
logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:",
cnt.incrementAndGet(),
isReadRequest,
canUseMultipleWriteLocations,
e);
if (this.locationEndpoint == null) {
logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " +
"probably request creation failed due to invalid options, serialization setting, etc.");
return Mono.just(ShouldRetryResult.error(e));
}
this.retryContext = null;
CosmosClientException clientException = Utils.as(e, CosmosClientException.class);
if (clientException != null && clientException.cosmosResponseDiagnostics() != null) {
this.cosmosResponseDiagnostics = clientException.cosmosResponseDiagnostics();
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN))
{
logger.warn("Endpoint not writable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(false, true);
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) &&
this.isReadRequest)
{
logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(true, false);
}
if (WebExceptionUtility.isNetworkFailure(e)) {
if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) {
logger.warn("Endpoint not reachable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false);
} else {
logger.warn("Endpoint not reachable. Can't retry on write", e);
return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false);
}
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) {
return Mono.just(this.shouldRetryOnSessionNotAvailable());
}
return this.throttlingRetry.shouldRetry(e);
}
private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
Duration retryDelay = Duration.ZERO;
if (!this.isReadRequest) {
logger.debug("Failover happening. retryCount {}", this.failoverRetryCount);
if (this.failoverRetryCount > 1) {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
} else {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay)));
}
private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry()));
}
private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) {
this.failoverRetryCount++;
if (isReadRequest) {
logger.warn("marking the endpoint {} as unavailable for read", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint);
} else {
logger.warn("marking the endpoint {} as unavailable for write", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint);
}
return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh);
}
@Override
public void onBeforeSendRequest(RxDocumentServiceRequest request) {
this.isReadRequest = request.isReadOnlyRequest();
this.canUseMultipleWriteLocations = this.globalEndpointManager.CanUseMultipleWriteLocations(request);
if (request.requestContext != null) {
request.requestContext.cosmosResponseDiagnostics = this.cosmosResponseDiagnostics;
}
if (request.requestContext != null) {
request.requestContext.ClearRouteToLocation();
}
if (this.retryContext != null) {
request.requestContext.RouteToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations);
}
this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request);
if (request.requestContext != null) {
request.requestContext.RouteToLocation(this.locationEndpoint);
}
}
private class RetryContext {
public int retryCount;
public boolean retryRequestOnPreferredLocations;
public RetryContext(int retryCount,
boolean retryRequestOnPreferredLocations) {
this.retryCount = retryCount;
this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations;
}
}
} |
intellj gives a recommendation in general to use ```java if (flag) { func(true) } ``` instead of ```java if (flag) { func(flag) } ``` that's why I am not using a variable here. | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints();
if (this.sessionTokenRetryCount > endpoints.size()) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, going to retry on next location", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
} else {
if (this.sessionTokenRetryCount > 1) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, going to retry", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
}
}
} | logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount); | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints();
if (this.sessionTokenRetryCount > endpoints.size()) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, going to retry on next location", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
} else {
if (this.sessionTokenRetryCount > 1) {
logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount);
return ShouldRetryResult.noRetry();
} else {
logger.info("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, going to retry", sessionTokenRetryCount);
this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false);
return ShouldRetryResult.retryAfter(Duration.ZERO);
}
}
}
} | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointManager globalEndpointManager;
private final boolean enableEndpointDiscovery;
private int failoverRetryCount;
private int sessionTokenRetryCount;
private boolean isReadRequest;
private boolean canUseMultipleWriteLocations;
private URL locationEndpoint;
private RetryContext retryContext;
private CosmosResponseDiagnostics cosmosResponseDiagnostics;
private AtomicInteger cnt = new AtomicInteger(0);
public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager,
boolean enableEndpointDiscovery,
RetryOptions retryOptions) {
this.throttlingRetry = new ResourceThrottleRetryPolicy(
retryOptions.maxRetryAttemptsOnThrottledRequests(),
retryOptions.maxRetryWaitTimeInSeconds());
this.globalEndpointManager = globalEndpointManager;
this.failoverRetryCount = 0;
this.enableEndpointDiscovery = enableEndpointDiscovery;
this.sessionTokenRetryCount = 0;
this.canUseMultipleWriteLocations = false;
this.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics();
}
@Override
public Mono<ShouldRetryResult> shouldRetry(Exception e) {
logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:",
cnt.incrementAndGet(),
isReadRequest,
canUseMultipleWriteLocations,
e);
if (this.locationEndpoint == null) {
logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " +
"probably request creation failed due to invalid options, serialization setting, etc.");
return Mono.just(ShouldRetryResult.error(e));
}
this.retryContext = null;
CosmosClientException clientException = Utils.as(e, CosmosClientException.class);
if (clientException != null && clientException.cosmosResponseDiagnostics() != null) {
this.cosmosResponseDiagnostics = clientException.cosmosResponseDiagnostics();
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN))
{
logger.warn("Endpoint not writable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(false, true);
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) &&
this.isReadRequest)
{
logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(true, false);
}
if (WebExceptionUtility.isNetworkFailure(e)) {
if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) {
logger.warn("Endpoint not reachable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false);
} else {
logger.warn("Endpoint not reachable. Can't retry on write", e);
return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false);
}
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) {
return Mono.just(this.shouldRetryOnSessionNotAvailable());
}
return this.throttlingRetry.shouldRetry(e);
}
private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
Duration retryDelay = Duration.ZERO;
if (!this.isReadRequest) {
logger.debug("Failover happening. retryCount {}", this.failoverRetryCount);
if (this.failoverRetryCount > 1) {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
} else {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay)));
}
private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry()));
}
private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) {
this.failoverRetryCount++;
if (isReadRequest) {
logger.warn("marking the endpoint {} as unavailable for read", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint);
} else {
logger.warn("marking the endpoint {} as unavailable for write", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint);
}
return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh);
}
@Override
public void onBeforeSendRequest(RxDocumentServiceRequest request) {
this.isReadRequest = request.isReadOnlyRequest();
this.canUseMultipleWriteLocations = this.globalEndpointManager.CanUseMultipleWriteLocations(request);
if (request.requestContext != null) {
request.requestContext.cosmosResponseDiagnostics = this.cosmosResponseDiagnostics;
}
if (request.requestContext != null) {
request.requestContext.ClearRouteToLocation();
}
if (this.retryContext != null) {
request.requestContext.RouteToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations);
}
this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request);
if (request.requestContext != null) {
request.requestContext.RouteToLocation(this.locationEndpoint);
}
}
private class RetryContext {
public int retryCount;
public boolean retryRequestOnPreferredLocations;
public RetryContext(int retryCount,
boolean retryRequestOnPreferredLocations) {
this.retryCount = retryCount;
this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations;
}
}
} | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointManager globalEndpointManager;
private final boolean enableEndpointDiscovery;
private int failoverRetryCount;
private int sessionTokenRetryCount;
private boolean isReadRequest;
private boolean canUseMultipleWriteLocations;
private URL locationEndpoint;
private RetryContext retryContext;
private CosmosResponseDiagnostics cosmosResponseDiagnostics;
private AtomicInteger cnt = new AtomicInteger(0);
public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager,
boolean enableEndpointDiscovery,
RetryOptions retryOptions) {
this.throttlingRetry = new ResourceThrottleRetryPolicy(
retryOptions.maxRetryAttemptsOnThrottledRequests(),
retryOptions.maxRetryWaitTimeInSeconds());
this.globalEndpointManager = globalEndpointManager;
this.failoverRetryCount = 0;
this.enableEndpointDiscovery = enableEndpointDiscovery;
this.sessionTokenRetryCount = 0;
this.canUseMultipleWriteLocations = false;
this.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics();
}
@Override
public Mono<ShouldRetryResult> shouldRetry(Exception e) {
logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:",
cnt.incrementAndGet(),
isReadRequest,
canUseMultipleWriteLocations,
e);
if (this.locationEndpoint == null) {
logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " +
"probably request creation failed due to invalid options, serialization setting, etc.");
return Mono.just(ShouldRetryResult.error(e));
}
this.retryContext = null;
CosmosClientException clientException = Utils.as(e, CosmosClientException.class);
if (clientException != null && clientException.cosmosResponseDiagnostics() != null) {
this.cosmosResponseDiagnostics = clientException.cosmosResponseDiagnostics();
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN))
{
logger.warn("Endpoint not writable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(false, true);
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) &&
this.isReadRequest)
{
logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(true, false);
}
if (WebExceptionUtility.isNetworkFailure(e)) {
if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) {
logger.warn("Endpoint not reachable. Will refresh cache and retry. ", e);
return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false);
} else {
logger.warn("Endpoint not reachable. Can't retry on write", e);
return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false);
}
}
if (clientException != null &&
Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) &&
Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) {
return Mono.just(this.shouldRetryOnSessionNotAvailable());
}
return this.throttlingRetry.shouldRetry(e);
}
private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
Duration retryDelay = Duration.ZERO;
if (!this.isReadRequest) {
logger.debug("Failover happening. retryCount {}", this.failoverRetryCount);
if (this.failoverRetryCount > 1) {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
} else {
retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS);
}
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay)));
}
private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) {
if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) {
logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount);
return Mono.just(ShouldRetryResult.noRetry());
}
Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh);
return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry()));
}
private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) {
this.failoverRetryCount++;
if (isReadRequest) {
logger.warn("marking the endpoint {} as unavailable for read", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint);
} else {
logger.warn("marking the endpoint {} as unavailable for write", this.locationEndpoint);
this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint);
}
return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh);
}
@Override
public void onBeforeSendRequest(RxDocumentServiceRequest request) {
this.isReadRequest = request.isReadOnlyRequest();
this.canUseMultipleWriteLocations = this.globalEndpointManager.CanUseMultipleWriteLocations(request);
if (request.requestContext != null) {
request.requestContext.cosmosResponseDiagnostics = this.cosmosResponseDiagnostics;
}
if (request.requestContext != null) {
request.requestContext.ClearRouteToLocation();
}
if (this.retryContext != null) {
request.requestContext.RouteToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations);
}
this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request);
if (request.requestContext != null) {
request.requestContext.RouteToLocation(this.locationEndpoint);
}
}
private class RetryContext {
public int retryCount;
public boolean retryRequestOnPreferredLocations;
public RetryContext(int retryCount,
boolean retryRequestOnPreferredLocations) {
this.retryCount = retryCount;
this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations;
}
}
} |
We only use record policy in RECORD mode. Should exclude LIVE test mode here as well. Same as below | HttpPipeline getHttpPipeline(HttpClient httpClient, CryptographyServiceVersion 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);
RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16));
policies.add(new RetryPolicy(strategy));
if (credential != null) {
policies.add(new BearerTokenAuthenticationPolicy(credential, CryptographyAsyncClient.KEY_VAULT_SCOPE));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)));
if (!interceptorManager.isPlaybackMode()) {
policies.add(interceptorManager.getRecordPolicy());
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient)
.build();
} | if (!interceptorManager.isPlaybackMode()) { | HttpPipeline getHttpPipeline(HttpClient httpClient, CryptographyServiceVersion 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);
RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16));
policies.add(new RetryPolicy(strategy));
if (credential != null) {
policies.add(new BearerTokenAuthenticationPolicy(credential, CryptographyAsyncClient.KEY_VAULT_SCOPE));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)));
if (getTestMode() == TestMode.RECORD) {
policies.add(interceptorManager.getRecordPolicy());
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient)
.build();
} | class KeyEncryptionKeyClientTestBase extends TestBase {
private static final String SDK_NAME = "client_name";
private static final String SDK_VERSION = "client_version";
@Override
protected String getTestName() {
return "";
}
void beforeTestSetup() {
}
@Test
public abstract void wrapUnwrapSymmetricAK128(HttpClient httpClient, CryptographyServiceVersion serviceVersion);
@Test
public abstract void wrapUnwrapSymmetricAK192(HttpClient httpClient, CryptographyServiceVersion serviceVersion);
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);
}
}
/**
* 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();
}
}
} | class KeyEncryptionKeyClientTestBase extends TestBase {
private static final String SDK_NAME = "client_name";
private static final String SDK_VERSION = "client_version";
@Override
protected String getTestName() {
return "";
}
void beforeTestSetup() {
}
@Test
public abstract void wrapUnwrapSymmetricAK128(HttpClient httpClient, CryptographyServiceVersion serviceVersion);
@Test
public abstract void wrapUnwrapSymmetricAK192(HttpClient httpClient, CryptographyServiceVersion serviceVersion);
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);
}
}
/**
* 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();
}
}
} |
@sima-zhu We probably should modify the other `TestBase` classes in our repository if that's the case. They currently use a record policy when **not** in playback mode. | HttpPipeline getHttpPipeline(HttpClient httpClient, CryptographyServiceVersion 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);
RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16));
policies.add(new RetryPolicy(strategy));
if (credential != null) {
policies.add(new BearerTokenAuthenticationPolicy(credential, CryptographyAsyncClient.KEY_VAULT_SCOPE));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)));
if (!interceptorManager.isPlaybackMode()) {
policies.add(interceptorManager.getRecordPolicy());
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient)
.build();
} | if (!interceptorManager.isPlaybackMode()) { | HttpPipeline getHttpPipeline(HttpClient httpClient, CryptographyServiceVersion 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);
RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16));
policies.add(new RetryPolicy(strategy));
if (credential != null) {
policies.add(new BearerTokenAuthenticationPolicy(credential, CryptographyAsyncClient.KEY_VAULT_SCOPE));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)));
if (getTestMode() == TestMode.RECORD) {
policies.add(interceptorManager.getRecordPolicy());
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient)
.build();
} | class KeyEncryptionKeyClientTestBase extends TestBase {
private static final String SDK_NAME = "client_name";
private static final String SDK_VERSION = "client_version";
@Override
protected String getTestName() {
return "";
}
void beforeTestSetup() {
}
@Test
public abstract void wrapUnwrapSymmetricAK128(HttpClient httpClient, CryptographyServiceVersion serviceVersion);
@Test
public abstract void wrapUnwrapSymmetricAK192(HttpClient httpClient, CryptographyServiceVersion serviceVersion);
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);
}
}
/**
* 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();
}
}
} | class KeyEncryptionKeyClientTestBase extends TestBase {
private static final String SDK_NAME = "client_name";
private static final String SDK_VERSION = "client_version";
@Override
protected String getTestName() {
return "";
}
void beforeTestSetup() {
}
@Test
public abstract void wrapUnwrapSymmetricAK128(HttpClient httpClient, CryptographyServiceVersion serviceVersion);
@Test
public abstract void wrapUnwrapSymmetricAK192(HttpClient httpClient, CryptographyServiceVersion serviceVersion);
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);
}
}
/**
* 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();
}
}
} |
Could you point out the place mentioned use RecordPolicy when not playback. We introduce LIVE mode slightly later than the other modes, so it might not up-to-date. | HttpPipeline getHttpPipeline(HttpClient httpClient, CryptographyServiceVersion 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);
RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16));
policies.add(new RetryPolicy(strategy));
if (credential != null) {
policies.add(new BearerTokenAuthenticationPolicy(credential, CryptographyAsyncClient.KEY_VAULT_SCOPE));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)));
if (!interceptorManager.isPlaybackMode()) {
policies.add(interceptorManager.getRecordPolicy());
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient)
.build();
} | if (!interceptorManager.isPlaybackMode()) { | HttpPipeline getHttpPipeline(HttpClient httpClient, CryptographyServiceVersion 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);
RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16));
policies.add(new RetryPolicy(strategy));
if (credential != null) {
policies.add(new BearerTokenAuthenticationPolicy(credential, CryptographyAsyncClient.KEY_VAULT_SCOPE));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)));
if (getTestMode() == TestMode.RECORD) {
policies.add(interceptorManager.getRecordPolicy());
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient)
.build();
} | class KeyEncryptionKeyClientTestBase extends TestBase {
private static final String SDK_NAME = "client_name";
private static final String SDK_VERSION = "client_version";
@Override
protected String getTestName() {
return "";
}
void beforeTestSetup() {
}
@Test
public abstract void wrapUnwrapSymmetricAK128(HttpClient httpClient, CryptographyServiceVersion serviceVersion);
@Test
public abstract void wrapUnwrapSymmetricAK192(HttpClient httpClient, CryptographyServiceVersion serviceVersion);
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);
}
}
/**
* 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();
}
}
} | class KeyEncryptionKeyClientTestBase extends TestBase {
private static final String SDK_NAME = "client_name";
private static final String SDK_VERSION = "client_version";
@Override
protected String getTestName() {
return "";
}
void beforeTestSetup() {
}
@Test
public abstract void wrapUnwrapSymmetricAK128(HttpClient httpClient, CryptographyServiceVersion serviceVersion);
@Test
public abstract void wrapUnwrapSymmetricAK192(HttpClient httpClient, CryptographyServiceVersion serviceVersion);
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);
}
}
/**
* 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();
}
}
} |
Besides the two classes included in this PR, in KeyVault you can find this in the following classes: - [CertificateClientTestBase](https://github.com/Azure/azure-sdk-for-java/blob/2e2b719ddd9106c0b4a7c046a5ac8513612ff0b1/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/CertificateClientTestBase.java#L106) - [CryptographyClientTestBase](https://github.com/Azure/azure-sdk-for-java/blob/2e2b719ddd9106c0b4a7c046a5ac8513612ff0b1/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientTestBase.java#L83) - [KeyClientTestBase](https://github.com/Azure/azure-sdk-for-java/blob/2e2b719ddd9106c0b4a7c046a5ac8513612ff0b1/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTestBase.java#L92) | HttpPipeline getHttpPipeline(HttpClient httpClient, CryptographyServiceVersion 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);
RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16));
policies.add(new RetryPolicy(strategy));
if (credential != null) {
policies.add(new BearerTokenAuthenticationPolicy(credential, CryptographyAsyncClient.KEY_VAULT_SCOPE));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)));
if (!interceptorManager.isPlaybackMode()) {
policies.add(interceptorManager.getRecordPolicy());
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient)
.build();
} | if (!interceptorManager.isPlaybackMode()) { | HttpPipeline getHttpPipeline(HttpClient httpClient, CryptographyServiceVersion 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);
RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16));
policies.add(new RetryPolicy(strategy));
if (credential != null) {
policies.add(new BearerTokenAuthenticationPolicy(credential, CryptographyAsyncClient.KEY_VAULT_SCOPE));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)));
if (getTestMode() == TestMode.RECORD) {
policies.add(interceptorManager.getRecordPolicy());
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient)
.build();
} | class KeyEncryptionKeyClientTestBase extends TestBase {
private static final String SDK_NAME = "client_name";
private static final String SDK_VERSION = "client_version";
@Override
protected String getTestName() {
return "";
}
void beforeTestSetup() {
}
@Test
public abstract void wrapUnwrapSymmetricAK128(HttpClient httpClient, CryptographyServiceVersion serviceVersion);
@Test
public abstract void wrapUnwrapSymmetricAK192(HttpClient httpClient, CryptographyServiceVersion serviceVersion);
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);
}
}
/**
* 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();
}
}
} | class KeyEncryptionKeyClientTestBase extends TestBase {
private static final String SDK_NAME = "client_name";
private static final String SDK_VERSION = "client_version";
@Override
protected String getTestName() {
return "";
}
void beforeTestSetup() {
}
@Test
public abstract void wrapUnwrapSymmetricAK128(HttpClient httpClient, CryptographyServiceVersion serviceVersion);
@Test
public abstract void wrapUnwrapSymmetricAK192(HttpClient httpClient, CryptographyServiceVersion serviceVersion);
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);
}
}
/**
* 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();
}
}
} |
Add some tests where the property name also contains `get` and `set`. | public void testPropertyNameOnMethodNameWithoutGetSet() throws NoSuchMethodException {
class LocalHotel {
String hotelName;
public String hotelName1() {
return hotelName;
}
public void hotelName2(String hotelName) {
this.hotelName = hotelName;
}
}
Method getterM = LocalHotel.class.getDeclaredMethod("hotelName1");
assertEquals("hotelName1", serializer.convertMemberName(getterM));
Method setterM = LocalHotel.class.getDeclaredMethod("hotelName2", String.class);
assertEquals("hotelName2", serializer.convertMemberName(setterM));
} | Method getterM = LocalHotel.class.getDeclaredMethod("hotelName1"); | public void testPropertyNameOnMethodNameWithoutGetSet() throws NoSuchMethodException {
class LocalHotel {
String hotelName;
public String hotelName1() {
return hotelName;
}
public void hotelName2(String hotelName) {
this.hotelName = hotelName;
}
}
Method getterM = LocalHotel.class.getDeclaredMethod("hotelName1");
assertNull(serializer.convertMemberName(getterM));
Method setterM = LocalHotel.class.getDeclaredMethod("hotelName2", String.class);
assertNull(serializer.convertMemberName(setterM));
} | class LocalHotel {
String hotelName;
public String getHotelName() {
return hotelName;
}
public void setHotelName(String hotelName) {
this.hotelName = hotelName;
}
} | class LocalHotel {
String hotelName;
boolean flag;
public String getHotelName() {
return hotelName;
}
public void setHotelName(String hotelName) {
this.hotelName = hotelName;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
} |
More test coverage now | public void testPropertyNameOnMethodNameWithoutGetSet() throws NoSuchMethodException {
class LocalHotel {
String hotelName;
public String hotelName1() {
return hotelName;
}
public void hotelName2(String hotelName) {
this.hotelName = hotelName;
}
}
Method getterM = LocalHotel.class.getDeclaredMethod("hotelName1");
assertEquals("hotelName1", serializer.convertMemberName(getterM));
Method setterM = LocalHotel.class.getDeclaredMethod("hotelName2", String.class);
assertEquals("hotelName2", serializer.convertMemberName(setterM));
} | Method getterM = LocalHotel.class.getDeclaredMethod("hotelName1"); | public void testPropertyNameOnMethodNameWithoutGetSet() throws NoSuchMethodException {
class LocalHotel {
String hotelName;
public String hotelName1() {
return hotelName;
}
public void hotelName2(String hotelName) {
this.hotelName = hotelName;
}
}
Method getterM = LocalHotel.class.getDeclaredMethod("hotelName1");
assertNull(serializer.convertMemberName(getterM));
Method setterM = LocalHotel.class.getDeclaredMethod("hotelName2", String.class);
assertNull(serializer.convertMemberName(setterM));
} | class LocalHotel {
String hotelName;
public String getHotelName() {
return hotelName;
}
public void setHotelName(String hotelName) {
this.hotelName = hotelName;
}
} | class LocalHotel {
String hotelName;
boolean flag;
public String getHotelName() {
return hotelName;
}
public void setHotelName(String hotelName) {
this.hotelName = hotelName;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
} |
is this just cleanup? or what is the motivation for these changes | static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3);
final List<DetectLanguageResult> detectLanguageResultList = Arrays.asList(
new DetectLanguageResult("0", new TextDocumentStatistics(26, 1), null, getDetectedLanguageEnglish()),
new DetectLanguageResult("1", new TextDocumentStatistics(40, 1), null, getDetectedLanguageSpanish()),
new DetectLanguageResult("2", new TextDocumentStatistics(6, 1), null, getUnknownDetectedLanguage()));
return new DetectLanguageResultCollection(detectLanguageResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
} | final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3); | static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3);
final List<DetectLanguageResult> detectLanguageResultList = Arrays.asList(
new DetectLanguageResult("0", new TextDocumentStatistics(26, 1), null, getDetectedLanguageEnglish()),
new DetectLanguageResult("1", new TextDocumentStatistics(40, 1), null, getDetectedLanguageSpanish()),
new DetectLanguageResult("2", new TextDocumentStatistics(6, 1), null, getUnknownDetectedLanguage()));
return new DetectLanguageResultCollection(detectLanguageResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
} | class TestUtils {
private static final String DEFAULT_MODEL_VERSION = "2019-10-01";
static final String INVALID_URL = "htttttttps:
static final String VALID_HTTPS_LOCALHOST = "https:
static final String FAKE_API_KEY = "1234567890";
static final String AZURE_TEXT_ANALYTICS_API_KEY = "AZURE_TEXT_ANALYTICS_API_KEY";
static final List<String> SENTIMENT_INPUTS = Arrays.asList("The hotel was dark and unclean. The restaurant had amazing gnocchi.",
"The restaurant had amazing gnocchi. The hotel was dark and unclean.");
static final List<String> CATEGORIZED_ENTITY_INPUTS = Arrays.asList(
"I had a wonderful trip to Seattle last week.", "I work at Microsoft.");
static final List<String> LINKED_ENTITY_INPUTS = Arrays.asList(
"I had a wonderful trip to Seattle last week.",
"I work at Microsoft.");
static final List<String> KEY_PHRASE_INPUTS = Arrays.asList(
"Hello world. This is some input text that I love.",
"Bonjour tout le monde");
static final String TOO_LONG_INPUT = "Thisisaveryveryverylongtextwhichgoesonforalongtimeandwhichalmostdoesn'tseemtostopatanygivenpointintime.ThereasonforthistestistotryandseewhathappenswhenwesubmitaveryveryverylongtexttoLanguage.Thisshouldworkjustfinebutjustincaseitisalwaysgoodtohaveatestcase.ThisallowsustotestwhathappensifitisnotOK.Ofcourseitisgoingtobeokbutthenagainitisalsobettertobesure!";
static final List<String> KEY_PHRASE_FRENCH_INPUTS = Arrays.asList(
"Bonjour tout le monde.",
"Je m'appelle Mondly.");
static final List<String> DETECT_LANGUAGE_INPUTS = Arrays.asList(
"This is written in English", "Este es un documento escrito en Español.", "~@!~:)");
static final List<String> SPANISH_SAME_AS_ENGLISH_INPUTS = Arrays.asList("personal", "social");
static final DetectedLanguage DETECTED_LANGUAGE_SPANISH = new DetectedLanguage("Spanish", "es", 1.0, null);
static final DetectedLanguage DETECTED_LANGUAGE_ENGLISH = new DetectedLanguage("English", "en", 1.0, null);
static final List<DetectedLanguage> DETECT_SPANISH_LANGUAGE_RESULTS = Arrays.asList(
DETECTED_LANGUAGE_SPANISH, DETECTED_LANGUAGE_SPANISH);
static final List<DetectedLanguage> DETECT_ENGLISH_LANGUAGE_RESULTS = Arrays.asList(
DETECTED_LANGUAGE_ENGLISH, DETECTED_LANGUAGE_ENGLISH);
static final HttpResponseException HTTP_RESPONSE_EXCEPTION_CLASS = new HttpResponseException("", null);
static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]";
private static final String AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS =
"AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS";
static List<DetectLanguageInput> getDetectLanguageInputs() {
return Arrays.asList(
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"),
new DetectLanguageInput("1", DETECT_LANGUAGE_INPUTS.get(1), "US"),
new DetectLanguageInput("2", DETECT_LANGUAGE_INPUTS.get(2), "US")
);
}
static List<DetectLanguageInput> getDuplicateIdDetectLanguageInputs() {
return Arrays.asList(
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"),
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US")
);
}
static List<TextDocumentInput> getDuplicateTextDocumentInputs() {
return Arrays.asList(
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)),
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)),
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0))
);
}
static List<TextDocumentInput> getWarningsTextDocumentInputs() {
return Arrays.asList(
new TextDocumentInput("0", TOO_LONG_INPUT),
new TextDocumentInput("1", CATEGORIZED_ENTITY_INPUTS.get(1))
);
}
static List<TextDocumentInput> getTextDocumentInputs(List<String> inputs) {
return IntStream.range(0, inputs.size())
.mapToObj(index ->
new TextDocumentInput(String.valueOf(index), inputs.get(index)))
.collect(Collectors.toList());
}
/**
* Helper method to get the expected Batch Detected Languages
*
* @return A {@link DetectLanguageResultCollection}.
*/
static DetectedLanguage getDetectedLanguageEnglish() {
return new DetectedLanguage("English", "en", 0.0, null);
}
static DetectedLanguage getDetectedLanguageSpanish() {
return new DetectedLanguage("Spanish", "es", 0.0, null);
}
static DetectedLanguage getUnknownDetectedLanguage() {
return new DetectedLanguage("(Unknown)", "(Unknown)", 0.0, null);
}
/**
* Helper method to get the expected Batch Categorized Entities
*
* @return A {@link RecognizeEntitiesResultCollection}.
*/
static RecognizeEntitiesResultCollection getExpectedBatchCategorizedEntities() {
return new RecognizeEntitiesResultCollection(
Arrays.asList(getExpectedBatchCategorizedEntities1(), getExpectedBatchCategorizedEntities2()),
DEFAULT_MODEL_VERSION,
new TextDocumentBatchStatistics(2, 2, 0, 2));
}
/**
* Helper method to get the expected Categorized Entities List 1
*/
static List<CategorizedEntity> getCategorizedEntitiesList1() {
CategorizedEntity categorizedEntity1 = new CategorizedEntity("trip", EntityCategory.EVENT, null, 18, 4, 0.0);
CategorizedEntity categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 26, 7, 0.0);
CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 34, 9, 0.0);
return Arrays.asList(categorizedEntity1, categorizedEntity2, categorizedEntity3);
}
/**
* Helper method to get the expected Categorized Entities List 2
*/
static List<CategorizedEntity> getCategorizedEntitiesList2() {
return Arrays.asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 10, 9, 0.0));
}
/**
* Helper method to get the expected Batch Categorized Entities
*/
static RecognizeEntitiesResult getExpectedBatchCategorizedEntities1() {
IterableStream<CategorizedEntity> categorizedEntityList1 = new IterableStream<>(getCategorizedEntitiesList1());
TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(44, 1);
RecognizeEntitiesResult recognizeEntitiesResult1 = new RecognizeEntitiesResult("0", textDocumentStatistics1, null, new CategorizedEntityCollection(categorizedEntityList1, null));
return recognizeEntitiesResult1;
}
/**
* Helper method to get the expected Batch Categorized Entities
*/
static RecognizeEntitiesResult getExpectedBatchCategorizedEntities2() {
IterableStream<CategorizedEntity> categorizedEntityList2 = new IterableStream<>(getCategorizedEntitiesList2());
TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(20, 1);
RecognizeEntitiesResult recognizeEntitiesResult2 = new RecognizeEntitiesResult("1", textDocumentStatistics2, null, new CategorizedEntityCollection(categorizedEntityList2, null));
return recognizeEntitiesResult2;
}
/**
* Helper method to get the expected Batch Linked Entities
* @return A {@link RecognizeLinkedEntitiesResultCollection}.
*/
static RecognizeLinkedEntitiesResultCollection getExpectedBatchLinkedEntities() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2);
final List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResultList =
Arrays.asList(
new RecognizeLinkedEntitiesResult(
"0", new TextDocumentStatistics(44, 1), null,
new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)),
new RecognizeLinkedEntitiesResult(
"1", new TextDocumentStatistics(20, 1), null,
new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null)));
return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}
/**
* Helper method to get the expected linked Entities List 1
*/
static List<LinkedEntity> getLinkedEntitiesList1() {
final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Seattle", 26, 7, 0.0);
LinkedEntity linkedEntity = new LinkedEntity(
"Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)),
"en", "Seattle", "https:
"Wikipedia");
return Arrays.asList(linkedEntity);
}
/**
* Helper method to get the expected linked Entities List 2
*/
static List<LinkedEntity> getLinkedEntitiesList2() {
LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 10, 9, 0.0);
LinkedEntity linkedEntity = new LinkedEntity(
"Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)),
"en", "Microsoft", "https:
"Wikipedia");
return Arrays.asList(linkedEntity);
}
/**
* Helper method to get the expected Batch Key Phrases
* @return
*/
static ExtractKeyPhrasesResultCollection getExpectedBatchKeyPhrases() {
TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(49, 1);
TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(21, 1);
ExtractKeyPhraseResult extractKeyPhraseResult1 = new ExtractKeyPhraseResult("0", textDocumentStatistics1, null, new KeyPhrasesCollection(new IterableStream<>(Arrays.asList("input text", "world")), null));
ExtractKeyPhraseResult extractKeyPhraseResult2 = new ExtractKeyPhraseResult("1", textDocumentStatistics2, null, new KeyPhrasesCollection(new IterableStream<>(Collections.singletonList("monde")), null));
TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2);
List<ExtractKeyPhraseResult> extractKeyPhraseResultList = Arrays.asList(extractKeyPhraseResult1, extractKeyPhraseResult2);
return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}
/**
* Helper method to get the expected Batch Text Sentiments
* @return
*/
static AnalyzeSentimentResultCollection getExpectedBatchTextSentiment() {
final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1);
final DocumentSentiment expectedDocumentSentiment = new DocumentSentiment(TextSentiment.MIXED,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(Arrays.asList(
new SentenceSentiment("", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new SentenceSentiment("", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0))
)), null);
final DocumentSentiment expectedDocumentSentiment2 = new DocumentSentiment(TextSentiment.MIXED,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(Arrays.asList(
new SentenceSentiment("", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new SentenceSentiment("", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0))
)), null);
final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0",
textDocumentStatistics, null, expectedDocumentSentiment);
final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1",
textDocumentStatistics, null, expectedDocumentSentiment2);
return new AnalyzeSentimentResultCollection(
Arrays.asList(analyzeSentimentResult1, analyzeSentimentResult2),
DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2));
}
/**
* 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.
*/
static Stream<Arguments> getTestParameters() {
List<Arguments> argumentsList = new ArrayList<>();
getHttpClients()
.forEach(httpClient -> {
Arrays.stream(TextAnalyticsServiceVersion.values()).filter(
TestUtils::shouldServiceVersionBeTested)
.forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion)));
});
return argumentsList.stream();
}
/**
* 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 TextAnalyticsServiceVersion} 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(TextAnalyticsServiceVersion serviceVersion) {
String serviceVersionFromEnv =
Configuration.getGlobalConfiguration().get(AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS);
if (CoreUtils.isNullOrEmpty(serviceVersionFromEnv)) {
return TextAnalyticsServiceVersion.getLatest().equals(serviceVersion);
}
if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(serviceVersionFromEnv)) {
return true;
}
String[] configuredServiceVersionList = serviceVersionFromEnv.split(",");
return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion ->
serviceVersion.getVersion().equals(configuredServiceVersion.trim()));
}
private TestUtils() {
}
} | class TestUtils {
private static final String DEFAULT_MODEL_VERSION = "2019-10-01";
static final String INVALID_URL = "htttttttps:
static final String VALID_HTTPS_LOCALHOST = "https:
static final String FAKE_API_KEY = "1234567890";
static final String AZURE_TEXT_ANALYTICS_API_KEY = "AZURE_TEXT_ANALYTICS_API_KEY";
static final List<String> SENTIMENT_INPUTS = Arrays.asList("The hotel was dark and unclean. The restaurant had amazing gnocchi.",
"The restaurant had amazing gnocchi. The hotel was dark and unclean.");
static final List<String> CATEGORIZED_ENTITY_INPUTS = Arrays.asList(
"I had a wonderful trip to Seattle last week.", "I work at Microsoft.");
static final List<String> LINKED_ENTITY_INPUTS = Arrays.asList(
"I had a wonderful trip to Seattle last week.",
"I work at Microsoft.");
static final List<String> KEY_PHRASE_INPUTS = Arrays.asList(
"Hello world. This is some input text that I love.",
"Bonjour tout le monde");
static final String TOO_LONG_INPUT = "Thisisaveryveryverylongtextwhichgoesonforalongtimeandwhichalmostdoesn'tseemtostopatanygivenpointintime.ThereasonforthistestistotryandseewhathappenswhenwesubmitaveryveryverylongtexttoLanguage.Thisshouldworkjustfinebutjustincaseitisalwaysgoodtohaveatestcase.ThisallowsustotestwhathappensifitisnotOK.Ofcourseitisgoingtobeokbutthenagainitisalsobettertobesure!";
static final List<String> KEY_PHRASE_FRENCH_INPUTS = Arrays.asList(
"Bonjour tout le monde.",
"Je m'appelle Mondly.");
static final List<String> DETECT_LANGUAGE_INPUTS = Arrays.asList(
"This is written in English", "Este es un documento escrito en Español.", "~@!~:)");
static final List<String> SPANISH_SAME_AS_ENGLISH_INPUTS = Arrays.asList("personal", "social");
static final DetectedLanguage DETECTED_LANGUAGE_SPANISH = new DetectedLanguage("Spanish", "es", 1.0, null);
static final DetectedLanguage DETECTED_LANGUAGE_ENGLISH = new DetectedLanguage("English", "en", 1.0, null);
static final List<DetectedLanguage> DETECT_SPANISH_LANGUAGE_RESULTS = Arrays.asList(
DETECTED_LANGUAGE_SPANISH, DETECTED_LANGUAGE_SPANISH);
static final List<DetectedLanguage> DETECT_ENGLISH_LANGUAGE_RESULTS = Arrays.asList(
DETECTED_LANGUAGE_ENGLISH, DETECTED_LANGUAGE_ENGLISH);
static final HttpResponseException HTTP_RESPONSE_EXCEPTION_CLASS = new HttpResponseException("", null);
static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]";
private static final String AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS =
"AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS";
static List<DetectLanguageInput> getDetectLanguageInputs() {
return Arrays.asList(
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"),
new DetectLanguageInput("1", DETECT_LANGUAGE_INPUTS.get(1), "US"),
new DetectLanguageInput("2", DETECT_LANGUAGE_INPUTS.get(2), "US")
);
}
static List<DetectLanguageInput> getDuplicateIdDetectLanguageInputs() {
return Arrays.asList(
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"),
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US")
);
}
static List<TextDocumentInput> getDuplicateTextDocumentInputs() {
return Arrays.asList(
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)),
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)),
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0))
);
}
static List<TextDocumentInput> getWarningsTextDocumentInputs() {
return Arrays.asList(
new TextDocumentInput("0", TOO_LONG_INPUT),
new TextDocumentInput("1", CATEGORIZED_ENTITY_INPUTS.get(1))
);
}
static List<TextDocumentInput> getTextDocumentInputs(List<String> inputs) {
return IntStream.range(0, inputs.size())
.mapToObj(index ->
new TextDocumentInput(String.valueOf(index), inputs.get(index)))
.collect(Collectors.toList());
}
/**
* Helper method to get the expected Batch Detected Languages
*
* @return A {@link DetectLanguageResultCollection}.
*/
static DetectedLanguage getDetectedLanguageEnglish() {
return new DetectedLanguage("English", "en", 0.0, null);
}
static DetectedLanguage getDetectedLanguageSpanish() {
return new DetectedLanguage("Spanish", "es", 0.0, null);
}
static DetectedLanguage getUnknownDetectedLanguage() {
return new DetectedLanguage("(Unknown)", "(Unknown)", 0.0, null);
}
/**
* Helper method to get the expected Batch Categorized Entities
*
* @return A {@link RecognizeEntitiesResultCollection}.
*/
static RecognizeEntitiesResultCollection getExpectedBatchCategorizedEntities() {
return new RecognizeEntitiesResultCollection(
Arrays.asList(getExpectedBatchCategorizedEntities1(), getExpectedBatchCategorizedEntities2()),
DEFAULT_MODEL_VERSION,
new TextDocumentBatchStatistics(2, 2, 0, 2));
}
/**
* Helper method to get the expected Categorized Entities List 1
*/
static List<CategorizedEntity> getCategorizedEntitiesList1() {
CategorizedEntity categorizedEntity1 = new CategorizedEntity("trip", EntityCategory.EVENT, null, 0.0, 18, 4);
CategorizedEntity categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26, 7);
CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34, 9);
return Arrays.asList(categorizedEntity1, categorizedEntity2, categorizedEntity3);
}
/**
* Helper method to get the expected Categorized Entities List 2
*/
static List<CategorizedEntity> getCategorizedEntitiesList2() {
return Arrays.asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10, 9));
}
/**
* Helper method to get the expected Batch Categorized Entities
*/
static RecognizeEntitiesResult getExpectedBatchCategorizedEntities1() {
IterableStream<CategorizedEntity> categorizedEntityList1 = new IterableStream<>(getCategorizedEntitiesList1());
TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(44, 1);
RecognizeEntitiesResult recognizeEntitiesResult1 = new RecognizeEntitiesResult("0", textDocumentStatistics1, null, new CategorizedEntityCollection(categorizedEntityList1, null));
return recognizeEntitiesResult1;
}
/**
* Helper method to get the expected Batch Categorized Entities
*/
static RecognizeEntitiesResult getExpectedBatchCategorizedEntities2() {
IterableStream<CategorizedEntity> categorizedEntityList2 = new IterableStream<>(getCategorizedEntitiesList2());
TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(20, 1);
RecognizeEntitiesResult recognizeEntitiesResult2 = new RecognizeEntitiesResult("1", textDocumentStatistics2, null, new CategorizedEntityCollection(categorizedEntityList2, null));
return recognizeEntitiesResult2;
}
/**
* Helper method to get the expected Batch Linked Entities
* @return A {@link RecognizeLinkedEntitiesResultCollection}.
*/
static RecognizeLinkedEntitiesResultCollection getExpectedBatchLinkedEntities() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2);
final List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResultList =
Arrays.asList(
new RecognizeLinkedEntitiesResult(
"0", new TextDocumentStatistics(44, 1), null,
new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)),
new RecognizeLinkedEntitiesResult(
"1", new TextDocumentStatistics(20, 1), null,
new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null)));
return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}
/**
* Helper method to get the expected linked Entities List 1
*/
static List<LinkedEntity> getLinkedEntitiesList1() {
final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Seattle", 26, 7, 0.0);
LinkedEntity linkedEntity = new LinkedEntity(
"Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)),
"en", "Seattle", "https:
"Wikipedia");
return Arrays.asList(linkedEntity);
}
/**
* Helper method to get the expected linked Entities List 2
*/
static List<LinkedEntity> getLinkedEntitiesList2() {
LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 10, 9, 0.0);
LinkedEntity linkedEntity = new LinkedEntity(
"Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)),
"en", "Microsoft", "https:
"Wikipedia");
return Arrays.asList(linkedEntity);
}
/**
* Helper method to get the expected Batch Key Phrases
* @return
*/
static ExtractKeyPhrasesResultCollection getExpectedBatchKeyPhrases() {
TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(49, 1);
TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(21, 1);
ExtractKeyPhraseResult extractKeyPhraseResult1 = new ExtractKeyPhraseResult("0", textDocumentStatistics1, null, new KeyPhrasesCollection(new IterableStream<>(Arrays.asList("input text", "world")), null));
ExtractKeyPhraseResult extractKeyPhraseResult2 = new ExtractKeyPhraseResult("1", textDocumentStatistics2, null, new KeyPhrasesCollection(new IterableStream<>(Collections.singletonList("monde")), null));
TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2);
List<ExtractKeyPhraseResult> extractKeyPhraseResultList = Arrays.asList(extractKeyPhraseResult1, extractKeyPhraseResult2);
return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}
/**
* Helper method to get the expected Batch Text Sentiments
* @return
*/
static AnalyzeSentimentResultCollection getExpectedBatchTextSentiment() {
final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1);
final DocumentSentiment expectedDocumentSentiment = new DocumentSentiment(TextSentiment.MIXED,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(Arrays.asList(
new SentenceSentiment("", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new SentenceSentiment("", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0))
)), null);
final DocumentSentiment expectedDocumentSentiment2 = new DocumentSentiment(TextSentiment.MIXED,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(Arrays.asList(
new SentenceSentiment("", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new SentenceSentiment("", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0))
)), null);
final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0",
textDocumentStatistics, null, expectedDocumentSentiment);
final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1",
textDocumentStatistics, null, expectedDocumentSentiment2);
return new AnalyzeSentimentResultCollection(
Arrays.asList(analyzeSentimentResult1, analyzeSentimentResult2),
DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2));
}
/**
* 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.
*/
static Stream<Arguments> getTestParameters() {
List<Arguments> argumentsList = new ArrayList<>();
getHttpClients()
.forEach(httpClient -> {
Arrays.stream(TextAnalyticsServiceVersion.values()).filter(
TestUtils::shouldServiceVersionBeTested)
.forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion)));
});
return argumentsList.stream();
}
/**
* 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 TextAnalyticsServiceVersion} 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(TextAnalyticsServiceVersion serviceVersion) {
String serviceVersionFromEnv =
Configuration.getGlobalConfiguration().get(AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS);
if (CoreUtils.isNullOrEmpty(serviceVersionFromEnv)) {
return TextAnalyticsServiceVersion.getLatest().equals(serviceVersion);
}
if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(serviceVersionFromEnv)) {
return true;
}
String[] configuredServiceVersionList = serviceVersionFromEnv.split(",");
return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion ->
serviceVersion.getVersion().equals(configuredServiceVersion.trim()));
}
private TestUtils() {
}
} |
To add getDetectedLanguageEnglish(), getDetectedLanguageSpanish(), and getUnknownDetectedLanguage() helper methods. These result repeatedly used over many place, such as atomic operation. | static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3);
final List<DetectLanguageResult> detectLanguageResultList = Arrays.asList(
new DetectLanguageResult("0", new TextDocumentStatistics(26, 1), null, getDetectedLanguageEnglish()),
new DetectLanguageResult("1", new TextDocumentStatistics(40, 1), null, getDetectedLanguageSpanish()),
new DetectLanguageResult("2", new TextDocumentStatistics(6, 1), null, getUnknownDetectedLanguage()));
return new DetectLanguageResultCollection(detectLanguageResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
} | final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3); | static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3);
final List<DetectLanguageResult> detectLanguageResultList = Arrays.asList(
new DetectLanguageResult("0", new TextDocumentStatistics(26, 1), null, getDetectedLanguageEnglish()),
new DetectLanguageResult("1", new TextDocumentStatistics(40, 1), null, getDetectedLanguageSpanish()),
new DetectLanguageResult("2", new TextDocumentStatistics(6, 1), null, getUnknownDetectedLanguage()));
return new DetectLanguageResultCollection(detectLanguageResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
} | class TestUtils {
private static final String DEFAULT_MODEL_VERSION = "2019-10-01";
static final String INVALID_URL = "htttttttps:
static final String VALID_HTTPS_LOCALHOST = "https:
static final String FAKE_API_KEY = "1234567890";
static final String AZURE_TEXT_ANALYTICS_API_KEY = "AZURE_TEXT_ANALYTICS_API_KEY";
static final List<String> SENTIMENT_INPUTS = Arrays.asList("The hotel was dark and unclean. The restaurant had amazing gnocchi.",
"The restaurant had amazing gnocchi. The hotel was dark and unclean.");
static final List<String> CATEGORIZED_ENTITY_INPUTS = Arrays.asList(
"I had a wonderful trip to Seattle last week.", "I work at Microsoft.");
static final List<String> LINKED_ENTITY_INPUTS = Arrays.asList(
"I had a wonderful trip to Seattle last week.",
"I work at Microsoft.");
static final List<String> KEY_PHRASE_INPUTS = Arrays.asList(
"Hello world. This is some input text that I love.",
"Bonjour tout le monde");
static final String TOO_LONG_INPUT = "Thisisaveryveryverylongtextwhichgoesonforalongtimeandwhichalmostdoesn'tseemtostopatanygivenpointintime.ThereasonforthistestistotryandseewhathappenswhenwesubmitaveryveryverylongtexttoLanguage.Thisshouldworkjustfinebutjustincaseitisalwaysgoodtohaveatestcase.ThisallowsustotestwhathappensifitisnotOK.Ofcourseitisgoingtobeokbutthenagainitisalsobettertobesure!";
static final List<String> KEY_PHRASE_FRENCH_INPUTS = Arrays.asList(
"Bonjour tout le monde.",
"Je m'appelle Mondly.");
static final List<String> DETECT_LANGUAGE_INPUTS = Arrays.asList(
"This is written in English", "Este es un documento escrito en Español.", "~@!~:)");
static final List<String> SPANISH_SAME_AS_ENGLISH_INPUTS = Arrays.asList("personal", "social");
static final DetectedLanguage DETECTED_LANGUAGE_SPANISH = new DetectedLanguage("Spanish", "es", 1.0, null);
static final DetectedLanguage DETECTED_LANGUAGE_ENGLISH = new DetectedLanguage("English", "en", 1.0, null);
static final List<DetectedLanguage> DETECT_SPANISH_LANGUAGE_RESULTS = Arrays.asList(
DETECTED_LANGUAGE_SPANISH, DETECTED_LANGUAGE_SPANISH);
static final List<DetectedLanguage> DETECT_ENGLISH_LANGUAGE_RESULTS = Arrays.asList(
DETECTED_LANGUAGE_ENGLISH, DETECTED_LANGUAGE_ENGLISH);
static final HttpResponseException HTTP_RESPONSE_EXCEPTION_CLASS = new HttpResponseException("", null);
static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]";
private static final String AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS =
"AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS";
static List<DetectLanguageInput> getDetectLanguageInputs() {
return Arrays.asList(
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"),
new DetectLanguageInput("1", DETECT_LANGUAGE_INPUTS.get(1), "US"),
new DetectLanguageInput("2", DETECT_LANGUAGE_INPUTS.get(2), "US")
);
}
static List<DetectLanguageInput> getDuplicateIdDetectLanguageInputs() {
return Arrays.asList(
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"),
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US")
);
}
static List<TextDocumentInput> getDuplicateTextDocumentInputs() {
return Arrays.asList(
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)),
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)),
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0))
);
}
static List<TextDocumentInput> getWarningsTextDocumentInputs() {
return Arrays.asList(
new TextDocumentInput("0", TOO_LONG_INPUT),
new TextDocumentInput("1", CATEGORIZED_ENTITY_INPUTS.get(1))
);
}
static List<TextDocumentInput> getTextDocumentInputs(List<String> inputs) {
return IntStream.range(0, inputs.size())
.mapToObj(index ->
new TextDocumentInput(String.valueOf(index), inputs.get(index)))
.collect(Collectors.toList());
}
/**
* Helper method to get the expected Batch Detected Languages
*
* @return A {@link DetectLanguageResultCollection}.
*/
static DetectedLanguage getDetectedLanguageEnglish() {
return new DetectedLanguage("English", "en", 0.0, null);
}
static DetectedLanguage getDetectedLanguageSpanish() {
return new DetectedLanguage("Spanish", "es", 0.0, null);
}
static DetectedLanguage getUnknownDetectedLanguage() {
return new DetectedLanguage("(Unknown)", "(Unknown)", 0.0, null);
}
/**
* Helper method to get the expected Batch Categorized Entities
*
* @return A {@link RecognizeEntitiesResultCollection}.
*/
static RecognizeEntitiesResultCollection getExpectedBatchCategorizedEntities() {
return new RecognizeEntitiesResultCollection(
Arrays.asList(getExpectedBatchCategorizedEntities1(), getExpectedBatchCategorizedEntities2()),
DEFAULT_MODEL_VERSION,
new TextDocumentBatchStatistics(2, 2, 0, 2));
}
/**
* Helper method to get the expected Categorized Entities List 1
*/
static List<CategorizedEntity> getCategorizedEntitiesList1() {
CategorizedEntity categorizedEntity1 = new CategorizedEntity("trip", EntityCategory.EVENT, null, 18, 4, 0.0);
CategorizedEntity categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 26, 7, 0.0);
CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 34, 9, 0.0);
return Arrays.asList(categorizedEntity1, categorizedEntity2, categorizedEntity3);
}
/**
* Helper method to get the expected Categorized Entities List 2
*/
static List<CategorizedEntity> getCategorizedEntitiesList2() {
return Arrays.asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 10, 9, 0.0));
}
/**
* Helper method to get the expected Batch Categorized Entities
*/
static RecognizeEntitiesResult getExpectedBatchCategorizedEntities1() {
IterableStream<CategorizedEntity> categorizedEntityList1 = new IterableStream<>(getCategorizedEntitiesList1());
TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(44, 1);
RecognizeEntitiesResult recognizeEntitiesResult1 = new RecognizeEntitiesResult("0", textDocumentStatistics1, null, new CategorizedEntityCollection(categorizedEntityList1, null));
return recognizeEntitiesResult1;
}
/**
* Helper method to get the expected Batch Categorized Entities
*/
static RecognizeEntitiesResult getExpectedBatchCategorizedEntities2() {
IterableStream<CategorizedEntity> categorizedEntityList2 = new IterableStream<>(getCategorizedEntitiesList2());
TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(20, 1);
RecognizeEntitiesResult recognizeEntitiesResult2 = new RecognizeEntitiesResult("1", textDocumentStatistics2, null, new CategorizedEntityCollection(categorizedEntityList2, null));
return recognizeEntitiesResult2;
}
/**
* Helper method to get the expected Batch Linked Entities
* @return A {@link RecognizeLinkedEntitiesResultCollection}.
*/
static RecognizeLinkedEntitiesResultCollection getExpectedBatchLinkedEntities() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2);
final List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResultList =
Arrays.asList(
new RecognizeLinkedEntitiesResult(
"0", new TextDocumentStatistics(44, 1), null,
new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)),
new RecognizeLinkedEntitiesResult(
"1", new TextDocumentStatistics(20, 1), null,
new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null)));
return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}
/**
* Helper method to get the expected linked Entities List 1
*/
static List<LinkedEntity> getLinkedEntitiesList1() {
final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Seattle", 26, 7, 0.0);
LinkedEntity linkedEntity = new LinkedEntity(
"Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)),
"en", "Seattle", "https:
"Wikipedia");
return Arrays.asList(linkedEntity);
}
/**
* Helper method to get the expected linked Entities List 2
*/
static List<LinkedEntity> getLinkedEntitiesList2() {
LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 10, 9, 0.0);
LinkedEntity linkedEntity = new LinkedEntity(
"Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)),
"en", "Microsoft", "https:
"Wikipedia");
return Arrays.asList(linkedEntity);
}
/**
* Helper method to get the expected Batch Key Phrases
* @return
*/
static ExtractKeyPhrasesResultCollection getExpectedBatchKeyPhrases() {
TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(49, 1);
TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(21, 1);
ExtractKeyPhraseResult extractKeyPhraseResult1 = new ExtractKeyPhraseResult("0", textDocumentStatistics1, null, new KeyPhrasesCollection(new IterableStream<>(Arrays.asList("input text", "world")), null));
ExtractKeyPhraseResult extractKeyPhraseResult2 = new ExtractKeyPhraseResult("1", textDocumentStatistics2, null, new KeyPhrasesCollection(new IterableStream<>(Collections.singletonList("monde")), null));
TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2);
List<ExtractKeyPhraseResult> extractKeyPhraseResultList = Arrays.asList(extractKeyPhraseResult1, extractKeyPhraseResult2);
return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}
/**
* Helper method to get the expected Batch Text Sentiments
* @return
*/
static AnalyzeSentimentResultCollection getExpectedBatchTextSentiment() {
final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1);
final DocumentSentiment expectedDocumentSentiment = new DocumentSentiment(TextSentiment.MIXED,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(Arrays.asList(
new SentenceSentiment("", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new SentenceSentiment("", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0))
)), null);
final DocumentSentiment expectedDocumentSentiment2 = new DocumentSentiment(TextSentiment.MIXED,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(Arrays.asList(
new SentenceSentiment("", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new SentenceSentiment("", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0))
)), null);
final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0",
textDocumentStatistics, null, expectedDocumentSentiment);
final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1",
textDocumentStatistics, null, expectedDocumentSentiment2);
return new AnalyzeSentimentResultCollection(
Arrays.asList(analyzeSentimentResult1, analyzeSentimentResult2),
DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2));
}
/**
* 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.
*/
static Stream<Arguments> getTestParameters() {
List<Arguments> argumentsList = new ArrayList<>();
getHttpClients()
.forEach(httpClient -> {
Arrays.stream(TextAnalyticsServiceVersion.values()).filter(
TestUtils::shouldServiceVersionBeTested)
.forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion)));
});
return argumentsList.stream();
}
/**
* 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 TextAnalyticsServiceVersion} 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(TextAnalyticsServiceVersion serviceVersion) {
String serviceVersionFromEnv =
Configuration.getGlobalConfiguration().get(AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS);
if (CoreUtils.isNullOrEmpty(serviceVersionFromEnv)) {
return TextAnalyticsServiceVersion.getLatest().equals(serviceVersion);
}
if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(serviceVersionFromEnv)) {
return true;
}
String[] configuredServiceVersionList = serviceVersionFromEnv.split(",");
return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion ->
serviceVersion.getVersion().equals(configuredServiceVersion.trim()));
}
private TestUtils() {
}
} | class TestUtils {
private static final String DEFAULT_MODEL_VERSION = "2019-10-01";
static final String INVALID_URL = "htttttttps:
static final String VALID_HTTPS_LOCALHOST = "https:
static final String FAKE_API_KEY = "1234567890";
static final String AZURE_TEXT_ANALYTICS_API_KEY = "AZURE_TEXT_ANALYTICS_API_KEY";
static final List<String> SENTIMENT_INPUTS = Arrays.asList("The hotel was dark and unclean. The restaurant had amazing gnocchi.",
"The restaurant had amazing gnocchi. The hotel was dark and unclean.");
static final List<String> CATEGORIZED_ENTITY_INPUTS = Arrays.asList(
"I had a wonderful trip to Seattle last week.", "I work at Microsoft.");
static final List<String> LINKED_ENTITY_INPUTS = Arrays.asList(
"I had a wonderful trip to Seattle last week.",
"I work at Microsoft.");
static final List<String> KEY_PHRASE_INPUTS = Arrays.asList(
"Hello world. This is some input text that I love.",
"Bonjour tout le monde");
static final String TOO_LONG_INPUT = "Thisisaveryveryverylongtextwhichgoesonforalongtimeandwhichalmostdoesn'tseemtostopatanygivenpointintime.ThereasonforthistestistotryandseewhathappenswhenwesubmitaveryveryverylongtexttoLanguage.Thisshouldworkjustfinebutjustincaseitisalwaysgoodtohaveatestcase.ThisallowsustotestwhathappensifitisnotOK.Ofcourseitisgoingtobeokbutthenagainitisalsobettertobesure!";
static final List<String> KEY_PHRASE_FRENCH_INPUTS = Arrays.asList(
"Bonjour tout le monde.",
"Je m'appelle Mondly.");
static final List<String> DETECT_LANGUAGE_INPUTS = Arrays.asList(
"This is written in English", "Este es un documento escrito en Español.", "~@!~:)");
static final List<String> SPANISH_SAME_AS_ENGLISH_INPUTS = Arrays.asList("personal", "social");
static final DetectedLanguage DETECTED_LANGUAGE_SPANISH = new DetectedLanguage("Spanish", "es", 1.0, null);
static final DetectedLanguage DETECTED_LANGUAGE_ENGLISH = new DetectedLanguage("English", "en", 1.0, null);
static final List<DetectedLanguage> DETECT_SPANISH_LANGUAGE_RESULTS = Arrays.asList(
DETECTED_LANGUAGE_SPANISH, DETECTED_LANGUAGE_SPANISH);
static final List<DetectedLanguage> DETECT_ENGLISH_LANGUAGE_RESULTS = Arrays.asList(
DETECTED_LANGUAGE_ENGLISH, DETECTED_LANGUAGE_ENGLISH);
static final HttpResponseException HTTP_RESPONSE_EXCEPTION_CLASS = new HttpResponseException("", null);
static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]";
private static final String AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS =
"AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS";
static List<DetectLanguageInput> getDetectLanguageInputs() {
return Arrays.asList(
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"),
new DetectLanguageInput("1", DETECT_LANGUAGE_INPUTS.get(1), "US"),
new DetectLanguageInput("2", DETECT_LANGUAGE_INPUTS.get(2), "US")
);
}
static List<DetectLanguageInput> getDuplicateIdDetectLanguageInputs() {
return Arrays.asList(
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"),
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US")
);
}
static List<TextDocumentInput> getDuplicateTextDocumentInputs() {
return Arrays.asList(
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)),
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)),
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0))
);
}
static List<TextDocumentInput> getWarningsTextDocumentInputs() {
return Arrays.asList(
new TextDocumentInput("0", TOO_LONG_INPUT),
new TextDocumentInput("1", CATEGORIZED_ENTITY_INPUTS.get(1))
);
}
static List<TextDocumentInput> getTextDocumentInputs(List<String> inputs) {
return IntStream.range(0, inputs.size())
.mapToObj(index ->
new TextDocumentInput(String.valueOf(index), inputs.get(index)))
.collect(Collectors.toList());
}
/**
* Helper method to get the expected Batch Detected Languages
*
* @return A {@link DetectLanguageResultCollection}.
*/
static DetectedLanguage getDetectedLanguageEnglish() {
return new DetectedLanguage("English", "en", 0.0, null);
}
static DetectedLanguage getDetectedLanguageSpanish() {
return new DetectedLanguage("Spanish", "es", 0.0, null);
}
static DetectedLanguage getUnknownDetectedLanguage() {
return new DetectedLanguage("(Unknown)", "(Unknown)", 0.0, null);
}
/**
* Helper method to get the expected Batch Categorized Entities
*
* @return A {@link RecognizeEntitiesResultCollection}.
*/
static RecognizeEntitiesResultCollection getExpectedBatchCategorizedEntities() {
return new RecognizeEntitiesResultCollection(
Arrays.asList(getExpectedBatchCategorizedEntities1(), getExpectedBatchCategorizedEntities2()),
DEFAULT_MODEL_VERSION,
new TextDocumentBatchStatistics(2, 2, 0, 2));
}
/**
* Helper method to get the expected Categorized Entities List 1
*/
static List<CategorizedEntity> getCategorizedEntitiesList1() {
CategorizedEntity categorizedEntity1 = new CategorizedEntity("trip", EntityCategory.EVENT, null, 0.0, 18, 4);
CategorizedEntity categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26, 7);
CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34, 9);
return Arrays.asList(categorizedEntity1, categorizedEntity2, categorizedEntity3);
}
/**
* Helper method to get the expected Categorized Entities List 2
*/
static List<CategorizedEntity> getCategorizedEntitiesList2() {
return Arrays.asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10, 9));
}
/**
* Helper method to get the expected Batch Categorized Entities
*/
static RecognizeEntitiesResult getExpectedBatchCategorizedEntities1() {
IterableStream<CategorizedEntity> categorizedEntityList1 = new IterableStream<>(getCategorizedEntitiesList1());
TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(44, 1);
RecognizeEntitiesResult recognizeEntitiesResult1 = new RecognizeEntitiesResult("0", textDocumentStatistics1, null, new CategorizedEntityCollection(categorizedEntityList1, null));
return recognizeEntitiesResult1;
}
/**
* Helper method to get the expected Batch Categorized Entities
*/
static RecognizeEntitiesResult getExpectedBatchCategorizedEntities2() {
IterableStream<CategorizedEntity> categorizedEntityList2 = new IterableStream<>(getCategorizedEntitiesList2());
TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(20, 1);
RecognizeEntitiesResult recognizeEntitiesResult2 = new RecognizeEntitiesResult("1", textDocumentStatistics2, null, new CategorizedEntityCollection(categorizedEntityList2, null));
return recognizeEntitiesResult2;
}
/**
* Helper method to get the expected Batch Linked Entities
* @return A {@link RecognizeLinkedEntitiesResultCollection}.
*/
static RecognizeLinkedEntitiesResultCollection getExpectedBatchLinkedEntities() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2);
final List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResultList =
Arrays.asList(
new RecognizeLinkedEntitiesResult(
"0", new TextDocumentStatistics(44, 1), null,
new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)),
new RecognizeLinkedEntitiesResult(
"1", new TextDocumentStatistics(20, 1), null,
new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null)));
return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}
/**
* Helper method to get the expected linked Entities List 1
*/
static List<LinkedEntity> getLinkedEntitiesList1() {
final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Seattle", 26, 7, 0.0);
LinkedEntity linkedEntity = new LinkedEntity(
"Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)),
"en", "Seattle", "https:
"Wikipedia");
return Arrays.asList(linkedEntity);
}
/**
* Helper method to get the expected linked Entities List 2
*/
static List<LinkedEntity> getLinkedEntitiesList2() {
LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 10, 9, 0.0);
LinkedEntity linkedEntity = new LinkedEntity(
"Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)),
"en", "Microsoft", "https:
"Wikipedia");
return Arrays.asList(linkedEntity);
}
/**
* Helper method to get the expected Batch Key Phrases
* @return
*/
static ExtractKeyPhrasesResultCollection getExpectedBatchKeyPhrases() {
TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(49, 1);
TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(21, 1);
ExtractKeyPhraseResult extractKeyPhraseResult1 = new ExtractKeyPhraseResult("0", textDocumentStatistics1, null, new KeyPhrasesCollection(new IterableStream<>(Arrays.asList("input text", "world")), null));
ExtractKeyPhraseResult extractKeyPhraseResult2 = new ExtractKeyPhraseResult("1", textDocumentStatistics2, null, new KeyPhrasesCollection(new IterableStream<>(Collections.singletonList("monde")), null));
TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2);
List<ExtractKeyPhraseResult> extractKeyPhraseResultList = Arrays.asList(extractKeyPhraseResult1, extractKeyPhraseResult2);
return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}
/**
* Helper method to get the expected Batch Text Sentiments
* @return
*/
static AnalyzeSentimentResultCollection getExpectedBatchTextSentiment() {
final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1);
final DocumentSentiment expectedDocumentSentiment = new DocumentSentiment(TextSentiment.MIXED,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(Arrays.asList(
new SentenceSentiment("", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new SentenceSentiment("", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0))
)), null);
final DocumentSentiment expectedDocumentSentiment2 = new DocumentSentiment(TextSentiment.MIXED,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(Arrays.asList(
new SentenceSentiment("", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new SentenceSentiment("", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0))
)), null);
final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0",
textDocumentStatistics, null, expectedDocumentSentiment);
final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1",
textDocumentStatistics, null, expectedDocumentSentiment2);
return new AnalyzeSentimentResultCollection(
Arrays.asList(analyzeSentimentResult1, analyzeSentimentResult2),
DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2));
}
/**
* 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.
*/
static Stream<Arguments> getTestParameters() {
List<Arguments> argumentsList = new ArrayList<>();
getHttpClients()
.forEach(httpClient -> {
Arrays.stream(TextAnalyticsServiceVersion.values()).filter(
TestUtils::shouldServiceVersionBeTested)
.forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion)));
});
return argumentsList.stream();
}
/**
* 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 TextAnalyticsServiceVersion} 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(TextAnalyticsServiceVersion serviceVersion) {
String serviceVersionFromEnv =
Configuration.getGlobalConfiguration().get(AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS);
if (CoreUtils.isNullOrEmpty(serviceVersionFromEnv)) {
return TextAnalyticsServiceVersion.getLatest().equals(serviceVersion);
}
if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(serviceVersionFromEnv)) {
return true;
}
String[] configuredServiceVersionList = serviceVersionFromEnv.split(",");
return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion ->
serviceVersion.getVersion().equals(configuredServiceVersion.trim()));
}
private TestUtils() {
}
} |
Instead of using blocking calls, since now we are going asynchronous, please try using `StepVerifier` from reactor-test. Its actually built in for testing async APIs. We have used it in azure-spring-data-cosmos-test and also in azure-cosmos. Please take a look at `VeryLargeDocumentQueryTest.java` and any reactive test in azure-spring-data-cosmos-test - `ReactiveCosmosTemplateIT`, `ReactiveCourseRepositoryIT`, etc. | public void asyncCreateItemEncrypt_readItemDecrypt() throws Exception {
EncryptionItemRequestOptions requestOptions = new EncryptionItemRequestOptions();
EncryptionOptions encryptionOptions = new EncryptionOptions();
encryptionOptions.setPathsToEncrypt(ImmutableList.of("/Sensitive"));
encryptionOptions.setDataEncryptionKeyId(dekId);
encryptionOptions.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256_RANDOMIZED);
requestOptions.setEncryptionOptions(encryptionOptions);
TestDoc properties = getItem(UUID.randomUUID().toString());
itemContainer.createItem(
properties,
new PartitionKey(properties.pk),
requestOptions)
.flatMap(
createResponse -> {
return encryptionContainer.upsertItem(
properties,
new PartitionKey(properties.pk),
requestOptions);
})
.flatMap(
response -> {
logger.info("1 on thread [{}]",
Thread.currentThread().getName());
Mono<CosmosItemResponse<TestDoc>> readItem = encryptionContainer.readItem(properties.id,
new PartitionKey(properties.pk),
requestOptions, TestDoc.class);
return readItem;
})
.flatMap(
readItem -> {
logger.info("2 on thread [{}]",
Thread.currentThread().getName());
return itemContainer.readItem(properties.id, new PartitionKey(properties.pk), TestDoc.class);
})
.flatMap(
readItem -> {
logger.info("3 on thread [{}]",
Thread.currentThread().getName());
return encryptionContainer.readItem(properties.id, new PartitionKey(properties.pk),
requestOptions,
TestDoc.class);
}
).block();
} | TestDoc properties = getItem(UUID.randomUUID().toString()); | public void asyncCreateItemEncrypt_readItemDecrypt() throws Exception {
EncryptionItemRequestOptions requestOptions = new EncryptionItemRequestOptions();
EncryptionOptions encryptionOptions = new EncryptionOptions();
encryptionOptions.setPathsToEncrypt(ImmutableList.of("/Sensitive"));
encryptionOptions.setDataEncryptionKeyId(dekId);
encryptionOptions.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256_RANDOMIZED);
requestOptions.setEncryptionOptions(encryptionOptions);
TestDoc properties = getItem(UUID.randomUUID().toString());
StepVerifier.create(itemContainer.createItem(
properties,
new PartitionKey(properties.pk),
requestOptions)
.flatMap(
createResponse -> {
logger.info("1 on thread [{}]",
Thread.currentThread().getName());
return encryptionContainer.upsertItem(
properties,
new PartitionKey(properties.pk),
requestOptions);
})
.flatMap(
response -> {
logger.info("2 on thread [{}]",
Thread.currentThread().getName());
Mono<CosmosItemResponse<TestDoc>> readItem = encryptionContainer.readItem(properties.id,
new PartitionKey(properties.pk),
requestOptions, TestDoc.class);
return readItem;
})
.flatMap(
readItem -> {
logger.info("3 on thread [{}]",
Thread.currentThread().getName());
return itemContainer.readItem(properties.id, new PartitionKey(properties.pk), TestDoc.class);
})
.flatMap(
readItem -> {
logger.info("4 on thread [{}]",
Thread.currentThread().getName());
return encryptionContainer.readItem(properties.id, new PartitionKey(properties.pk),
requestOptions,
TestDoc.class);
}
))
.expectNextMatches(testDocCosmosItemResponse ->
{
TestDoc item = testDocCosmosItemResponse.getItem();
return item.sensitive != null;
})
.verifyComplete();
} | class TestDoc {
public static List<String> PathsToEncrypt = ImmutableList.of("/Sensitive");
public static List<String> AllPath = ImmutableList.of("/Sensitive", "/id", "/PK", "/NonSensitive");
@JsonProperty("id")
public String id;
@JsonProperty("PK")
public String pk;
@JsonProperty("NonSensitive")
public String nonSensitive;
@JsonProperty("Sensitive")
public String sensitive;
public TestDoc() {
}
public TestDoc(TestDoc other) {
this.id = other.id;
this.pk = other.pk;
this.nonSensitive = other.nonSensitive;
this.sensitive = other.sensitive;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TestDoc testDoc = (TestDoc) o;
return Objects.equals(id, testDoc.id) &&
Objects.equals(pk, testDoc.pk) &&
Objects.equals(nonSensitive, testDoc.nonSensitive) &&
Objects.equals(sensitive, testDoc.sensitive);
}
public static TestDoc create() {
return TestDoc.create(null);
}
public static TestDoc create(String partitionKey) {
TestDoc testDoc = new TestDoc();
testDoc.id = UUID.randomUUID().toString();
testDoc.pk = partitionKey == null ? UUID.randomUUID().toString() : partitionKey;
testDoc.nonSensitive = UUID.randomUUID().toString();
testDoc.sensitive = UUID.randomUUID().toString();
return testDoc;
}
@Override
public int hashCode() {
return Objects.hash(id, pk, nonSensitive, sensitive);
}
} | class TestDoc {
public static List<String> PathsToEncrypt = ImmutableList.of("/Sensitive");
public static List<String> AllPath = ImmutableList.of("/Sensitive", "/id", "/PK", "/NonSensitive");
@JsonProperty("id")
public String id;
@JsonProperty("PK")
public String pk;
@JsonProperty("NonSensitive")
public String nonSensitive;
@JsonProperty("Sensitive")
public String sensitive;
public TestDoc() {
}
public TestDoc(TestDoc other) {
this.id = other.id;
this.pk = other.pk;
this.nonSensitive = other.nonSensitive;
this.sensitive = other.sensitive;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TestDoc testDoc = (TestDoc) o;
return Objects.equals(id, testDoc.id) &&
Objects.equals(pk, testDoc.pk) &&
Objects.equals(nonSensitive, testDoc.nonSensitive) &&
Objects.equals(sensitive, testDoc.sensitive);
}
public static TestDoc create() {
return TestDoc.create(null);
}
public static TestDoc create(String partitionKey) {
TestDoc testDoc = new TestDoc();
testDoc.id = UUID.randomUUID().toString();
testDoc.pk = partitionKey == null ? UUID.randomUUID().toString() : partitionKey;
testDoc.nonSensitive = UUID.randomUUID().toString();
testDoc.sensitive = UUID.randomUUID().toString();
return testDoc;
}
@Override
public int hashCode() {
return Objects.hash(id, pk, nonSensitive, sensitive);
}
} |
good suggestion. Moved to `StepVerifier` for test validation. | public void asyncCreateItemEncrypt_readItemDecrypt() throws Exception {
EncryptionItemRequestOptions requestOptions = new EncryptionItemRequestOptions();
EncryptionOptions encryptionOptions = new EncryptionOptions();
encryptionOptions.setPathsToEncrypt(ImmutableList.of("/Sensitive"));
encryptionOptions.setDataEncryptionKeyId(dekId);
encryptionOptions.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256_RANDOMIZED);
requestOptions.setEncryptionOptions(encryptionOptions);
TestDoc properties = getItem(UUID.randomUUID().toString());
itemContainer.createItem(
properties,
new PartitionKey(properties.pk),
requestOptions)
.flatMap(
createResponse -> {
return encryptionContainer.upsertItem(
properties,
new PartitionKey(properties.pk),
requestOptions);
})
.flatMap(
response -> {
logger.info("1 on thread [{}]",
Thread.currentThread().getName());
Mono<CosmosItemResponse<TestDoc>> readItem = encryptionContainer.readItem(properties.id,
new PartitionKey(properties.pk),
requestOptions, TestDoc.class);
return readItem;
})
.flatMap(
readItem -> {
logger.info("2 on thread [{}]",
Thread.currentThread().getName());
return itemContainer.readItem(properties.id, new PartitionKey(properties.pk), TestDoc.class);
})
.flatMap(
readItem -> {
logger.info("3 on thread [{}]",
Thread.currentThread().getName());
return encryptionContainer.readItem(properties.id, new PartitionKey(properties.pk),
requestOptions,
TestDoc.class);
}
).block();
} | TestDoc properties = getItem(UUID.randomUUID().toString()); | public void asyncCreateItemEncrypt_readItemDecrypt() throws Exception {
EncryptionItemRequestOptions requestOptions = new EncryptionItemRequestOptions();
EncryptionOptions encryptionOptions = new EncryptionOptions();
encryptionOptions.setPathsToEncrypt(ImmutableList.of("/Sensitive"));
encryptionOptions.setDataEncryptionKeyId(dekId);
encryptionOptions.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256_RANDOMIZED);
requestOptions.setEncryptionOptions(encryptionOptions);
TestDoc properties = getItem(UUID.randomUUID().toString());
StepVerifier.create(itemContainer.createItem(
properties,
new PartitionKey(properties.pk),
requestOptions)
.flatMap(
createResponse -> {
logger.info("1 on thread [{}]",
Thread.currentThread().getName());
return encryptionContainer.upsertItem(
properties,
new PartitionKey(properties.pk),
requestOptions);
})
.flatMap(
response -> {
logger.info("2 on thread [{}]",
Thread.currentThread().getName());
Mono<CosmosItemResponse<TestDoc>> readItem = encryptionContainer.readItem(properties.id,
new PartitionKey(properties.pk),
requestOptions, TestDoc.class);
return readItem;
})
.flatMap(
readItem -> {
logger.info("3 on thread [{}]",
Thread.currentThread().getName());
return itemContainer.readItem(properties.id, new PartitionKey(properties.pk), TestDoc.class);
})
.flatMap(
readItem -> {
logger.info("4 on thread [{}]",
Thread.currentThread().getName());
return encryptionContainer.readItem(properties.id, new PartitionKey(properties.pk),
requestOptions,
TestDoc.class);
}
))
.expectNextMatches(testDocCosmosItemResponse ->
{
TestDoc item = testDocCosmosItemResponse.getItem();
return item.sensitive != null;
})
.verifyComplete();
} | class TestDoc {
public static List<String> PathsToEncrypt = ImmutableList.of("/Sensitive");
public static List<String> AllPath = ImmutableList.of("/Sensitive", "/id", "/PK", "/NonSensitive");
@JsonProperty("id")
public String id;
@JsonProperty("PK")
public String pk;
@JsonProperty("NonSensitive")
public String nonSensitive;
@JsonProperty("Sensitive")
public String sensitive;
public TestDoc() {
}
public TestDoc(TestDoc other) {
this.id = other.id;
this.pk = other.pk;
this.nonSensitive = other.nonSensitive;
this.sensitive = other.sensitive;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TestDoc testDoc = (TestDoc) o;
return Objects.equals(id, testDoc.id) &&
Objects.equals(pk, testDoc.pk) &&
Objects.equals(nonSensitive, testDoc.nonSensitive) &&
Objects.equals(sensitive, testDoc.sensitive);
}
public static TestDoc create() {
return TestDoc.create(null);
}
public static TestDoc create(String partitionKey) {
TestDoc testDoc = new TestDoc();
testDoc.id = UUID.randomUUID().toString();
testDoc.pk = partitionKey == null ? UUID.randomUUID().toString() : partitionKey;
testDoc.nonSensitive = UUID.randomUUID().toString();
testDoc.sensitive = UUID.randomUUID().toString();
return testDoc;
}
@Override
public int hashCode() {
return Objects.hash(id, pk, nonSensitive, sensitive);
}
} | class TestDoc {
public static List<String> PathsToEncrypt = ImmutableList.of("/Sensitive");
public static List<String> AllPath = ImmutableList.of("/Sensitive", "/id", "/PK", "/NonSensitive");
@JsonProperty("id")
public String id;
@JsonProperty("PK")
public String pk;
@JsonProperty("NonSensitive")
public String nonSensitive;
@JsonProperty("Sensitive")
public String sensitive;
public TestDoc() {
}
public TestDoc(TestDoc other) {
this.id = other.id;
this.pk = other.pk;
this.nonSensitive = other.nonSensitive;
this.sensitive = other.sensitive;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TestDoc testDoc = (TestDoc) o;
return Objects.equals(id, testDoc.id) &&
Objects.equals(pk, testDoc.pk) &&
Objects.equals(nonSensitive, testDoc.nonSensitive) &&
Objects.equals(sensitive, testDoc.sensitive);
}
public static TestDoc create() {
return TestDoc.create(null);
}
public static TestDoc create(String partitionKey) {
TestDoc testDoc = new TestDoc();
testDoc.id = UUID.randomUUID().toString();
testDoc.pk = partitionKey == null ? UUID.randomUUID().toString() : partitionKey;
testDoc.nonSensitive = UUID.randomUUID().toString();
testDoc.sensitive = UUID.randomUUID().toString();
return testDoc;
}
@Override
public int hashCode() {
return Objects.hash(id, pk, nonSensitive, sensitive);
}
} |
ditto, for the`SPACE`, the only constant we should use here is the `HttpConstants.Versions.SDK_VERSION` | private String getUserAgentFixedPart() {
String osName = System.getProperty("os.name");
if (osName == null) {
osName = "Unknown";
}
osName = osName.replaceAll("\\s", "");
String geteUserAgentFixedPart =
UserAgentContainer.AZSDK_USERAGENT_PREFIX +
"cosmos" +
"/" +
HttpConstants.Versions.SDK_VERSION +
SPACE +
osName +
"/" +
System.getProperty("os.version") +
SPACE +
"JRE/" +
System.getProperty("java.version");
return geteUserAgentFixedPart;
} | SPACE + | private String getUserAgentFixedPart() {
String osName = System.getProperty("os.name");
if (osName == null) {
osName = "Unknown";
}
osName = osName.replaceAll("\\s", "");
String geteUserAgentFixedPart = "azsdk-java-" +
"cosmos" +
"/" +
HttpConstants.Versions.SDK_VERSION +
SPACE +
osName +
"/" +
System.getProperty("os.version") +
SPACE +
"JRE/" +
System.getProperty("java.version");
return geteUserAgentFixedPart;
} | class UserAgentContainerTest {
private final static String SPACE = " ";
private final static int TIMEOUT = 40000;
@Test(groups = {"unit"})
public void userAgentContainerSetSuffix() {
String expectedStringFixedPart = getUserAgentFixedPart();
String userProvidedSuffix = "test-application-id";
UserAgentContainer userAgentContainer = new UserAgentContainer();
userAgentContainer.setSuffix(userProvidedSuffix);
String expectedString = expectedStringFixedPart + SPACE + userProvidedSuffix;
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
userAgentContainer = new UserAgentContainer();
expectedString = expectedStringFixedPart;
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
userProvidedSuffix = "greater than 64 characters
userAgentContainer = new UserAgentContainer();
userAgentContainer.setSuffix(userProvidedSuffix);
expectedString = expectedStringFixedPart + SPACE + userProvidedSuffix.substring(0, 64);
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
}
@Test(groups = {"emulator"}, timeOut = TIMEOUT)
public void UserAgentIntegrationTest() {
String userProvidedSuffix = "test-application-id";
CosmosAsyncClient gatewayClient = null;
CosmosAsyncClient directClient = null;
try {
gatewayClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.gatewayMode()
.userAgentSuffix(userProvidedSuffix)
.buildAsyncClient();
RxDocumentClientImpl documentClient =
(RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(gatewayClient);
UserAgentContainer userAgentContainer = ReflectionUtils.getUserAgentContainer(documentClient);
String expectedString = getUserAgentFixedPart() + SPACE + userProvidedSuffix;
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
directClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.directMode()
.userAgentSuffix(userProvidedSuffix)
.buildAsyncClient();
documentClient = (RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(directClient);
userAgentContainer = ReflectionUtils.getUserAgentContainer(documentClient);
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
} finally {
if (gatewayClient != null) {
gatewayClient.close();
}
if (directClient != null) {
directClient.close();
}
}
}
} | class UserAgentContainerTest {
private final static String SPACE = " ";
private final static int TIMEOUT = 40000;
@Test(groups = {"unit"})
public void userAgentContainerSetSuffix() {
String expectedStringFixedPart = getUserAgentFixedPart();
String userProvidedSuffix = "test-application-id";
UserAgentContainer userAgentContainer = new UserAgentContainer();
userAgentContainer.setSuffix(userProvidedSuffix);
String expectedString = expectedStringFixedPart + SPACE + userProvidedSuffix;
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
userAgentContainer = new UserAgentContainer();
expectedString = expectedStringFixedPart;
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
userProvidedSuffix = "greater than 64 characters
userAgentContainer = new UserAgentContainer();
userAgentContainer.setSuffix(userProvidedSuffix);
expectedString = expectedStringFixedPart + SPACE + userProvidedSuffix.substring(0, 64);
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
}
@Test(groups = {"emulator"}, timeOut = TIMEOUT)
public void UserAgentIntegration() {
String userProvidedSuffix = "test-application-id";
CosmosAsyncClient gatewayClient = null;
CosmosAsyncClient directClient = null;
try {
gatewayClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.gatewayMode()
.userAgentSuffix(userProvidedSuffix)
.buildAsyncClient();
RxDocumentClientImpl documentClient =
(RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(gatewayClient);
UserAgentContainer userAgentContainer = ReflectionUtils.getUserAgentContainer(documentClient);
String expectedString = getUserAgentFixedPart() + SPACE + userProvidedSuffix;
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
directClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.directMode()
.userAgentSuffix(userProvidedSuffix)
.buildAsyncClient();
documentClient = (RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(directClient);
userAgentContainer = ReflectionUtils.getUserAgentContainer(documentClient);
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
} finally {
if (gatewayClient != null) {
gatewayClient.close();
}
if (directClient != null) {
directClient.close();
}
}
}
} |
Why can't we change the name directly in hotel json file but to modify here after serialization? There are two other test classes which have the similar structure, SuggestSyncTests and SearchSyncTest. | public static void setupClass() {
TestBase.setupClass();
if (TEST_MODE == TestMode.PLAYBACK) {
return;
}
Reader indexData = new InputStreamReader(Objects.requireNonNull(AutocompleteSyncTests.class
.getClassLoader()
.getResourceAsStream(HOTELS_TESTS_INDEX_DATA_JSON)));
try {
SearchIndex index = new ObjectMapper().readValue(indexData, SearchIndex.class);
Field searchIndexName = index.getClass().getDeclaredField("name");
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
searchIndexName.setAccessible(true);
return null;
});
searchIndexName.set(index, INDEX_NAME);
searchIndexClient = new SearchIndexClientBuilder()
.endpoint(ENDPOINT)
.credential(new AzureKeyCredential(API_KEY))
.retryPolicy(new RetryPolicy(new ExponentialBackoff(3, Duration.ofSeconds(10), Duration.ofSeconds(30))))
.buildClient();
searchIndexClient.createOrUpdateIndex(index);
uploadDocumentsJson(searchIndexClient.getSearchClient(INDEX_NAME), HOTELS_DATA_JSON);
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
} | searchIndexName.set(index, INDEX_NAME); | public static void setupClass() {
TestBase.setupClass();
if (TEST_MODE == TestMode.PLAYBACK) {
return;
}
searchIndexClient = setupSharedIndex(INDEX_NAME);
} | class AutocompleteSyncTests extends SearchTestBase {
private static final String HOTELS_DATA_JSON = "HotelsDataArray.json";
private static final String INDEX_NAME = "azsearch-autocomplete-shared-instance";
private static SearchIndexClient searchIndexClient;
private SearchClient client;
@BeforeAll
@Override
protected void beforeTest() {
client = getSearchClientBuilder(INDEX_NAME).buildClient();
}
@AfterAll
protected static void cleanupClass() {
if (TEST_MODE != TestMode.PLAYBACK) {
searchIndexClient.deleteIndex(INDEX_NAME);
}
}
@Test
public void canAutocompleteThrowsWhenGivenBadSuggesterName() {
AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("very po", "Invalid suggester", params, Context.NONE);
assertHttpResponseException(
() -> results.iterableByPage().iterator().next(),
HttpURLConnection.HTTP_BAD_REQUEST,
"The specified suggester name 'Invalid suggester' does not exist in this index definition.\\r\\nParameter name: name");
}
@Test
public void canAutocompleteDefaultsToOneTermMode() {
List<String> expectedText = Arrays.asList("point", "police", "polite", "pool", "popular");
List<String> expectedQueryPlusText = Arrays.asList("point", "police", "polite", "pool", "popular");
validateResults(client.autocomplete("po", "sg").iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void canAutocompleteOneTermWithContext() {
List<String> expectedText = Arrays.asList("very police", "very polite", "very popular");
List<String> expectedQueryPlusText = Arrays.asList("looking for very police", "looking for very polite",
"looking for very popular");
AutocompleteOptions params = new AutocompleteOptions();
params.setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("looking for very po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void canAutocompleteExcludesFieldsNotInSuggester() {
AutocompleteOptions params = new AutocompleteOptions();
params.setAutocompleteMode(AutocompleteMode.ONE_TERM);
params.setSearchFields("HotelName");
Iterator<AutocompletePagedResponse> results = client
.autocomplete("luxu", "sg", params, Context.NONE)
.iterableByPage()
.iterator();
assertEquals(0, results.next().getValue().size());
assertFalse(results.hasNext());
}
@Test
public void canAutocompleteFuzzyIsOffByDefault() {
AutocompleteOptions params = new AutocompleteOptions();
params.setAutocompleteMode(AutocompleteMode.ONE_TERM);
Iterator<AutocompletePagedResponse> results = client
.autocomplete("pi", "sg", params, Context.NONE)
.iterableByPage()
.iterator();
assertEquals(0, results.next().getValue().size());
assertFalse(results.hasNext());
}
@Test
public void canAutocompleteOneTerm() {
List<String> expectedText = Arrays.asList("point", "police", "polite", "pool", "popular");
List<String> expectedQueryPlusText = Arrays.asList("point", "police", "polite", "pool", "popular");
AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void canAutocompleteStaticallyTypedDocuments() {
List<String> expectedText = Arrays.asList("point", "police", "polite", "pool", "popular");
List<String> expectedQueryPlusText = Arrays.asList("very point", "very police", "very polite", "very pool", "very popular");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setUseFuzzyMatching(false);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("very po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void canAutocompleteThrowsWhenRequestIsMalformed() {
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client.autocomplete("very po", "");
assertHttpResponseException(
() -> results.iterableByPage().iterator().next(),
HttpURLConnection.HTTP_BAD_REQUEST,
"Cannot find fields enabled for suggestions. Please provide a value for 'suggesterName' in the query.\\r\\nParameter name: suggestions"
);
}
@Test
public void canAutocompleteTwoTerms() {
List<String> expectedText = Arrays.asList("point motel", "police station", "polite staff", "pool a", "popular hotel");
List<String> expectedQueryPlusText = Arrays.asList("point motel", "police station", "polite staff", "pool a", "popular hotel");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.TWO_TERMS);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteCanUseHitHighlighting() {
List<String> expectedText = Arrays.asList("pool", "popular");
List<String> expectedQueryPlusText = Arrays.asList("<b>pool</b>", "<b>popular</b>");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setFilter("HotelName eq 'EconoStay' or HotelName eq 'Fancy Stay'")
.setHighlightPreTag("<b>")
.setHighlightPostTag("</b>");
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteWithMultipleSelectedFields() {
List<String> expectedText = Arrays.asList("model", "modern");
List<String> expectedQueryPlusText = Arrays.asList("model", "modern");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setSearchFields("HotelName", "Description");
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("mod", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteWithSelectedFields() {
List<String> expectedText = Collections.singletonList("modern");
List<String> expectedQueryPlusText = Collections.singletonList("modern");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setSearchFields("HotelName")
.setFilter("HotelId eq '7'");
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("mod", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteTopTrimsResults() {
List<String> expectedText = Arrays.asList("point", "police");
List<String> expectedQueryPlusText = Arrays.asList("point", "police");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setTop(2);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteWithFilter() {
List<String> expectedText = Collections.singletonList("polite");
List<String> expectedQueryPlusText = Collections.singletonList("polite");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setFilter("search.in(HotelId, '6,7')");
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteOneTermWithContextWithFuzzy() {
List<String> expectedText = Arrays.asList("very polite", "very police");
List<String> expectedQueryPlusText = Arrays.asList("very polite", "very police");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT)
.setUseFuzzyMatching(true);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("very polit", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteOneTermWithFuzzy() {
List<String> expectedText = Arrays.asList("model", "modern", "morel", "motel");
List<String> expectedQueryPlusText = Arrays.asList("model", "modern", "morel", "motel");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setUseFuzzyMatching(true);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("mod", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteTwoTermsWithFuzzy() {
List<String> expectedText = Arrays.asList("model suites", "modern architecture", "modern stay", "morel coverings", "motel");
List<String> expectedQueryPlusText = Arrays.asList("model suites", "modern architecture", "modern stay", "morel coverings", "motel");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.TWO_TERMS)
.setUseFuzzyMatching(true);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("mod", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteWithFilterAndFuzzy() {
List<String> expectedText = Arrays.asList("modern", "motel");
List<String> expectedQueryPlusText = Arrays.asList("modern", "motel");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setUseFuzzyMatching(true)
.setFilter("HotelId ne '6' and (HotelName eq 'Modern Stay' or Tags/any(t : t eq 'budget'))");
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("mod", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
/**
* Compare the autocomplete results with the expected strings
*
* @param iterator results iterator
* @param expectedText expected text
* @param expectedQueryPlusText expected query plus text
*/
private void validateResults(Iterator<AutocompleteItem> iterator, List<String> expectedText,
List<String> expectedQueryPlusText) {
int index = 0;
while (iterator.hasNext()) {
AutocompleteItem item = iterator.next();
assertEquals(expectedText.get(index), item.getText());
assertEquals(expectedQueryPlusText.get(index), item.getQueryPlusText());
index++;
}
}
} | class AutocompleteSyncTests extends SearchTestBase {
private static final String HOTELS_DATA_JSON = "HotelsDataArray.json";
private static final String INDEX_NAME = "azsearch-autocomplete-shared-instance";
private static SearchIndexClient searchIndexClient;
private SearchClient client;
@BeforeAll
@Override
protected void beforeTest() {
client = getSearchClientBuilder(INDEX_NAME).buildClient();
}
@AfterAll
protected static void cleanupClass() {
if (TEST_MODE != TestMode.PLAYBACK) {
searchIndexClient.deleteIndex(INDEX_NAME);
}
}
@Test
public void canAutocompleteThrowsWhenGivenBadSuggesterName() {
AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("very po", "Invalid suggester", params, Context.NONE);
assertHttpResponseException(
() -> results.iterableByPage().iterator().next(),
HttpURLConnection.HTTP_BAD_REQUEST,
"The specified suggester name 'Invalid suggester' does not exist in this index definition.\\r\\nParameter name: name");
}
@Test
public void canAutocompleteDefaultsToOneTermMode() {
List<String> expectedText = Arrays.asList("point", "police", "polite", "pool", "popular");
List<String> expectedQueryPlusText = Arrays.asList("point", "police", "polite", "pool", "popular");
validateResults(client.autocomplete("po", "sg").iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void canAutocompleteOneTermWithContext() {
List<String> expectedText = Arrays.asList("very police", "very polite", "very popular");
List<String> expectedQueryPlusText = Arrays.asList("looking for very police", "looking for very polite",
"looking for very popular");
AutocompleteOptions params = new AutocompleteOptions();
params.setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("looking for very po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void canAutocompleteExcludesFieldsNotInSuggester() {
AutocompleteOptions params = new AutocompleteOptions();
params.setAutocompleteMode(AutocompleteMode.ONE_TERM);
params.setSearchFields("HotelName");
Iterator<AutocompletePagedResponse> results = client
.autocomplete("luxu", "sg", params, Context.NONE)
.iterableByPage()
.iterator();
assertEquals(0, results.next().getValue().size());
assertFalse(results.hasNext());
}
@Test
public void canAutocompleteFuzzyIsOffByDefault() {
AutocompleteOptions params = new AutocompleteOptions();
params.setAutocompleteMode(AutocompleteMode.ONE_TERM);
Iterator<AutocompletePagedResponse> results = client
.autocomplete("pi", "sg", params, Context.NONE)
.iterableByPage()
.iterator();
assertEquals(0, results.next().getValue().size());
assertFalse(results.hasNext());
}
@Test
public void canAutocompleteOneTerm() {
List<String> expectedText = Arrays.asList("point", "police", "polite", "pool", "popular");
List<String> expectedQueryPlusText = Arrays.asList("point", "police", "polite", "pool", "popular");
AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void canAutocompleteStaticallyTypedDocuments() {
List<String> expectedText = Arrays.asList("point", "police", "polite", "pool", "popular");
List<String> expectedQueryPlusText = Arrays.asList("very point", "very police", "very polite", "very pool", "very popular");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setUseFuzzyMatching(false);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("very po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void canAutocompleteThrowsWhenRequestIsMalformed() {
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client.autocomplete("very po", "");
assertHttpResponseException(
() -> results.iterableByPage().iterator().next(),
HttpURLConnection.HTTP_BAD_REQUEST,
"Cannot find fields enabled for suggestions. Please provide a value for 'suggesterName' in the query.\\r\\nParameter name: suggestions"
);
}
@Test
public void canAutocompleteTwoTerms() {
List<String> expectedText = Arrays.asList("point motel", "police station", "polite staff", "pool a", "popular hotel");
List<String> expectedQueryPlusText = Arrays.asList("point motel", "police station", "polite staff", "pool a", "popular hotel");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.TWO_TERMS);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteCanUseHitHighlighting() {
List<String> expectedText = Arrays.asList("pool", "popular");
List<String> expectedQueryPlusText = Arrays.asList("<b>pool</b>", "<b>popular</b>");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setFilter("HotelName eq 'EconoStay' or HotelName eq 'Fancy Stay'")
.setHighlightPreTag("<b>")
.setHighlightPostTag("</b>");
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteWithMultipleSelectedFields() {
List<String> expectedText = Arrays.asList("model", "modern");
List<String> expectedQueryPlusText = Arrays.asList("model", "modern");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setSearchFields("HotelName", "Description");
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("mod", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteWithSelectedFields() {
List<String> expectedText = Collections.singletonList("modern");
List<String> expectedQueryPlusText = Collections.singletonList("modern");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setSearchFields("HotelName")
.setFilter("HotelId eq '7'");
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("mod", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteTopTrimsResults() {
List<String> expectedText = Arrays.asList("point", "police");
List<String> expectedQueryPlusText = Arrays.asList("point", "police");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setTop(2);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteWithFilter() {
List<String> expectedText = Collections.singletonList("polite");
List<String> expectedQueryPlusText = Collections.singletonList("polite");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setFilter("search.in(HotelId, '6,7')");
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteOneTermWithContextWithFuzzy() {
List<String> expectedText = Arrays.asList("very polite", "very police");
List<String> expectedQueryPlusText = Arrays.asList("very polite", "very police");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT)
.setUseFuzzyMatching(true);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("very polit", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteOneTermWithFuzzy() {
List<String> expectedText = Arrays.asList("model", "modern", "morel", "motel");
List<String> expectedQueryPlusText = Arrays.asList("model", "modern", "morel", "motel");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setUseFuzzyMatching(true);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("mod", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteTwoTermsWithFuzzy() {
List<String> expectedText = Arrays.asList("model suites", "modern architecture", "modern stay", "morel coverings", "motel");
List<String> expectedQueryPlusText = Arrays.asList("model suites", "modern architecture", "modern stay", "morel coverings", "motel");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.TWO_TERMS)
.setUseFuzzyMatching(true);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("mod", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteWithFilterAndFuzzy() {
List<String> expectedText = Arrays.asList("modern", "motel");
List<String> expectedQueryPlusText = Arrays.asList("modern", "motel");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setUseFuzzyMatching(true)
.setFilter("HotelId ne '6' and (HotelName eq 'Modern Stay' or Tags/any(t : t eq 'budget'))");
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("mod", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
/**
* Compare the autocomplete results with the expected strings
*
* @param iterator results iterator
* @param expectedText expected text
* @param expectedQueryPlusText expected query plus text
*/
private void validateResults(Iterator<AutocompleteItem> iterator, List<String> expectedText,
List<String> expectedQueryPlusText) {
int index = 0;
while (iterator.hasNext()) {
AutocompleteItem item = iterator.next();
assertEquals(expectedText.get(index), item.getText());
assertEquals(expectedQueryPlusText.get(index), item.getQueryPlusText());
index++;
}
}
} |
Updated Search and Suggest test which are able to share an instance. The name is changed using reflection as many tests use this file so it won't be safe to make it a global name. | public static void setupClass() {
TestBase.setupClass();
if (TEST_MODE == TestMode.PLAYBACK) {
return;
}
Reader indexData = new InputStreamReader(Objects.requireNonNull(AutocompleteSyncTests.class
.getClassLoader()
.getResourceAsStream(HOTELS_TESTS_INDEX_DATA_JSON)));
try {
SearchIndex index = new ObjectMapper().readValue(indexData, SearchIndex.class);
Field searchIndexName = index.getClass().getDeclaredField("name");
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
searchIndexName.setAccessible(true);
return null;
});
searchIndexName.set(index, INDEX_NAME);
searchIndexClient = new SearchIndexClientBuilder()
.endpoint(ENDPOINT)
.credential(new AzureKeyCredential(API_KEY))
.retryPolicy(new RetryPolicy(new ExponentialBackoff(3, Duration.ofSeconds(10), Duration.ofSeconds(30))))
.buildClient();
searchIndexClient.createOrUpdateIndex(index);
uploadDocumentsJson(searchIndexClient.getSearchClient(INDEX_NAME), HOTELS_DATA_JSON);
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
} | searchIndexName.set(index, INDEX_NAME); | public static void setupClass() {
TestBase.setupClass();
if (TEST_MODE == TestMode.PLAYBACK) {
return;
}
searchIndexClient = setupSharedIndex(INDEX_NAME);
} | class AutocompleteSyncTests extends SearchTestBase {
private static final String HOTELS_DATA_JSON = "HotelsDataArray.json";
private static final String INDEX_NAME = "azsearch-autocomplete-shared-instance";
private static SearchIndexClient searchIndexClient;
private SearchClient client;
@BeforeAll
@Override
protected void beforeTest() {
client = getSearchClientBuilder(INDEX_NAME).buildClient();
}
@AfterAll
protected static void cleanupClass() {
if (TEST_MODE != TestMode.PLAYBACK) {
searchIndexClient.deleteIndex(INDEX_NAME);
}
}
@Test
public void canAutocompleteThrowsWhenGivenBadSuggesterName() {
AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("very po", "Invalid suggester", params, Context.NONE);
assertHttpResponseException(
() -> results.iterableByPage().iterator().next(),
HttpURLConnection.HTTP_BAD_REQUEST,
"The specified suggester name 'Invalid suggester' does not exist in this index definition.\\r\\nParameter name: name");
}
@Test
public void canAutocompleteDefaultsToOneTermMode() {
List<String> expectedText = Arrays.asList("point", "police", "polite", "pool", "popular");
List<String> expectedQueryPlusText = Arrays.asList("point", "police", "polite", "pool", "popular");
validateResults(client.autocomplete("po", "sg").iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void canAutocompleteOneTermWithContext() {
List<String> expectedText = Arrays.asList("very police", "very polite", "very popular");
List<String> expectedQueryPlusText = Arrays.asList("looking for very police", "looking for very polite",
"looking for very popular");
AutocompleteOptions params = new AutocompleteOptions();
params.setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("looking for very po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void canAutocompleteExcludesFieldsNotInSuggester() {
AutocompleteOptions params = new AutocompleteOptions();
params.setAutocompleteMode(AutocompleteMode.ONE_TERM);
params.setSearchFields("HotelName");
Iterator<AutocompletePagedResponse> results = client
.autocomplete("luxu", "sg", params, Context.NONE)
.iterableByPage()
.iterator();
assertEquals(0, results.next().getValue().size());
assertFalse(results.hasNext());
}
@Test
public void canAutocompleteFuzzyIsOffByDefault() {
AutocompleteOptions params = new AutocompleteOptions();
params.setAutocompleteMode(AutocompleteMode.ONE_TERM);
Iterator<AutocompletePagedResponse> results = client
.autocomplete("pi", "sg", params, Context.NONE)
.iterableByPage()
.iterator();
assertEquals(0, results.next().getValue().size());
assertFalse(results.hasNext());
}
@Test
public void canAutocompleteOneTerm() {
List<String> expectedText = Arrays.asList("point", "police", "polite", "pool", "popular");
List<String> expectedQueryPlusText = Arrays.asList("point", "police", "polite", "pool", "popular");
AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void canAutocompleteStaticallyTypedDocuments() {
List<String> expectedText = Arrays.asList("point", "police", "polite", "pool", "popular");
List<String> expectedQueryPlusText = Arrays.asList("very point", "very police", "very polite", "very pool", "very popular");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setUseFuzzyMatching(false);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("very po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void canAutocompleteThrowsWhenRequestIsMalformed() {
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client.autocomplete("very po", "");
assertHttpResponseException(
() -> results.iterableByPage().iterator().next(),
HttpURLConnection.HTTP_BAD_REQUEST,
"Cannot find fields enabled for suggestions. Please provide a value for 'suggesterName' in the query.\\r\\nParameter name: suggestions"
);
}
@Test
public void canAutocompleteTwoTerms() {
List<String> expectedText = Arrays.asList("point motel", "police station", "polite staff", "pool a", "popular hotel");
List<String> expectedQueryPlusText = Arrays.asList("point motel", "police station", "polite staff", "pool a", "popular hotel");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.TWO_TERMS);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteCanUseHitHighlighting() {
List<String> expectedText = Arrays.asList("pool", "popular");
List<String> expectedQueryPlusText = Arrays.asList("<b>pool</b>", "<b>popular</b>");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setFilter("HotelName eq 'EconoStay' or HotelName eq 'Fancy Stay'")
.setHighlightPreTag("<b>")
.setHighlightPostTag("</b>");
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteWithMultipleSelectedFields() {
List<String> expectedText = Arrays.asList("model", "modern");
List<String> expectedQueryPlusText = Arrays.asList("model", "modern");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setSearchFields("HotelName", "Description");
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("mod", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteWithSelectedFields() {
List<String> expectedText = Collections.singletonList("modern");
List<String> expectedQueryPlusText = Collections.singletonList("modern");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setSearchFields("HotelName")
.setFilter("HotelId eq '7'");
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("mod", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteTopTrimsResults() {
List<String> expectedText = Arrays.asList("point", "police");
List<String> expectedQueryPlusText = Arrays.asList("point", "police");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setTop(2);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteWithFilter() {
List<String> expectedText = Collections.singletonList("polite");
List<String> expectedQueryPlusText = Collections.singletonList("polite");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setFilter("search.in(HotelId, '6,7')");
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteOneTermWithContextWithFuzzy() {
List<String> expectedText = Arrays.asList("very polite", "very police");
List<String> expectedQueryPlusText = Arrays.asList("very polite", "very police");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT)
.setUseFuzzyMatching(true);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("very polit", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteOneTermWithFuzzy() {
List<String> expectedText = Arrays.asList("model", "modern", "morel", "motel");
List<String> expectedQueryPlusText = Arrays.asList("model", "modern", "morel", "motel");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setUseFuzzyMatching(true);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("mod", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteTwoTermsWithFuzzy() {
List<String> expectedText = Arrays.asList("model suites", "modern architecture", "modern stay", "morel coverings", "motel");
List<String> expectedQueryPlusText = Arrays.asList("model suites", "modern architecture", "modern stay", "morel coverings", "motel");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.TWO_TERMS)
.setUseFuzzyMatching(true);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("mod", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteWithFilterAndFuzzy() {
List<String> expectedText = Arrays.asList("modern", "motel");
List<String> expectedQueryPlusText = Arrays.asList("modern", "motel");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setUseFuzzyMatching(true)
.setFilter("HotelId ne '6' and (HotelName eq 'Modern Stay' or Tags/any(t : t eq 'budget'))");
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("mod", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
/**
* Compare the autocomplete results with the expected strings
*
* @param iterator results iterator
* @param expectedText expected text
* @param expectedQueryPlusText expected query plus text
*/
private void validateResults(Iterator<AutocompleteItem> iterator, List<String> expectedText,
List<String> expectedQueryPlusText) {
int index = 0;
while (iterator.hasNext()) {
AutocompleteItem item = iterator.next();
assertEquals(expectedText.get(index), item.getText());
assertEquals(expectedQueryPlusText.get(index), item.getQueryPlusText());
index++;
}
}
} | class AutocompleteSyncTests extends SearchTestBase {
private static final String HOTELS_DATA_JSON = "HotelsDataArray.json";
private static final String INDEX_NAME = "azsearch-autocomplete-shared-instance";
private static SearchIndexClient searchIndexClient;
private SearchClient client;
@BeforeAll
@Override
protected void beforeTest() {
client = getSearchClientBuilder(INDEX_NAME).buildClient();
}
@AfterAll
protected static void cleanupClass() {
if (TEST_MODE != TestMode.PLAYBACK) {
searchIndexClient.deleteIndex(INDEX_NAME);
}
}
@Test
public void canAutocompleteThrowsWhenGivenBadSuggesterName() {
AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("very po", "Invalid suggester", params, Context.NONE);
assertHttpResponseException(
() -> results.iterableByPage().iterator().next(),
HttpURLConnection.HTTP_BAD_REQUEST,
"The specified suggester name 'Invalid suggester' does not exist in this index definition.\\r\\nParameter name: name");
}
@Test
public void canAutocompleteDefaultsToOneTermMode() {
List<String> expectedText = Arrays.asList("point", "police", "polite", "pool", "popular");
List<String> expectedQueryPlusText = Arrays.asList("point", "police", "polite", "pool", "popular");
validateResults(client.autocomplete("po", "sg").iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void canAutocompleteOneTermWithContext() {
List<String> expectedText = Arrays.asList("very police", "very polite", "very popular");
List<String> expectedQueryPlusText = Arrays.asList("looking for very police", "looking for very polite",
"looking for very popular");
AutocompleteOptions params = new AutocompleteOptions();
params.setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("looking for very po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void canAutocompleteExcludesFieldsNotInSuggester() {
AutocompleteOptions params = new AutocompleteOptions();
params.setAutocompleteMode(AutocompleteMode.ONE_TERM);
params.setSearchFields("HotelName");
Iterator<AutocompletePagedResponse> results = client
.autocomplete("luxu", "sg", params, Context.NONE)
.iterableByPage()
.iterator();
assertEquals(0, results.next().getValue().size());
assertFalse(results.hasNext());
}
@Test
public void canAutocompleteFuzzyIsOffByDefault() {
AutocompleteOptions params = new AutocompleteOptions();
params.setAutocompleteMode(AutocompleteMode.ONE_TERM);
Iterator<AutocompletePagedResponse> results = client
.autocomplete("pi", "sg", params, Context.NONE)
.iterableByPage()
.iterator();
assertEquals(0, results.next().getValue().size());
assertFalse(results.hasNext());
}
@Test
public void canAutocompleteOneTerm() {
List<String> expectedText = Arrays.asList("point", "police", "polite", "pool", "popular");
List<String> expectedQueryPlusText = Arrays.asList("point", "police", "polite", "pool", "popular");
AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void canAutocompleteStaticallyTypedDocuments() {
List<String> expectedText = Arrays.asList("point", "police", "polite", "pool", "popular");
List<String> expectedQueryPlusText = Arrays.asList("very point", "very police", "very polite", "very pool", "very popular");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setUseFuzzyMatching(false);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("very po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void canAutocompleteThrowsWhenRequestIsMalformed() {
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client.autocomplete("very po", "");
assertHttpResponseException(
() -> results.iterableByPage().iterator().next(),
HttpURLConnection.HTTP_BAD_REQUEST,
"Cannot find fields enabled for suggestions. Please provide a value for 'suggesterName' in the query.\\r\\nParameter name: suggestions"
);
}
@Test
public void canAutocompleteTwoTerms() {
List<String> expectedText = Arrays.asList("point motel", "police station", "polite staff", "pool a", "popular hotel");
List<String> expectedQueryPlusText = Arrays.asList("point motel", "police station", "polite staff", "pool a", "popular hotel");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.TWO_TERMS);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteCanUseHitHighlighting() {
List<String> expectedText = Arrays.asList("pool", "popular");
List<String> expectedQueryPlusText = Arrays.asList("<b>pool</b>", "<b>popular</b>");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setFilter("HotelName eq 'EconoStay' or HotelName eq 'Fancy Stay'")
.setHighlightPreTag("<b>")
.setHighlightPostTag("</b>");
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteWithMultipleSelectedFields() {
List<String> expectedText = Arrays.asList("model", "modern");
List<String> expectedQueryPlusText = Arrays.asList("model", "modern");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setSearchFields("HotelName", "Description");
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("mod", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteWithSelectedFields() {
List<String> expectedText = Collections.singletonList("modern");
List<String> expectedQueryPlusText = Collections.singletonList("modern");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setSearchFields("HotelName")
.setFilter("HotelId eq '7'");
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("mod", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteTopTrimsResults() {
List<String> expectedText = Arrays.asList("point", "police");
List<String> expectedQueryPlusText = Arrays.asList("point", "police");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setTop(2);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteWithFilter() {
List<String> expectedText = Collections.singletonList("polite");
List<String> expectedQueryPlusText = Collections.singletonList("polite");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setFilter("search.in(HotelId, '6,7')");
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("po", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteOneTermWithContextWithFuzzy() {
List<String> expectedText = Arrays.asList("very polite", "very police");
List<String> expectedQueryPlusText = Arrays.asList("very polite", "very police");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT)
.setUseFuzzyMatching(true);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("very polit", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteOneTermWithFuzzy() {
List<String> expectedText = Arrays.asList("model", "modern", "morel", "motel");
List<String> expectedQueryPlusText = Arrays.asList("model", "modern", "morel", "motel");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setUseFuzzyMatching(true);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("mod", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteTwoTermsWithFuzzy() {
List<String> expectedText = Arrays.asList("model suites", "modern architecture", "modern stay", "morel coverings", "motel");
List<String> expectedQueryPlusText = Arrays.asList("model suites", "modern architecture", "modern stay", "morel coverings", "motel");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.TWO_TERMS)
.setUseFuzzyMatching(true);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("mod", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
@Test
public void testAutocompleteWithFilterAndFuzzy() {
List<String> expectedText = Arrays.asList("modern", "motel");
List<String> expectedQueryPlusText = Arrays.asList("modern", "motel");
AutocompleteOptions params = new AutocompleteOptions()
.setAutocompleteMode(AutocompleteMode.ONE_TERM)
.setUseFuzzyMatching(true)
.setFilter("HotelId ne '6' and (HotelName eq 'Modern Stay' or Tags/any(t : t eq 'budget'))");
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = client
.autocomplete("mod", "sg", params, Context.NONE);
validateResults(results.iterator(), expectedText, expectedQueryPlusText);
}
/**
* Compare the autocomplete results with the expected strings
*
* @param iterator results iterator
* @param expectedText expected text
* @param expectedQueryPlusText expected query plus text
*/
private void validateResults(Iterator<AutocompleteItem> iterator, List<String> expectedText,
List<String> expectedQueryPlusText) {
int index = 0;
while (iterator.hasNext()) {
AutocompleteItem item = iterator.next();
assertEquals(expectedText.get(index), item.getText());
assertEquals(expectedQueryPlusText.get(index), item.getQueryPlusText());
index++;
}
}
} |
I would keep the original testing scenarios commented too. | static void validatePrimaryLanguage(DetectedLanguage expectedLanguage, DetectedLanguage actualLanguage) {
assertNotNull(actualLanguage.getIso6391Name());
assertNotNull(actualLanguage.getName());
assertNotNull(actualLanguage.getConfidenceScore());
} | static void validatePrimaryLanguage(DetectedLanguage expectedLanguage, DetectedLanguage actualLanguage) {
assertNotNull(actualLanguage.getIso6391Name());
assertNotNull(actualLanguage.getName());
assertNotNull(actualLanguage.getConfidenceScore());
} | class TextAnalyticsClientTestBase extends TestBase {
static final String BATCH_ERROR_EXCEPTION_MESSAGE = "Error in accessing the property on document id: 2, when RecognizeEntitiesResult returned with an error: Document text is empty. ErrorCodeValue: {invalidDocument}";
static final String EXCEEDED_ALLOWED_DOCUMENTS_LIMITS_MESSAGE = "The number of documents in the request have exceeded the data limitations. See https:
static final String INVALID_COUNTRY_HINT_EXPECTED_EXCEPTION_MESSAGE = "Country hint is not valid. Please specify an ISO 3166-1 alpha-2 two letter country code. ErrorCodeValue: {invalidCountryHint}";
static final String INVALID_DOCUMENT_BATCH = "invalidDocumentBatch";
static final String INVALID_DOCUMENT_BATCH_NPE_MESSAGE = "'documents' cannot be null.";
static final String INVALID_DOCUMENT_EMPTY_LIST_EXCEPTION_MESSAGE = "'documents' cannot be empty.";
static final String INVALID_DOCUMENT_EXPECTED_EXCEPTION_MESSAGE = "Document text is empty. ErrorCodeValue: {invalidDocument}";
static final String INVALID_DOCUMENT_NPE_MESSAGE = "'document' cannot be null.";
static final String WARNING_TOO_LONG_DOCUMENT_INPUT_MESSAGE = "The document contains very long words (longer than 64 characters). These words will be truncated and may result in unreliable model predictions.";
@Test
abstract void detectSingleTextLanguage(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void detectLanguageEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void detectLanguageFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void detectLanguagesBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void detectLanguagesBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void detectLanguagesBatchListCountryHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeEntitiesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeEntitiesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeEntitiesForFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeEntitiesBatchInputSingleError(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeEntitiesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeEntitiesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeEntitiesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeLinkedEntitiesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeLinkedEntitiesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeLinkedEntitiesForFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeLinkedEntitiesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeLinkedEntitiesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeLinkedEntitiesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void extractKeyPhrasesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void extractKeyPhrasesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void extractKeyPhrasesForFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void extractKeyPhrasesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void extractKeyPhrasesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void extractKeyPhrasesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void extractKeyPhrasesWarning(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void extractKeyPhrasesBatchWarning(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void analyzeSentimentForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void analyzeSentimentForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void analyzeSentimentForFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void analyzeSentimentForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void analyzeSentimentForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void analyzeSentimentForBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void analyzeSentimentForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
void detectLanguageShowStatisticsRunner(BiConsumer<List<DetectLanguageInput>,
TextAnalyticsRequestOptions> testRunner) {
final List<DetectLanguageInput> detectLanguageInputs = TestUtils.getDetectLanguageInputs();
TextAnalyticsRequestOptions options = new TextAnalyticsRequestOptions().setIncludeStatistics(true);
testRunner.accept(detectLanguageInputs, options);
}
void detectLanguageDuplicateIdRunner(BiConsumer<List<DetectLanguageInput>,
TextAnalyticsRequestOptions> testRunner) {
testRunner.accept(TestUtils.getDuplicateIdDetectLanguageInputs(), null);
}
void detectLanguagesCountryHintRunner(BiConsumer<List<String>, String> testRunner) {
testRunner.accept(DETECT_LANGUAGE_INPUTS, "US");
}
void detectLanguagesBatchListCountryHintWithOptionsRunner(BiConsumer<List<String>,
TextAnalyticsRequestOptions> testRunner) {
TextAnalyticsRequestOptions options = new TextAnalyticsRequestOptions().setIncludeStatistics(true);
testRunner.accept(TestUtils.DETECT_LANGUAGE_INPUTS, options);
}
void detectLanguageStringInputRunner(Consumer<List<String>> testRunner) {
testRunner.accept(DETECT_LANGUAGE_INPUTS);
}
void detectLanguageRunner(Consumer<List<DetectLanguageInput>> testRunner) {
testRunner.accept(TestUtils.getDetectLanguageInputs());
}
void detectSingleTextLanguageRunner(Consumer<String> testRunner) {
testRunner.accept(DETECT_LANGUAGE_INPUTS.get(0));
}
void detectLanguageInvalidCountryHintRunner(BiConsumer<String, String> testRunner) {
testRunner.accept(DETECT_LANGUAGE_INPUTS.get(1), "en");
}
void detectLanguageEmptyCountryHintRunner(BiConsumer<String, String> testRunner) {
testRunner.accept(DETECT_LANGUAGE_INPUTS.get(1), "");
}
void detectLanguageNoneCountryHintRunner(BiConsumer<String, String> testRunner) {
testRunner.accept(DETECT_LANGUAGE_INPUTS.get(1), "none");
}
void recognizeCategorizedEntitiesForSingleTextInputRunner(Consumer<String> testRunner) {
testRunner.accept(CATEGORIZED_ENTITY_INPUTS.get(0));
}
void recognizeCategorizedEntityStringInputRunner(Consumer<List<String>> testRunner) {
testRunner.accept(CATEGORIZED_ENTITY_INPUTS);
}
void recognizeCategorizedEntityDuplicateIdRunner(Consumer<List<TextDocumentInput>> testRunner) {
testRunner.accept(getDuplicateTextDocumentInputs());
}
void recognizeCategorizedEntitiesLanguageHintRunner(BiConsumer<List<String>, String> testRunner) {
testRunner.accept(CATEGORIZED_ENTITY_INPUTS, "en");
}
void recognizeBatchCategorizedEntitySingleErrorRunner(Consumer<List<TextDocumentInput>> testRunner) {
List<TextDocumentInput> inputs = Collections.singletonList(new TextDocumentInput("2", " "));
testRunner.accept(inputs);
}
void recognizeBatchCategorizedEntityRunner(Consumer<List<TextDocumentInput>> testRunner) {
testRunner.accept(TestUtils.getTextDocumentInputs(CATEGORIZED_ENTITY_INPUTS));
}
void recognizeBatchCategorizedEntitiesShowStatsRunner(
BiConsumer<List<TextDocumentInput>, TextAnalyticsRequestOptions> testRunner) {
final List<TextDocumentInput> textDocumentInputs = TestUtils.getTextDocumentInputs(CATEGORIZED_ENTITY_INPUTS);
TextAnalyticsRequestOptions options = new TextAnalyticsRequestOptions().setIncludeStatistics(true);
testRunner.accept(textDocumentInputs, options);
}
void recognizeStringBatchCategorizedEntitiesShowStatsRunner(
BiConsumer<List<String>, TextAnalyticsRequestOptions> testRunner) {
testRunner.accept(CATEGORIZED_ENTITY_INPUTS, new TextAnalyticsRequestOptions().setIncludeStatistics(true));
}
void recognizeEntitiesTooManyDocumentsRunner(
Consumer<List<String>> testRunner) {
final String documentInput = CATEGORIZED_ENTITY_INPUTS.get(0);
testRunner.accept(
Arrays.asList(documentInput, documentInput, documentInput, documentInput, documentInput, documentInput));
}
void recognizeLinkedEntitiesForSingleTextInputRunner(Consumer<String> testRunner) {
testRunner.accept(LINKED_ENTITY_INPUTS.get(0));
}
void recognizeBatchStringLinkedEntitiesShowStatsRunner(
BiConsumer<List<String>, TextAnalyticsRequestOptions> testRunner) {
testRunner.accept(LINKED_ENTITY_INPUTS, new TextAnalyticsRequestOptions().setIncludeStatistics(true));
}
void recognizeBatchLinkedEntitiesShowStatsRunner(
BiConsumer<List<TextDocumentInput>, TextAnalyticsRequestOptions> testRunner) {
TextAnalyticsRequestOptions options = new TextAnalyticsRequestOptions().setIncludeStatistics(true);
testRunner.accept(TestUtils.getTextDocumentInputs(LINKED_ENTITY_INPUTS), options);
}
void recognizeLinkedLanguageHintRunner(BiConsumer<List<String>, String> testRunner) {
testRunner.accept(LINKED_ENTITY_INPUTS, "en");
}
void recognizeLinkedStringInputRunner(Consumer<List<String>> testRunner) {
testRunner.accept(LINKED_ENTITY_INPUTS);
}
void recognizeBatchLinkedEntityRunner(Consumer<List<TextDocumentInput>> testRunner) {
testRunner.accept(TestUtils.getTextDocumentInputs(LINKED_ENTITY_INPUTS));
}
void recognizeBatchLinkedEntityDuplicateIdRunner(Consumer<List<TextDocumentInput>> testRunner) {
testRunner.accept(getDuplicateTextDocumentInputs());
}
void recognizeLinkedEntitiesTooManyDocumentsRunner(
Consumer<List<String>> testRunner) {
final String documentInput = LINKED_ENTITY_INPUTS.get(0);
testRunner.accept(
Arrays.asList(documentInput, documentInput, documentInput, documentInput, documentInput, documentInput));
}
void extractKeyPhrasesForSingleTextInputRunner(Consumer<String> testRunner) {
testRunner.accept(KEY_PHRASE_INPUTS.get(1));
};
void extractBatchStringKeyPhrasesShowStatsRunner(BiConsumer<List<String>, TextAnalyticsRequestOptions> testRunner) {
testRunner.accept(KEY_PHRASE_INPUTS, new TextAnalyticsRequestOptions().setIncludeStatistics(true));
}
void extractBatchKeyPhrasesShowStatsRunner(
BiConsumer<List<TextDocumentInput>, TextAnalyticsRequestOptions> testRunner) {
final List<TextDocumentInput> textDocumentInputs = TestUtils.getTextDocumentInputs(KEY_PHRASE_INPUTS);
TextAnalyticsRequestOptions options = new TextAnalyticsRequestOptions().setIncludeStatistics(true);
testRunner.accept(textDocumentInputs, options);
}
void extractKeyPhrasesLanguageHintRunner(BiConsumer<List<String>, String> testRunner) {
testRunner.accept(KEY_PHRASE_INPUTS, "en");
}
void extractKeyPhrasesStringInputRunner(Consumer<List<String>> testRunner) {
testRunner.accept(KEY_PHRASE_INPUTS);
}
void extractBatchKeyPhrasesRunner(Consumer<List<TextDocumentInput>> testRunner) {
testRunner.accept(TestUtils.getTextDocumentInputs(KEY_PHRASE_INPUTS));
}
void extractBatchKeyPhrasesDuplicateIdRunner(Consumer<List<TextDocumentInput>> testRunner) {
testRunner.accept(getDuplicateTextDocumentInputs());
}
void extractKeyPhrasesWarningRunner(Consumer<String> testRunner) {
testRunner.accept(TOO_LONG_INPUT);
}
void extractKeyPhrasesBatchWarningRunner(Consumer<List<TextDocumentInput>> testRunner) {
testRunner.accept(getWarningsTextDocumentInputs());
}
void analyzeSentimentLanguageHintRunner(BiConsumer<List<String>, String> testRunner) {
testRunner.accept(SENTIMENT_INPUTS, "en");
}
void analyzeSentimentStringInputRunner(Consumer<List<String>> testRunner) {
testRunner.accept(SENTIMENT_INPUTS);
}
void analyzeBatchSentimentRunner(Consumer<List<TextDocumentInput>> testRunner) {
testRunner.accept(TestUtils.getTextDocumentInputs(SENTIMENT_INPUTS));
}
void analyzeBatchSentimentDuplicateIdRunner(Consumer<List<TextDocumentInput>> testRunner) {
testRunner.accept(getDuplicateTextDocumentInputs());
}
void analyzeBatchStringSentimentShowStatsRunner(BiConsumer<List<String>, TextAnalyticsRequestOptions> testRunner) {
testRunner.accept(SENTIMENT_INPUTS, new TextAnalyticsRequestOptions().setIncludeStatistics(true));
}
void analyzeBatchSentimentShowStatsRunner(
BiConsumer<List<TextDocumentInput>, TextAnalyticsRequestOptions> testRunner) {
final List<TextDocumentInput> textDocumentInputs = TestUtils.getTextDocumentInputs(SENTIMENT_INPUTS);
TextAnalyticsRequestOptions options = new TextAnalyticsRequestOptions().setIncludeStatistics(true);
testRunner.accept(textDocumentInputs, options);
}
void emptyTextRunner(Consumer<String> testRunner) {
testRunner.accept("");
}
void faultyTextRunner(Consumer<String> testRunner) {
testRunner.accept("!@
}
String getEndpoint() {
return interceptorManager.isPlaybackMode()
? "https:
: Configuration.getGlobalConfiguration().get("AZURE_TEXT_ANALYTICS_ENDPOINT");
}
TextAnalyticsClientBuilder getTextAnalyticsAsyncClientBuilder(HttpClient httpClient,
TextAnalyticsServiceVersion serviceVersion) {
TextAnalyticsClientBuilder builder = new TextAnalyticsClientBuilder()
.endpoint(getEndpoint())
.httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient)
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
.serviceVersion(serviceVersion);
if (getTestMode() == TestMode.RECORD) {
builder.addPolicy(interceptorManager.getRecordPolicy());
}
if (getTestMode() == TestMode.PLAYBACK) {
builder.credential(new AzureKeyCredential(FAKE_API_KEY));
} else {
builder.credential(new DefaultAzureCredentialBuilder().build());
}
return builder;
}
static void validateDetectLanguageResultCollectionWithResponse(boolean showStatistics,
DetectLanguageResultCollection expected,
int expectedStatusCode,
Response<DetectLanguageResultCollection> response) {
assertNotNull(response);
assertEquals(expectedStatusCode, response.getStatusCode());
validateDetectLanguageResultCollection(showStatistics, expected, response.getValue());
}
static void validateDetectLanguageResultCollection(boolean showStatistics,
DetectLanguageResultCollection expected,
DetectLanguageResultCollection actual) {
validateTextAnalyticsResult(showStatistics, expected, actual, (expectedItem, actualItem) ->
validatePrimaryLanguage(expectedItem.getPrimaryLanguage(), actualItem.getPrimaryLanguage()));
}
static void validateCategorizedEntitiesResultCollectionWithResponse(boolean showStatistics,
RecognizeEntitiesResultCollection expected,
int expectedStatusCode, Response<RecognizeEntitiesResultCollection> response) {
assertNotNull(response);
assertEquals(expectedStatusCode, response.getStatusCode());
validateCategorizedEntitiesResultCollection(showStatistics, expected, response.getValue());
}
static void validateCategorizedEntitiesResultCollection(boolean showStatistics,
RecognizeEntitiesResultCollection expected,
RecognizeEntitiesResultCollection actual) {
validateTextAnalyticsResult(showStatistics, expected, actual, (expectedItem, actualItem) ->
validateCategorizedEntities(
expectedItem.getEntities().stream().collect(Collectors.toList()),
actualItem.getEntities().stream().collect(Collectors.toList())));
}
static void validateLinkedEntitiesResultCollectionWithResponse(boolean showStatistics,
RecognizeLinkedEntitiesResultCollection expected,
int expectedStatusCode, Response<RecognizeLinkedEntitiesResultCollection> response) {
assertNotNull(response);
assertEquals(expectedStatusCode, response.getStatusCode());
validateLinkedEntitiesResultCollection(showStatistics, expected, response.getValue());
}
static void validateLinkedEntitiesResultCollection(boolean showStatistics,
RecognizeLinkedEntitiesResultCollection expected,
RecognizeLinkedEntitiesResultCollection actual) {
validateTextAnalyticsResult(showStatistics, expected, actual, (expectedItem, actualItem) ->
validateLinkedEntities(
expectedItem.getEntities().stream().collect(Collectors.toList()),
actualItem.getEntities().stream().collect(Collectors.toList())));
}
static void validateExtractKeyPhrasesResultCollectionWithResponse(boolean showStatistics,
ExtractKeyPhrasesResultCollection expected,
int expectedStatusCode, Response<ExtractKeyPhrasesResultCollection> response) {
assertNotNull(response);
assertEquals(expectedStatusCode, response.getStatusCode());
validateExtractKeyPhrasesResultCollection(showStatistics, expected, response.getValue());
}
static void validateExtractKeyPhrasesResultCollection(boolean showStatistics,
ExtractKeyPhrasesResultCollection expected,
ExtractKeyPhrasesResultCollection actual) {
validateTextAnalyticsResult(showStatistics, expected, actual, (expectedItem, actualItem) ->
validateKeyPhrases(
expectedItem.getKeyPhrases().stream().collect(Collectors.toList()),
actualItem.getKeyPhrases().stream().collect(Collectors.toList())));
}
static void validateSentimentResultCollectionWithResponse(boolean showStatistics,
AnalyzeSentimentResultCollection expected,
int expectedStatusCode, Response<AnalyzeSentimentResultCollection> response) {
assertNotNull(response);
assertEquals(expectedStatusCode, response.getStatusCode());
validateSentimentResultCollection(showStatistics, expected, response.getValue());
}
static void validateSentimentResultCollection(boolean showStatistics,
AnalyzeSentimentResultCollection expected,
AnalyzeSentimentResultCollection actual) {
validateTextAnalyticsResult(showStatistics, expected, actual, (expectedItem, actualItem) ->
validateAnalyzedSentiment(expectedItem.getDocumentSentiment(), actualItem.getDocumentSentiment()));
}
/**
* Helper method to validate a single detected language.
*
* @param expectedLanguage detectedLanguage returned by the service.
* @param actualLanguage detectedLanguage returned by the API.
*/
/**
* Helper method to validate a single categorized entity.
*
* @param expectedCategorizedEntity CategorizedEntity returned by the service.
* @param actualCategorizedEntity CategorizedEntity returned by the API.
*/
static void validateCategorizedEntity(
CategorizedEntity expectedCategorizedEntity, CategorizedEntity actualCategorizedEntity) {
assertEquals(expectedCategorizedEntity.getSubcategory(), actualCategorizedEntity.getSubcategory());
assertEquals(expectedCategorizedEntity.getText(), actualCategorizedEntity.getText());
assertEquals(expectedCategorizedEntity.getOffset(), actualCategorizedEntity.getOffset());
assertEquals(expectedCategorizedEntity.getLength(), actualCategorizedEntity.getLength());
assertEquals(expectedCategorizedEntity.getCategory(), actualCategorizedEntity.getCategory());
assertNotNull(actualCategorizedEntity.getConfidenceScore());
}
/**
* Helper method to validate a single linked entity.
*
* @param expectedLinkedEntity LinkedEntity returned by the service.
* @param actualLinkedEntity LinkedEntity returned by the API.
*/
static void validateLinkedEntity(LinkedEntity expectedLinkedEntity, LinkedEntity actualLinkedEntity) {
assertEquals(expectedLinkedEntity.getName(), actualLinkedEntity.getName());
assertEquals(expectedLinkedEntity.getDataSource(), actualLinkedEntity.getDataSource());
assertEquals(expectedLinkedEntity.getLanguage(), actualLinkedEntity.getLanguage());
assertEquals(expectedLinkedEntity.getUrl(), actualLinkedEntity.getUrl());
assertEquals(expectedLinkedEntity.getDataSourceEntityId(), actualLinkedEntity.getDataSourceEntityId());
validateLinkedEntityMatches(expectedLinkedEntity.getMatches().stream().collect(Collectors.toList()),
actualLinkedEntity.getMatches().stream().collect(Collectors.toList()));
}
/**
* Helper method to validate a single key phrase.
*
* @param expectedKeyPhrases key phrases returned by the service.
* @param actualKeyPhrases key phrases returned by the API.
*/
static void validateKeyPhrases(List<String> expectedKeyPhrases, List<String> actualKeyPhrases) {
assertEquals(expectedKeyPhrases.size(), actualKeyPhrases.size());
Collections.sort(expectedKeyPhrases);
Collections.sort(actualKeyPhrases);
for (int i = 0; i < expectedKeyPhrases.size(); i++) {
assertEquals(expectedKeyPhrases.get(i), actualKeyPhrases.get(i));
}
}
/**
* Helper method to validate the list of categorized entities.
*
* @param expectedCategorizedEntityList categorizedEntities returned by the service.
* @param actualCategorizedEntityList categorizedEntities returned by the API.
*/
static void validateCategorizedEntities(List<CategorizedEntity> expectedCategorizedEntityList,
List<CategorizedEntity> actualCategorizedEntityList) {
assertEquals(expectedCategorizedEntityList.size(), actualCategorizedEntityList.size());
expectedCategorizedEntityList.sort(Comparator.comparing(CategorizedEntity::getText));
actualCategorizedEntityList.sort(Comparator.comparing(CategorizedEntity::getText));
for (int i = 0; i < expectedCategorizedEntityList.size(); i++) {
CategorizedEntity expectedCategorizedEntity = expectedCategorizedEntityList.get(i);
CategorizedEntity actualCategorizedEntity = actualCategorizedEntityList.get(i);
validateCategorizedEntity(expectedCategorizedEntity, actualCategorizedEntity);
}
}
/**
* Helper method to validate the list of linked entities.
*
* @param expectedLinkedEntityList linkedEntities returned by the service.
* @param actualLinkedEntityList linkedEntities returned by the API.
*/
static void validateLinkedEntities(List<LinkedEntity> expectedLinkedEntityList,
List<LinkedEntity> actualLinkedEntityList) {
assertEquals(expectedLinkedEntityList.size(), actualLinkedEntityList.size());
expectedLinkedEntityList.sort(Comparator.comparing(LinkedEntity::getName));
actualLinkedEntityList.sort(Comparator.comparing(LinkedEntity::getName));
for (int i = 0; i < expectedLinkedEntityList.size(); i++) {
LinkedEntity expectedLinkedEntity = expectedLinkedEntityList.get(i);
LinkedEntity actualLinkedEntity = actualLinkedEntityList.get(i);
validateLinkedEntity(expectedLinkedEntity, actualLinkedEntity);
}
}
/**
* Helper method to validate the list of sentence sentiment. Can't really validate score numbers because it
* frequently changed by background model computation.
*
* @param expectedSentimentList a list of analyzed sentence sentiment returned by the service.
* @param actualSentimentList a list of analyzed sentence sentiment returned by the API.
*/
static void validateAnalyzedSentenceSentiment(List<SentenceSentiment> expectedSentimentList,
List<SentenceSentiment> actualSentimentList) {
assertEquals(expectedSentimentList.size(), actualSentimentList.size());
for (int i = 0; i < expectedSentimentList.size(); i++) {
validateSentenceSentiment(expectedSentimentList.get(i), actualSentimentList.get(i));
}
}
/**
* Helper method to validate one pair of analyzed sentiments. Can't really validate score numbers because it
* frequently changed by background model computation.
*
* @param expectedSentiment analyzed sentence sentiment returned by the service.
* @param actualSentiment analyzed sentence sentiment returned by the API.
*/
static void validateSentenceSentiment(SentenceSentiment expectedSentiment, SentenceSentiment actualSentiment) {
assertEquals(expectedSentiment.getSentiment(), actualSentiment.getSentiment());
}
/**
* Helper method to validate one pair of analyzed sentiments. Can't really validate score numbers because it
* frequently changed by background model computation.
*
* @param expectedSentiment analyzed document sentiment returned by the service.
* @param actualSentiment analyzed document sentiment returned by the API.
*/
static void validateAnalyzedSentiment(DocumentSentiment expectedSentiment, DocumentSentiment actualSentiment) {
assertEquals(expectedSentiment.getSentiment(), actualSentiment.getSentiment());
validateAnalyzedSentenceSentiment(expectedSentiment.getSentences().stream().collect(Collectors.toList()),
expectedSentiment.getSentences().stream().collect(Collectors.toList()));
}
/**
* Helper method to verify {@link TextAnalyticsResult documents} returned in a batch request.
*/
static <T extends TextAnalyticsResult, H extends IterableStream<T>> void validateTextAnalyticsResult(
boolean showStatistics, H expectedResults, H actualResults, BiConsumer<T, T> additionalAssertions) {
final Map<String, T> expected = expectedResults.stream().collect(
Collectors.toMap(TextAnalyticsResult::getId, r -> r));
final Map<String, T> actual = actualResults.stream().collect(
Collectors.toMap(TextAnalyticsResult::getId, r -> r));
assertEquals(expected.size(), actual.size());
if (showStatistics) {
if (expectedResults instanceof AnalyzeSentimentResultCollection) {
validateBatchStatistics(((AnalyzeSentimentResultCollection) expectedResults).getStatistics(),
((AnalyzeSentimentResultCollection) actualResults).getStatistics());
} else if (expectedResults instanceof DetectLanguageResultCollection) {
validateBatchStatistics(((DetectLanguageResultCollection) expectedResults).getStatistics(),
((DetectLanguageResultCollection) actualResults).getStatistics());
} else if (expectedResults instanceof ExtractKeyPhrasesResultCollection) {
validateBatchStatistics(((ExtractKeyPhrasesResultCollection) expectedResults).getStatistics(),
((ExtractKeyPhrasesResultCollection) actualResults).getStatistics());
} else if (expectedResults instanceof RecognizeEntitiesResultCollection) {
validateBatchStatistics(((RecognizeEntitiesResultCollection) expectedResults).getStatistics(),
((RecognizeEntitiesResultCollection) actualResults).getStatistics());
} else if (expectedResults instanceof RecognizeLinkedEntitiesResultCollection) {
validateBatchStatistics(((RecognizeLinkedEntitiesResultCollection) expectedResults).getStatistics(),
((RecognizeLinkedEntitiesResultCollection) actualResults).getStatistics());
}
}
expected.forEach((key, expectedValue) -> {
T actualValue = actual.get(key);
assertNotNull(actualValue);
if (showStatistics) {
validateDocumentStatistics(expectedValue.getStatistics(), actualValue.getStatistics());
}
if (expectedValue.getError() == null) {
assertNull(actualValue.getError());
} else {
assertNotNull(actualValue.getError());
assertEquals(expectedValue.getError().getErrorCode(), actualValue.getError().getErrorCode());
validateErrorDocument(expectedValue.getError(), actualValue.getError());
}
additionalAssertions.accept(expectedValue, actualValue);
});
}
/**
* Helper method to verify TextBatchStatistics.
*
* @param expectedStatistics the expected value for TextBatchStatistics.
* @param actualStatistics the value returned by API.
*/
private static void validateBatchStatistics(TextDocumentBatchStatistics expectedStatistics,
TextDocumentBatchStatistics actualStatistics) {
assertEquals(expectedStatistics.getDocumentCount(), actualStatistics.getDocumentCount());
assertEquals(expectedStatistics.getInvalidDocumentCount(), actualStatistics.getInvalidDocumentCount());
assertEquals(expectedStatistics.getValidDocumentCount(), actualStatistics.getValidDocumentCount());
assertEquals(expectedStatistics.getTransactionCount(), actualStatistics.getTransactionCount());
}
/**
* Helper method to verify TextDocumentStatistics.
*
* @param expected the expected value for TextDocumentStatistics.
* @param actual the value returned by API.
*/
private static void validateDocumentStatistics(TextDocumentStatistics expected, TextDocumentStatistics actual) {
assertEquals(expected.getCharacterCount(), actual.getCharacterCount());
assertEquals(expected.getTransactionCount(), actual.getTransactionCount());
}
/**
* Helper method to verify LinkedEntityMatches.
*
* @param expectedLinkedEntityMatches the expected value for LinkedEntityMatches.
* @param actualLinkedEntityMatches the value returned by API.
*/
private static void validateLinkedEntityMatches(List<LinkedEntityMatch> expectedLinkedEntityMatches,
List<LinkedEntityMatch> actualLinkedEntityMatches) {
assertEquals(expectedLinkedEntityMatches.size(), actualLinkedEntityMatches.size());
expectedLinkedEntityMatches.sort(Comparator.comparing(LinkedEntityMatch::getText));
actualLinkedEntityMatches.sort(Comparator.comparing(LinkedEntityMatch::getText));
for (int i = 0; i < expectedLinkedEntityMatches.size(); i++) {
LinkedEntityMatch expectedLinkedEntity = expectedLinkedEntityMatches.get(i);
LinkedEntityMatch actualLinkedEntity = actualLinkedEntityMatches.get(i);
assertEquals(expectedLinkedEntity.getText(), actualLinkedEntity.getText());
assertEquals(expectedLinkedEntity.getOffset(), actualLinkedEntity.getOffset());
assertEquals(expectedLinkedEntity.getLength(), actualLinkedEntity.getLength());
assertNotNull(actualLinkedEntity.getConfidenceScore());
}
}
/**
* Helper method to verify the error document.
*
* @param expectedError the Error returned from the service.
* @param actualError the Error returned from the API.
*/
static void validateErrorDocument(TextAnalyticsError expectedError, TextAnalyticsError actualError) {
assertEquals(expectedError.getErrorCode(), actualError.getErrorCode());
assertEquals(expectedError.getMessage(), actualError.getMessage());
assertEquals(expectedError.getTarget(), actualError.getTarget());
}
} | class TextAnalyticsClientTestBase extends TestBase {
static final String BATCH_ERROR_EXCEPTION_MESSAGE = "Error in accessing the property on document id: 2, when RecognizeEntitiesResult returned with an error: Document text is empty. ErrorCodeValue: {invalidDocument}";
static final String EXCEEDED_ALLOWED_DOCUMENTS_LIMITS_MESSAGE = "The number of documents in the request have exceeded the data limitations. See https:
static final String INVALID_COUNTRY_HINT_EXPECTED_EXCEPTION_MESSAGE = "Country hint is not valid. Please specify an ISO 3166-1 alpha-2 two letter country code. ErrorCodeValue: {invalidCountryHint}";
static final String INVALID_DOCUMENT_BATCH = "invalidDocumentBatch";
static final String INVALID_DOCUMENT_BATCH_NPE_MESSAGE = "'documents' cannot be null.";
static final String INVALID_DOCUMENT_EMPTY_LIST_EXCEPTION_MESSAGE = "'documents' cannot be empty.";
static final String INVALID_DOCUMENT_EXPECTED_EXCEPTION_MESSAGE = "Document text is empty. ErrorCodeValue: {invalidDocument}";
static final String INVALID_DOCUMENT_NPE_MESSAGE = "'document' cannot be null.";
static final String WARNING_TOO_LONG_DOCUMENT_INPUT_MESSAGE = "The document contains very long words (longer than 64 characters). These words will be truncated and may result in unreliable model predictions.";
@Test
abstract void detectSingleTextLanguage(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void detectLanguageEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void detectLanguageFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void detectLanguagesBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void detectLanguagesBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void detectLanguagesBatchListCountryHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeEntitiesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeEntitiesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeEntitiesForFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeEntitiesBatchInputSingleError(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeEntitiesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeEntitiesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeEntitiesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeLinkedEntitiesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeLinkedEntitiesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeLinkedEntitiesForFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeLinkedEntitiesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeLinkedEntitiesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void recognizeLinkedEntitiesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void extractKeyPhrasesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void extractKeyPhrasesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void extractKeyPhrasesForFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void extractKeyPhrasesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void extractKeyPhrasesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void extractKeyPhrasesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void extractKeyPhrasesWarning(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void extractKeyPhrasesBatchWarning(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void analyzeSentimentForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void analyzeSentimentForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void analyzeSentimentForFaultyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void analyzeSentimentForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void analyzeSentimentForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void analyzeSentimentForBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
@Test
abstract void analyzeSentimentForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion);
void detectLanguageShowStatisticsRunner(BiConsumer<List<DetectLanguageInput>,
TextAnalyticsRequestOptions> testRunner) {
final List<DetectLanguageInput> detectLanguageInputs = TestUtils.getDetectLanguageInputs();
TextAnalyticsRequestOptions options = new TextAnalyticsRequestOptions().setIncludeStatistics(true);
testRunner.accept(detectLanguageInputs, options);
}
void detectLanguageDuplicateIdRunner(BiConsumer<List<DetectLanguageInput>,
TextAnalyticsRequestOptions> testRunner) {
testRunner.accept(TestUtils.getDuplicateIdDetectLanguageInputs(), null);
}
void detectLanguagesCountryHintRunner(BiConsumer<List<String>, String> testRunner) {
testRunner.accept(DETECT_LANGUAGE_INPUTS, "US");
}
void detectLanguagesBatchListCountryHintWithOptionsRunner(BiConsumer<List<String>,
TextAnalyticsRequestOptions> testRunner) {
TextAnalyticsRequestOptions options = new TextAnalyticsRequestOptions().setIncludeStatistics(true);
testRunner.accept(TestUtils.DETECT_LANGUAGE_INPUTS, options);
}
void detectLanguageStringInputRunner(Consumer<List<String>> testRunner) {
testRunner.accept(DETECT_LANGUAGE_INPUTS);
}
void detectLanguageRunner(Consumer<List<DetectLanguageInput>> testRunner) {
testRunner.accept(TestUtils.getDetectLanguageInputs());
}
void detectSingleTextLanguageRunner(Consumer<String> testRunner) {
testRunner.accept(DETECT_LANGUAGE_INPUTS.get(0));
}
void detectLanguageInvalidCountryHintRunner(BiConsumer<String, String> testRunner) {
testRunner.accept(DETECT_LANGUAGE_INPUTS.get(1), "en");
}
void detectLanguageEmptyCountryHintRunner(BiConsumer<String, String> testRunner) {
testRunner.accept(DETECT_LANGUAGE_INPUTS.get(1), "");
}
void detectLanguageNoneCountryHintRunner(BiConsumer<String, String> testRunner) {
testRunner.accept(DETECT_LANGUAGE_INPUTS.get(1), "none");
}
void recognizeCategorizedEntitiesForSingleTextInputRunner(Consumer<String> testRunner) {
testRunner.accept(CATEGORIZED_ENTITY_INPUTS.get(0));
}
void recognizeCategorizedEntityStringInputRunner(Consumer<List<String>> testRunner) {
testRunner.accept(CATEGORIZED_ENTITY_INPUTS);
}
void recognizeCategorizedEntityDuplicateIdRunner(Consumer<List<TextDocumentInput>> testRunner) {
testRunner.accept(getDuplicateTextDocumentInputs());
}
void recognizeCategorizedEntitiesLanguageHintRunner(BiConsumer<List<String>, String> testRunner) {
testRunner.accept(CATEGORIZED_ENTITY_INPUTS, "en");
}
void recognizeBatchCategorizedEntitySingleErrorRunner(Consumer<List<TextDocumentInput>> testRunner) {
List<TextDocumentInput> inputs = Collections.singletonList(new TextDocumentInput("2", " "));
testRunner.accept(inputs);
}
void recognizeBatchCategorizedEntityRunner(Consumer<List<TextDocumentInput>> testRunner) {
testRunner.accept(TestUtils.getTextDocumentInputs(CATEGORIZED_ENTITY_INPUTS));
}
void recognizeBatchCategorizedEntitiesShowStatsRunner(
BiConsumer<List<TextDocumentInput>, TextAnalyticsRequestOptions> testRunner) {
final List<TextDocumentInput> textDocumentInputs = TestUtils.getTextDocumentInputs(CATEGORIZED_ENTITY_INPUTS);
TextAnalyticsRequestOptions options = new TextAnalyticsRequestOptions().setIncludeStatistics(true);
testRunner.accept(textDocumentInputs, options);
}
void recognizeStringBatchCategorizedEntitiesShowStatsRunner(
BiConsumer<List<String>, TextAnalyticsRequestOptions> testRunner) {
testRunner.accept(CATEGORIZED_ENTITY_INPUTS, new TextAnalyticsRequestOptions().setIncludeStatistics(true));
}
void recognizeEntitiesTooManyDocumentsRunner(
Consumer<List<String>> testRunner) {
final String documentInput = CATEGORIZED_ENTITY_INPUTS.get(0);
testRunner.accept(
Arrays.asList(documentInput, documentInput, documentInput, documentInput, documentInput, documentInput));
}
void recognizeLinkedEntitiesForSingleTextInputRunner(Consumer<String> testRunner) {
testRunner.accept(LINKED_ENTITY_INPUTS.get(0));
}
void recognizeBatchStringLinkedEntitiesShowStatsRunner(
BiConsumer<List<String>, TextAnalyticsRequestOptions> testRunner) {
testRunner.accept(LINKED_ENTITY_INPUTS, new TextAnalyticsRequestOptions().setIncludeStatistics(true));
}
void recognizeBatchLinkedEntitiesShowStatsRunner(
BiConsumer<List<TextDocumentInput>, TextAnalyticsRequestOptions> testRunner) {
TextAnalyticsRequestOptions options = new TextAnalyticsRequestOptions().setIncludeStatistics(true);
testRunner.accept(TestUtils.getTextDocumentInputs(LINKED_ENTITY_INPUTS), options);
}
void recognizeLinkedLanguageHintRunner(BiConsumer<List<String>, String> testRunner) {
testRunner.accept(LINKED_ENTITY_INPUTS, "en");
}
void recognizeLinkedStringInputRunner(Consumer<List<String>> testRunner) {
testRunner.accept(LINKED_ENTITY_INPUTS);
}
void recognizeBatchLinkedEntityRunner(Consumer<List<TextDocumentInput>> testRunner) {
testRunner.accept(TestUtils.getTextDocumentInputs(LINKED_ENTITY_INPUTS));
}
void recognizeBatchLinkedEntityDuplicateIdRunner(Consumer<List<TextDocumentInput>> testRunner) {
testRunner.accept(getDuplicateTextDocumentInputs());
}
void recognizeLinkedEntitiesTooManyDocumentsRunner(
Consumer<List<String>> testRunner) {
final String documentInput = LINKED_ENTITY_INPUTS.get(0);
testRunner.accept(
Arrays.asList(documentInput, documentInput, documentInput, documentInput, documentInput, documentInput));
}
void extractKeyPhrasesForSingleTextInputRunner(Consumer<String> testRunner) {
testRunner.accept(KEY_PHRASE_INPUTS.get(1));
};
void extractBatchStringKeyPhrasesShowStatsRunner(BiConsumer<List<String>, TextAnalyticsRequestOptions> testRunner) {
testRunner.accept(KEY_PHRASE_INPUTS, new TextAnalyticsRequestOptions().setIncludeStatistics(true));
}
void extractBatchKeyPhrasesShowStatsRunner(
BiConsumer<List<TextDocumentInput>, TextAnalyticsRequestOptions> testRunner) {
final List<TextDocumentInput> textDocumentInputs = TestUtils.getTextDocumentInputs(KEY_PHRASE_INPUTS);
TextAnalyticsRequestOptions options = new TextAnalyticsRequestOptions().setIncludeStatistics(true);
testRunner.accept(textDocumentInputs, options);
}
void extractKeyPhrasesLanguageHintRunner(BiConsumer<List<String>, String> testRunner) {
testRunner.accept(KEY_PHRASE_INPUTS, "en");
}
void extractKeyPhrasesStringInputRunner(Consumer<List<String>> testRunner) {
testRunner.accept(KEY_PHRASE_INPUTS);
}
void extractBatchKeyPhrasesRunner(Consumer<List<TextDocumentInput>> testRunner) {
testRunner.accept(TestUtils.getTextDocumentInputs(KEY_PHRASE_INPUTS));
}
void extractBatchKeyPhrasesDuplicateIdRunner(Consumer<List<TextDocumentInput>> testRunner) {
testRunner.accept(getDuplicateTextDocumentInputs());
}
void extractKeyPhrasesWarningRunner(Consumer<String> testRunner) {
testRunner.accept(TOO_LONG_INPUT);
}
void extractKeyPhrasesBatchWarningRunner(Consumer<List<TextDocumentInput>> testRunner) {
testRunner.accept(getWarningsTextDocumentInputs());
}
void analyzeSentimentLanguageHintRunner(BiConsumer<List<String>, String> testRunner) {
testRunner.accept(SENTIMENT_INPUTS, "en");
}
void analyzeSentimentStringInputRunner(Consumer<List<String>> testRunner) {
testRunner.accept(SENTIMENT_INPUTS);
}
void analyzeBatchSentimentRunner(Consumer<List<TextDocumentInput>> testRunner) {
testRunner.accept(TestUtils.getTextDocumentInputs(SENTIMENT_INPUTS));
}
void analyzeBatchSentimentDuplicateIdRunner(Consumer<List<TextDocumentInput>> testRunner) {
testRunner.accept(getDuplicateTextDocumentInputs());
}
void analyzeBatchStringSentimentShowStatsRunner(BiConsumer<List<String>, TextAnalyticsRequestOptions> testRunner) {
testRunner.accept(SENTIMENT_INPUTS, new TextAnalyticsRequestOptions().setIncludeStatistics(true));
}
void analyzeBatchSentimentShowStatsRunner(
BiConsumer<List<TextDocumentInput>, TextAnalyticsRequestOptions> testRunner) {
final List<TextDocumentInput> textDocumentInputs = TestUtils.getTextDocumentInputs(SENTIMENT_INPUTS);
TextAnalyticsRequestOptions options = new TextAnalyticsRequestOptions().setIncludeStatistics(true);
testRunner.accept(textDocumentInputs, options);
}
void emptyTextRunner(Consumer<String> testRunner) {
testRunner.accept("");
}
void faultyTextRunner(Consumer<String> testRunner) {
testRunner.accept("!@
}
String getEndpoint() {
return interceptorManager.isPlaybackMode()
? "https:
: Configuration.getGlobalConfiguration().get("AZURE_TEXT_ANALYTICS_ENDPOINT");
}
TextAnalyticsClientBuilder getTextAnalyticsAsyncClientBuilder(HttpClient httpClient,
TextAnalyticsServiceVersion serviceVersion) {
TextAnalyticsClientBuilder builder = new TextAnalyticsClientBuilder()
.endpoint(getEndpoint())
.httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient)
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
.serviceVersion(serviceVersion);
if (getTestMode() == TestMode.RECORD) {
builder.addPolicy(interceptorManager.getRecordPolicy());
}
if (getTestMode() == TestMode.PLAYBACK) {
builder.credential(new AzureKeyCredential(FAKE_API_KEY));
} else {
builder.credential(new DefaultAzureCredentialBuilder().build());
}
return builder;
}
static void validateDetectLanguageResultCollectionWithResponse(boolean showStatistics,
DetectLanguageResultCollection expected,
int expectedStatusCode,
Response<DetectLanguageResultCollection> response) {
assertNotNull(response);
assertEquals(expectedStatusCode, response.getStatusCode());
validateDetectLanguageResultCollection(showStatistics, expected, response.getValue());
}
static void validateDetectLanguageResultCollection(boolean showStatistics,
DetectLanguageResultCollection expected,
DetectLanguageResultCollection actual) {
validateTextAnalyticsResult(showStatistics, expected, actual, (expectedItem, actualItem) ->
validatePrimaryLanguage(expectedItem.getPrimaryLanguage(), actualItem.getPrimaryLanguage()));
}
static void validateCategorizedEntitiesResultCollectionWithResponse(boolean showStatistics,
RecognizeEntitiesResultCollection expected,
int expectedStatusCode, Response<RecognizeEntitiesResultCollection> response) {
assertNotNull(response);
assertEquals(expectedStatusCode, response.getStatusCode());
validateCategorizedEntitiesResultCollection(showStatistics, expected, response.getValue());
}
static void validateCategorizedEntitiesResultCollection(boolean showStatistics,
RecognizeEntitiesResultCollection expected,
RecognizeEntitiesResultCollection actual) {
validateTextAnalyticsResult(showStatistics, expected, actual, (expectedItem, actualItem) ->
validateCategorizedEntities(
expectedItem.getEntities().stream().collect(Collectors.toList()),
actualItem.getEntities().stream().collect(Collectors.toList())));
}
static void validateLinkedEntitiesResultCollectionWithResponse(boolean showStatistics,
RecognizeLinkedEntitiesResultCollection expected,
int expectedStatusCode, Response<RecognizeLinkedEntitiesResultCollection> response) {
assertNotNull(response);
assertEquals(expectedStatusCode, response.getStatusCode());
validateLinkedEntitiesResultCollection(showStatistics, expected, response.getValue());
}
static void validateLinkedEntitiesResultCollection(boolean showStatistics,
RecognizeLinkedEntitiesResultCollection expected,
RecognizeLinkedEntitiesResultCollection actual) {
validateTextAnalyticsResult(showStatistics, expected, actual, (expectedItem, actualItem) ->
validateLinkedEntities(
expectedItem.getEntities().stream().collect(Collectors.toList()),
actualItem.getEntities().stream().collect(Collectors.toList())));
}
static void validateExtractKeyPhrasesResultCollectionWithResponse(boolean showStatistics,
ExtractKeyPhrasesResultCollection expected,
int expectedStatusCode, Response<ExtractKeyPhrasesResultCollection> response) {
assertNotNull(response);
assertEquals(expectedStatusCode, response.getStatusCode());
validateExtractKeyPhrasesResultCollection(showStatistics, expected, response.getValue());
}
static void validateExtractKeyPhrasesResultCollection(boolean showStatistics,
ExtractKeyPhrasesResultCollection expected,
ExtractKeyPhrasesResultCollection actual) {
validateTextAnalyticsResult(showStatistics, expected, actual, (expectedItem, actualItem) ->
validateKeyPhrases(
expectedItem.getKeyPhrases().stream().collect(Collectors.toList()),
actualItem.getKeyPhrases().stream().collect(Collectors.toList())));
}
static void validateSentimentResultCollectionWithResponse(boolean showStatistics,
AnalyzeSentimentResultCollection expected,
int expectedStatusCode, Response<AnalyzeSentimentResultCollection> response) {
assertNotNull(response);
assertEquals(expectedStatusCode, response.getStatusCode());
validateSentimentResultCollection(showStatistics, expected, response.getValue());
}
static void validateSentimentResultCollection(boolean showStatistics,
AnalyzeSentimentResultCollection expected,
AnalyzeSentimentResultCollection actual) {
validateTextAnalyticsResult(showStatistics, expected, actual, (expectedItem, actualItem) ->
validateAnalyzedSentiment(expectedItem.getDocumentSentiment(), actualItem.getDocumentSentiment()));
}
/**
* Helper method to validate a single detected language.
*
* @param expectedLanguage detectedLanguage returned by the service.
* @param actualLanguage detectedLanguage returned by the API.
*/
/**
* Helper method to validate a single categorized entity.
*
* @param expectedCategorizedEntity CategorizedEntity returned by the service.
* @param actualCategorizedEntity CategorizedEntity returned by the API.
*/
static void validateCategorizedEntity(
CategorizedEntity expectedCategorizedEntity, CategorizedEntity actualCategorizedEntity) {
assertEquals(expectedCategorizedEntity.getSubcategory(), actualCategorizedEntity.getSubcategory());
assertEquals(expectedCategorizedEntity.getText(), actualCategorizedEntity.getText());
assertEquals(expectedCategorizedEntity.getOffset(), actualCategorizedEntity.getOffset());
assertEquals(expectedCategorizedEntity.getLength(), actualCategorizedEntity.getLength());
assertEquals(expectedCategorizedEntity.getCategory(), actualCategorizedEntity.getCategory());
assertNotNull(actualCategorizedEntity.getConfidenceScore());
}
/**
* Helper method to validate a single linked entity.
*
* @param expectedLinkedEntity LinkedEntity returned by the service.
* @param actualLinkedEntity LinkedEntity returned by the API.
*/
static void validateLinkedEntity(LinkedEntity expectedLinkedEntity, LinkedEntity actualLinkedEntity) {
assertEquals(expectedLinkedEntity.getName(), actualLinkedEntity.getName());
assertEquals(expectedLinkedEntity.getDataSource(), actualLinkedEntity.getDataSource());
assertEquals(expectedLinkedEntity.getLanguage(), actualLinkedEntity.getLanguage());
assertEquals(expectedLinkedEntity.getUrl(), actualLinkedEntity.getUrl());
assertEquals(expectedLinkedEntity.getDataSourceEntityId(), actualLinkedEntity.getDataSourceEntityId());
validateLinkedEntityMatches(expectedLinkedEntity.getMatches().stream().collect(Collectors.toList()),
actualLinkedEntity.getMatches().stream().collect(Collectors.toList()));
}
/**
* Helper method to validate a single key phrase.
*
* @param expectedKeyPhrases key phrases returned by the service.
* @param actualKeyPhrases key phrases returned by the API.
*/
static void validateKeyPhrases(List<String> expectedKeyPhrases, List<String> actualKeyPhrases) {
assertEquals(expectedKeyPhrases.size(), actualKeyPhrases.size());
Collections.sort(expectedKeyPhrases);
Collections.sort(actualKeyPhrases);
for (int i = 0; i < expectedKeyPhrases.size(); i++) {
assertEquals(expectedKeyPhrases.get(i), actualKeyPhrases.get(i));
}
}
/**
* Helper method to validate the list of categorized entities.
*
* @param expectedCategorizedEntityList categorizedEntities returned by the service.
* @param actualCategorizedEntityList categorizedEntities returned by the API.
*/
static void validateCategorizedEntities(List<CategorizedEntity> expectedCategorizedEntityList,
List<CategorizedEntity> actualCategorizedEntityList) {
assertEquals(expectedCategorizedEntityList.size(), actualCategorizedEntityList.size());
expectedCategorizedEntityList.sort(Comparator.comparing(CategorizedEntity::getText));
actualCategorizedEntityList.sort(Comparator.comparing(CategorizedEntity::getText));
for (int i = 0; i < expectedCategorizedEntityList.size(); i++) {
CategorizedEntity expectedCategorizedEntity = expectedCategorizedEntityList.get(i);
CategorizedEntity actualCategorizedEntity = actualCategorizedEntityList.get(i);
validateCategorizedEntity(expectedCategorizedEntity, actualCategorizedEntity);
}
}
/**
* Helper method to validate the list of linked entities.
*
* @param expectedLinkedEntityList linkedEntities returned by the service.
* @param actualLinkedEntityList linkedEntities returned by the API.
*/
static void validateLinkedEntities(List<LinkedEntity> expectedLinkedEntityList,
List<LinkedEntity> actualLinkedEntityList) {
assertEquals(expectedLinkedEntityList.size(), actualLinkedEntityList.size());
expectedLinkedEntityList.sort(Comparator.comparing(LinkedEntity::getName));
actualLinkedEntityList.sort(Comparator.comparing(LinkedEntity::getName));
for (int i = 0; i < expectedLinkedEntityList.size(); i++) {
LinkedEntity expectedLinkedEntity = expectedLinkedEntityList.get(i);
LinkedEntity actualLinkedEntity = actualLinkedEntityList.get(i);
validateLinkedEntity(expectedLinkedEntity, actualLinkedEntity);
}
}
/**
* Helper method to validate the list of sentence sentiment. Can't really validate score numbers because it
* frequently changed by background model computation.
*
* @param expectedSentimentList a list of analyzed sentence sentiment returned by the service.
* @param actualSentimentList a list of analyzed sentence sentiment returned by the API.
*/
static void validateAnalyzedSentenceSentiment(List<SentenceSentiment> expectedSentimentList,
List<SentenceSentiment> actualSentimentList) {
assertEquals(expectedSentimentList.size(), actualSentimentList.size());
for (int i = 0; i < expectedSentimentList.size(); i++) {
validateSentenceSentiment(expectedSentimentList.get(i), actualSentimentList.get(i));
}
}
/**
* Helper method to validate one pair of analyzed sentiments. Can't really validate score numbers because it
* frequently changed by background model computation.
*
* @param expectedSentiment analyzed sentence sentiment returned by the service.
* @param actualSentiment analyzed sentence sentiment returned by the API.
*/
static void validateSentenceSentiment(SentenceSentiment expectedSentiment, SentenceSentiment actualSentiment) {
assertEquals(expectedSentiment.getSentiment(), actualSentiment.getSentiment());
}
/**
* Helper method to validate one pair of analyzed sentiments. Can't really validate score numbers because it
* frequently changed by background model computation.
*
* @param expectedSentiment analyzed document sentiment returned by the service.
* @param actualSentiment analyzed document sentiment returned by the API.
*/
static void validateAnalyzedSentiment(DocumentSentiment expectedSentiment, DocumentSentiment actualSentiment) {
assertEquals(expectedSentiment.getSentiment(), actualSentiment.getSentiment());
validateAnalyzedSentenceSentiment(expectedSentiment.getSentences().stream().collect(Collectors.toList()),
expectedSentiment.getSentences().stream().collect(Collectors.toList()));
}
/**
* Helper method to verify {@link TextAnalyticsResult documents} returned in a batch request.
*/
static <T extends TextAnalyticsResult, H extends IterableStream<T>> void validateTextAnalyticsResult(
boolean showStatistics, H expectedResults, H actualResults, BiConsumer<T, T> additionalAssertions) {
final Map<String, T> expected = expectedResults.stream().collect(
Collectors.toMap(TextAnalyticsResult::getId, r -> r));
final Map<String, T> actual = actualResults.stream().collect(
Collectors.toMap(TextAnalyticsResult::getId, r -> r));
assertEquals(expected.size(), actual.size());
if (showStatistics) {
if (expectedResults instanceof AnalyzeSentimentResultCollection) {
validateBatchStatistics(((AnalyzeSentimentResultCollection) expectedResults).getStatistics(),
((AnalyzeSentimentResultCollection) actualResults).getStatistics());
} else if (expectedResults instanceof DetectLanguageResultCollection) {
validateBatchStatistics(((DetectLanguageResultCollection) expectedResults).getStatistics(),
((DetectLanguageResultCollection) actualResults).getStatistics());
} else if (expectedResults instanceof ExtractKeyPhrasesResultCollection) {
validateBatchStatistics(((ExtractKeyPhrasesResultCollection) expectedResults).getStatistics(),
((ExtractKeyPhrasesResultCollection) actualResults).getStatistics());
} else if (expectedResults instanceof RecognizeEntitiesResultCollection) {
validateBatchStatistics(((RecognizeEntitiesResultCollection) expectedResults).getStatistics(),
((RecognizeEntitiesResultCollection) actualResults).getStatistics());
} else if (expectedResults instanceof RecognizeLinkedEntitiesResultCollection) {
validateBatchStatistics(((RecognizeLinkedEntitiesResultCollection) expectedResults).getStatistics(),
((RecognizeLinkedEntitiesResultCollection) actualResults).getStatistics());
}
}
expected.forEach((key, expectedValue) -> {
T actualValue = actual.get(key);
assertNotNull(actualValue);
if (showStatistics) {
validateDocumentStatistics(expectedValue.getStatistics(), actualValue.getStatistics());
}
if (expectedValue.getError() == null) {
assertNull(actualValue.getError());
} else {
assertNotNull(actualValue.getError());
assertEquals(expectedValue.getError().getErrorCode(), actualValue.getError().getErrorCode());
validateErrorDocument(expectedValue.getError(), actualValue.getError());
}
additionalAssertions.accept(expectedValue, actualValue);
});
}
/**
* Helper method to verify TextBatchStatistics.
*
* @param expectedStatistics the expected value for TextBatchStatistics.
* @param actualStatistics the value returned by API.
*/
private static void validateBatchStatistics(TextDocumentBatchStatistics expectedStatistics,
TextDocumentBatchStatistics actualStatistics) {
assertEquals(expectedStatistics.getDocumentCount(), actualStatistics.getDocumentCount());
assertEquals(expectedStatistics.getInvalidDocumentCount(), actualStatistics.getInvalidDocumentCount());
assertEquals(expectedStatistics.getValidDocumentCount(), actualStatistics.getValidDocumentCount());
assertEquals(expectedStatistics.getTransactionCount(), actualStatistics.getTransactionCount());
}
/**
* Helper method to verify TextDocumentStatistics.
*
* @param expected the expected value for TextDocumentStatistics.
* @param actual the value returned by API.
*/
private static void validateDocumentStatistics(TextDocumentStatistics expected, TextDocumentStatistics actual) {
assertEquals(expected.getCharacterCount(), actual.getCharacterCount());
assertEquals(expected.getTransactionCount(), actual.getTransactionCount());
}
/**
* Helper method to verify LinkedEntityMatches.
*
* @param expectedLinkedEntityMatches the expected value for LinkedEntityMatches.
* @param actualLinkedEntityMatches the value returned by API.
*/
private static void validateLinkedEntityMatches(List<LinkedEntityMatch> expectedLinkedEntityMatches,
List<LinkedEntityMatch> actualLinkedEntityMatches) {
assertEquals(expectedLinkedEntityMatches.size(), actualLinkedEntityMatches.size());
expectedLinkedEntityMatches.sort(Comparator.comparing(LinkedEntityMatch::getText));
actualLinkedEntityMatches.sort(Comparator.comparing(LinkedEntityMatch::getText));
for (int i = 0; i < expectedLinkedEntityMatches.size(); i++) {
LinkedEntityMatch expectedLinkedEntity = expectedLinkedEntityMatches.get(i);
LinkedEntityMatch actualLinkedEntity = actualLinkedEntityMatches.get(i);
assertEquals(expectedLinkedEntity.getText(), actualLinkedEntity.getText());
assertEquals(expectedLinkedEntity.getOffset(), actualLinkedEntity.getOffset());
assertEquals(expectedLinkedEntity.getLength(), actualLinkedEntity.getLength());
assertNotNull(actualLinkedEntity.getConfidenceScore());
}
}
/**
* Helper method to verify the error document.
*
* @param expectedError the Error returned from the service.
* @param actualError the Error returned from the API.
*/
static void validateErrorDocument(TextAnalyticsError expectedError, TextAnalyticsError actualError) {
assertEquals(expectedError.getErrorCode(), actualError.getErrorCode());
assertEquals(expectedError.getMessage(), actualError.getMessage());
assertEquals(expectedError.getTarget(), actualError.getTarget());
}
} | |
please also replace `UserAgentContainer.AZSDK_USERAGENT_PREFIX` with hard coded value for the test | private String getUserAgentFixedPart() {
String osName = System.getProperty("os.name");
if (osName == null) {
osName = "Unknown";
}
osName = osName.replaceAll("\\s", "");
String geteUserAgentFixedPart =
UserAgentContainer.AZSDK_USERAGENT_PREFIX +
"cosmos" +
"/" +
HttpConstants.Versions.SDK_VERSION +
SPACE +
osName +
"/" +
System.getProperty("os.version") +
SPACE +
"JRE/" +
System.getProperty("java.version");
return geteUserAgentFixedPart;
} | UserAgentContainer.AZSDK_USERAGENT_PREFIX + | private String getUserAgentFixedPart() {
String osName = System.getProperty("os.name");
if (osName == null) {
osName = "Unknown";
}
osName = osName.replaceAll("\\s", "");
String geteUserAgentFixedPart = "azsdk-java-" +
"cosmos" +
"/" +
HttpConstants.Versions.SDK_VERSION +
SPACE +
osName +
"/" +
System.getProperty("os.version") +
SPACE +
"JRE/" +
System.getProperty("java.version");
return geteUserAgentFixedPart;
} | class UserAgentContainerTest {
private final static String SPACE = " ";
private final static int TIMEOUT = 40000;
@Test(groups = {"unit"})
public void userAgentContainerSetSuffix() {
String expectedStringFixedPart = getUserAgentFixedPart();
String userProvidedSuffix = "test-application-id";
UserAgentContainer userAgentContainer = new UserAgentContainer();
userAgentContainer.setSuffix(userProvidedSuffix);
String expectedString = expectedStringFixedPart + SPACE + userProvidedSuffix;
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
userAgentContainer = new UserAgentContainer();
expectedString = expectedStringFixedPart;
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
userProvidedSuffix = "greater than 64 characters
userAgentContainer = new UserAgentContainer();
userAgentContainer.setSuffix(userProvidedSuffix);
expectedString = expectedStringFixedPart + SPACE + userProvidedSuffix.substring(0, 64);
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
}
@Test(groups = {"emulator"}, timeOut = TIMEOUT)
public void UserAgentIntegrationTest() {
String userProvidedSuffix = "test-application-id";
CosmosAsyncClient gatewayClient = null;
CosmosAsyncClient directClient = null;
try {
gatewayClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.gatewayMode()
.userAgentSuffix(userProvidedSuffix)
.buildAsyncClient();
RxDocumentClientImpl documentClient =
(RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(gatewayClient);
UserAgentContainer userAgentContainer = ReflectionUtils.getUserAgentContainer(documentClient);
String expectedString = getUserAgentFixedPart() + SPACE + userProvidedSuffix;
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
directClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.directMode()
.userAgentSuffix(userProvidedSuffix)
.buildAsyncClient();
documentClient = (RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(directClient);
userAgentContainer = ReflectionUtils.getUserAgentContainer(documentClient);
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
} finally {
if (gatewayClient != null) {
gatewayClient.close();
}
if (directClient != null) {
directClient.close();
}
}
}
} | class UserAgentContainerTest {
private final static String SPACE = " ";
private final static int TIMEOUT = 40000;
@Test(groups = {"unit"})
public void userAgentContainerSetSuffix() {
String expectedStringFixedPart = getUserAgentFixedPart();
String userProvidedSuffix = "test-application-id";
UserAgentContainer userAgentContainer = new UserAgentContainer();
userAgentContainer.setSuffix(userProvidedSuffix);
String expectedString = expectedStringFixedPart + SPACE + userProvidedSuffix;
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
userAgentContainer = new UserAgentContainer();
expectedString = expectedStringFixedPart;
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
userProvidedSuffix = "greater than 64 characters
userAgentContainer = new UserAgentContainer();
userAgentContainer.setSuffix(userProvidedSuffix);
expectedString = expectedStringFixedPart + SPACE + userProvidedSuffix.substring(0, 64);
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
}
@Test(groups = {"emulator"}, timeOut = TIMEOUT)
public void UserAgentIntegration() {
String userProvidedSuffix = "test-application-id";
CosmosAsyncClient gatewayClient = null;
CosmosAsyncClient directClient = null;
try {
gatewayClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.gatewayMode()
.userAgentSuffix(userProvidedSuffix)
.buildAsyncClient();
RxDocumentClientImpl documentClient =
(RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(gatewayClient);
UserAgentContainer userAgentContainer = ReflectionUtils.getUserAgentContainer(documentClient);
String expectedString = getUserAgentFixedPart() + SPACE + userProvidedSuffix;
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
directClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.directMode()
.userAgentSuffix(userProvidedSuffix)
.buildAsyncClient();
documentClient = (RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(directClient);
userAgentContainer = ReflectionUtils.getUserAgentContainer(documentClient);
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
} finally {
if (gatewayClient != null) {
gatewayClient.close();
}
if (directClient != null) {
directClient.close();
}
}
}
} |
btw, this class, has a test named `UserAgentIntegrationTest()` (from prior useragent PR), please change that to `userAgentIntegration()` to follow test name code style. | private String getUserAgentFixedPart() {
String osName = System.getProperty("os.name");
if (osName == null) {
osName = "Unknown";
}
osName = osName.replaceAll("\\s", "");
String geteUserAgentFixedPart =
UserAgentContainer.AZSDK_USERAGENT_PREFIX +
"cosmos" +
"/" +
HttpConstants.Versions.SDK_VERSION +
SPACE +
osName +
"/" +
System.getProperty("os.version") +
SPACE +
"JRE/" +
System.getProperty("java.version");
return geteUserAgentFixedPart;
} | osName = osName.replaceAll("\\s", ""); | private String getUserAgentFixedPart() {
String osName = System.getProperty("os.name");
if (osName == null) {
osName = "Unknown";
}
osName = osName.replaceAll("\\s", "");
String geteUserAgentFixedPart = "azsdk-java-" +
"cosmos" +
"/" +
HttpConstants.Versions.SDK_VERSION +
SPACE +
osName +
"/" +
System.getProperty("os.version") +
SPACE +
"JRE/" +
System.getProperty("java.version");
return geteUserAgentFixedPart;
} | class UserAgentContainerTest {
private final static String SPACE = " ";
private final static int TIMEOUT = 40000;
@Test(groups = {"unit"})
public void userAgentContainerSetSuffix() {
String expectedStringFixedPart = getUserAgentFixedPart();
String userProvidedSuffix = "test-application-id";
UserAgentContainer userAgentContainer = new UserAgentContainer();
userAgentContainer.setSuffix(userProvidedSuffix);
String expectedString = expectedStringFixedPart + SPACE + userProvidedSuffix;
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
userAgentContainer = new UserAgentContainer();
expectedString = expectedStringFixedPart;
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
userProvidedSuffix = "greater than 64 characters
userAgentContainer = new UserAgentContainer();
userAgentContainer.setSuffix(userProvidedSuffix);
expectedString = expectedStringFixedPart + SPACE + userProvidedSuffix.substring(0, 64);
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
}
@Test(groups = {"emulator"}, timeOut = TIMEOUT)
public void UserAgentIntegrationTest() {
String userProvidedSuffix = "test-application-id";
CosmosAsyncClient gatewayClient = null;
CosmosAsyncClient directClient = null;
try {
gatewayClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.gatewayMode()
.userAgentSuffix(userProvidedSuffix)
.buildAsyncClient();
RxDocumentClientImpl documentClient =
(RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(gatewayClient);
UserAgentContainer userAgentContainer = ReflectionUtils.getUserAgentContainer(documentClient);
String expectedString = getUserAgentFixedPart() + SPACE + userProvidedSuffix;
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
directClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.directMode()
.userAgentSuffix(userProvidedSuffix)
.buildAsyncClient();
documentClient = (RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(directClient);
userAgentContainer = ReflectionUtils.getUserAgentContainer(documentClient);
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
} finally {
if (gatewayClient != null) {
gatewayClient.close();
}
if (directClient != null) {
directClient.close();
}
}
}
} | class UserAgentContainerTest {
private final static String SPACE = " ";
private final static int TIMEOUT = 40000;
@Test(groups = {"unit"})
public void userAgentContainerSetSuffix() {
String expectedStringFixedPart = getUserAgentFixedPart();
String userProvidedSuffix = "test-application-id";
UserAgentContainer userAgentContainer = new UserAgentContainer();
userAgentContainer.setSuffix(userProvidedSuffix);
String expectedString = expectedStringFixedPart + SPACE + userProvidedSuffix;
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
userAgentContainer = new UserAgentContainer();
expectedString = expectedStringFixedPart;
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
userProvidedSuffix = "greater than 64 characters
userAgentContainer = new UserAgentContainer();
userAgentContainer.setSuffix(userProvidedSuffix);
expectedString = expectedStringFixedPart + SPACE + userProvidedSuffix.substring(0, 64);
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
}
@Test(groups = {"emulator"}, timeOut = TIMEOUT)
public void UserAgentIntegration() {
String userProvidedSuffix = "test-application-id";
CosmosAsyncClient gatewayClient = null;
CosmosAsyncClient directClient = null;
try {
gatewayClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.gatewayMode()
.userAgentSuffix(userProvidedSuffix)
.buildAsyncClient();
RxDocumentClientImpl documentClient =
(RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(gatewayClient);
UserAgentContainer userAgentContainer = ReflectionUtils.getUserAgentContainer(documentClient);
String expectedString = getUserAgentFixedPart() + SPACE + userProvidedSuffix;
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
directClient = new CosmosClientBuilder()
.endpoint(TestConfigurations.HOST)
.key(TestConfigurations.MASTER_KEY)
.contentResponseOnWriteEnabled(true)
.directMode()
.userAgentSuffix(userProvidedSuffix)
.buildAsyncClient();
documentClient = (RxDocumentClientImpl) ReflectionUtils.getAsyncDocumentClient(directClient);
userAgentContainer = ReflectionUtils.getUserAgentContainer(documentClient);
assertThat(userAgentContainer.getUserAgent()).isEqualTo(expectedString);
} finally {
if (gatewayClient != null) {
gatewayClient.close();
}
if (directClient != null) {
directClient.close();
}
}
}
} |
isZero() | isNegative() ? | private Disposable getRenewLockOperation(Instant initialLockedUntil, Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration.isZero()) {
status.set(LockRenewalStatus.COMPLETE);
return Disposables.single();
}
final Instant now = Instant.now();
Duration initialInterval = Duration.between(now, initialLockedUntil);
if (initialInterval.isNegative()) {
logger.info("Duration was negative. now[{}] lockedUntil[{}]", now, initialLockedUntil);
initialInterval = Duration.ZERO;
} else {
final Duration adjusted = MessageUtils.adjustServerTimeout(initialInterval);
if (adjusted.isNegative()) {
logger.info("Adjusted duration is negative. Adjusted: {}ms", initialInterval.toMillis());
} else {
initialInterval = adjusted;
}
}
final EmitterProcessor<Duration> emitterProcessor = EmitterProcessor.create();
final FluxSink<Duration> sink = emitterProcessor.sink();
sink.next(initialInterval);
final Flux<Object> cancellationSignals = Flux.first(cancellationProcessor, Mono.delay(maxLockRenewalDuration));
return Flux.switchOnNext(emitterProcessor.map(Flux::interval))
.takeUntilOther(cancellationSignals)
.flatMap(delay -> {
final String id = lockToken;
logger.info("token[{}]. now[{}]. Starting lock renewal.", id, Instant.now());
if (CoreUtils.isNullOrEmpty(id)) {
return Mono.error(new IllegalStateException("Cannot renew session lock without session id."));
}
return renewalOperation.apply(lockToken);
})
.map(instant -> {
final Duration next = Duration.between(Instant.now(), instant);
logger.info("token[{}]. nextExpiration[{}]. next: [{}]. isSession[{}]", lockToken, instant, next,
isSession);
sink.next(MessageUtils.adjustServerTimeout(next));
return instant;
})
.subscribe(until -> lockedUntil.set(until),
error -> {
logger.error("token[{}]. Error occurred while renewing lock token.", error);
status.set(LockRenewalStatus.FAILED);
throwable.set(error);
cancellationProcessor.onComplete();
}, () -> {
if (status.compareAndSet(LockRenewalStatus.RUNNING, LockRenewalStatus.COMPLETE)) {
logger.verbose("token[{}]. Renewing session lock task completed.", lockToken);
}
cancellationProcessor.onComplete();
});
} | if (maxLockRenewalDuration.isZero()) { | private Disposable getRenewLockOperation(Instant initialLockedUntil, Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration.isZero()) {
status.set(LockRenewalStatus.COMPLETE);
return Disposables.single();
}
final Instant now = Instant.now();
Duration initialInterval = Duration.between(now, initialLockedUntil);
if (initialInterval.isNegative()) {
logger.info("Duration was negative. now[{}] lockedUntil[{}]", now, initialLockedUntil);
initialInterval = Duration.ZERO;
} else {
final Duration adjusted = MessageUtils.adjustServerTimeout(initialInterval);
if (adjusted.isNegative()) {
logger.info("Adjusted duration is negative. Adjusted: {}ms", initialInterval.toMillis());
} else {
initialInterval = adjusted;
}
}
final EmitterProcessor<Duration> emitterProcessor = EmitterProcessor.create();
final FluxSink<Duration> sink = emitterProcessor.sink();
sink.next(initialInterval);
final Flux<Object> cancellationSignals = Flux.first(cancellationProcessor, Mono.delay(maxLockRenewalDuration));
return Flux.switchOnNext(emitterProcessor.map(interval -> Mono.delay(interval)
.thenReturn(Flux.create(s -> s.next(interval)))))
.takeUntilOther(cancellationSignals)
.flatMap(delay -> {
logger.info("token[{}]. now[{}]. Starting lock renewal.", lockToken, Instant.now());
return renewalOperation.apply(lockToken);
})
.map(instant -> {
final Duration next = Duration.between(Instant.now(), instant);
logger.info("token[{}]. nextExpiration[{}]. next: [{}]. isSession[{}]", lockToken, instant, next,
isSession);
sink.next(MessageUtils.adjustServerTimeout(next));
return instant;
})
.subscribe(until -> lockedUntil.set(until),
error -> {
logger.error("token[{}]. Error occurred while renewing lock token.", error);
status.set(LockRenewalStatus.FAILED);
throwable.set(error);
cancellationProcessor.onComplete();
}, () -> {
if (status.compareAndSet(LockRenewalStatus.RUNNING, LockRenewalStatus.COMPLETE)) {
logger.verbose("token[{}]. Renewing session lock task completed.", lockToken);
}
cancellationProcessor.onComplete();
});
} | class LockRenewalOperation implements AutoCloseable {
private final ClientLogger logger = new ClientLogger(LockRenewalOperation.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicReference<Instant> lockedUntil = new AtomicReference<>();
private final AtomicReference<Throwable> throwable = new AtomicReference<>();
private final AtomicReference<LockRenewalStatus> status = new AtomicReference<>(LockRenewalStatus.RUNNING);
private final MonoProcessor<Void> cancellationProcessor = MonoProcessor.create();
private final String lockToken;
private final boolean isSession;
private final Function<String, Mono<Instant>> renewalOperation;
private final Disposable subscription;
/**
* Creates a new lock renewal operation. The lock is initially renewed.
*
* @param lockToken Lock or session id to renew.
* @param maxLockRenewalDuration The maximum duration this lock should be renewed.
* @param isSession Whether the lock represents a session lock or message lock.
* @param renewalOperation The renewal operation to call.
*/
LockRenewalOperation(String lockToken, Duration maxLockRenewalDuration, boolean isSession,
Function<String, Mono<Instant>> renewalOperation) {
this(lockToken, maxLockRenewalDuration, isSession, renewalOperation, Instant.now());
}
/**
* Creates a new lock renewal operation.
*
* @param lockToken Lock or session id to renew.
* @param lockedUntil The initial period the message or session is locked until.
* @param maxLockRenewalDuration The maximum duration this lock should be renewed.
* @param isSession Whether the lock represents a session lock or message lock.
* @param renewalOperation The renewal operation to call.
*/
LockRenewalOperation(String lockToken, Duration maxLockRenewalDuration, boolean isSession,
Function<String, Mono<Instant>> renewalOperation, Instant lockedUntil) {
this.lockToken = Objects.requireNonNull(lockToken, "'lockToken' cannot be null.");
this.renewalOperation = Objects.requireNonNull(renewalOperation, "'renewalOperation' cannot be null.");
this.isSession = isSession;
Objects.requireNonNull(lockedUntil, "'lockedUntil cannot be null.'");
Objects.requireNonNull(maxLockRenewalDuration, "'maxLockRenewalDuration' cannot be null.");
if (maxLockRenewalDuration.isNegative()) {
throw logger.logThrowableAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
this.lockedUntil.set(lockedUntil);
this.subscription = getRenewLockOperation(lockedUntil, maxLockRenewalDuration);
}
/**
* Gets the current instant the message or session is locked until.
*
* @return the instant the message or session is locked until.
*/
public Instant getLockedUntil() {
return lockedUntil.get();
}
/**
* Gets the message lock token for the renewal operation.
*
* @return The message lock token or {@code null} if a session is being renewed instead.
*/
public String getLockToken() {
return isSession ? null : lockToken;
}
/**
* Gets the session id for this lock renewal operation.
*
* @return The session id or {@code null} if it is not a session renewal.
*/
public String getSessionId() {
return isSession ? lockToken : null;
}
/**
* Gets the current status of the renewal operation.
*
* @return The current status of the renewal operation.
*/
public LockRenewalStatus getStatus() {
return status.get();
}
/**
* Gets the exception if an error occurred whilst renewing the message or session lock.
*
* @return the exception if an error occurred whilst renewing the message or session lock, otherwise {@code null}.
*/
public Throwable getThrowable() {
return throwable.get();
}
/**
* Cancels the lock renewal operation.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
if (status.compareAndSet(LockRenewalStatus.RUNNING, LockRenewalStatus.CANCELLED)) {
logger.verbose("token[{}] Cancelled operation.", lockToken);
}
cancellationProcessor.onComplete();
subscription.dispose();
}
/**
* Gets the lock renewal operation. if the {@code maxLockRenewalDuration} is {@link Duration
* lock is never renewed.
*
* @param initialLockedUntil When the initial call is locked until.
* @param maxLockRenewalDuration Duration to renew lock for.
* @return The subscription for the operation.
*/
} | class LockRenewalOperation implements AutoCloseable {
private final ClientLogger logger = new ClientLogger(LockRenewalOperation.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicReference<Instant> lockedUntil = new AtomicReference<>();
private final AtomicReference<Throwable> throwable = new AtomicReference<>();
private final AtomicReference<LockRenewalStatus> status = new AtomicReference<>(LockRenewalStatus.RUNNING);
private final MonoProcessor<Void> cancellationProcessor = MonoProcessor.create();
private final String lockToken;
private final boolean isSession;
private final Function<String, Mono<Instant>> renewalOperation;
private final Disposable subscription;
/**
* Creates a new lock renewal operation. The lock is initially renewed.
*
* @param lockToken Message lock or session id to renew.
* @param maxLockRenewalDuration The maximum duration this lock should be renewed.
* @param isSession Whether the lock represents a session lock or message lock.
* @param renewalOperation The renewal operation to call.
*/
LockRenewalOperation(String lockToken, Duration maxLockRenewalDuration, boolean isSession,
Function<String, Mono<Instant>> renewalOperation) {
this(lockToken, maxLockRenewalDuration, isSession, renewalOperation, Instant.now());
}
/**
* Creates a new lock renewal operation.
*
* @param lockToken Lock or session id to renew.
* @param lockedUntil The initial period the message or session is locked until.
* @param maxLockRenewalDuration The maximum duration this lock should be renewed.
* @param isSession Whether the lock represents a session lock or message lock.
* @param renewalOperation The renewal operation to call.
*/
LockRenewalOperation(String lockToken, Duration maxLockRenewalDuration, boolean isSession,
Function<String, Mono<Instant>> renewalOperation, Instant lockedUntil) {
this.lockToken = Objects.requireNonNull(lockToken, "'lockToken' cannot be null.");
this.renewalOperation = Objects.requireNonNull(renewalOperation, "'renewalOperation' cannot be null.");
this.isSession = isSession;
Objects.requireNonNull(lockedUntil, "'lockedUntil cannot be null.'");
Objects.requireNonNull(maxLockRenewalDuration, "'maxLockRenewalDuration' cannot be null.");
if (maxLockRenewalDuration.isNegative()) {
throw logger.logThrowableAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
this.lockedUntil.set(lockedUntil);
this.subscription = getRenewLockOperation(lockedUntil, maxLockRenewalDuration);
}
/**
* Gets the current instant the message or session is locked until.
*
* @return the instant the message or session is locked until.
*/
public Instant getLockedUntil() {
return lockedUntil.get();
}
/**
* Gets the message lock token for the renewal operation.
*
* @return The message lock token or {@code null} if a session is being renewed instead.
*/
public String getLockToken() {
return isSession ? null : lockToken;
}
/**
* Gets the session id for this lock renewal operation.
*
* @return The session id or {@code null} if it is not a session renewal.
*/
public String getSessionId() {
return isSession ? lockToken : null;
}
/**
* Gets the current status of the renewal operation.
*
* @return The current status of the renewal operation.
*/
public LockRenewalStatus getStatus() {
return status.get();
}
/**
* Gets the exception if an error occurred whilst renewing the message or session lock.
*
* @return the exception if an error occurred whilst renewing the message or session lock, otherwise {@code null}.
*/
public Throwable getThrowable() {
return throwable.get();
}
/**
* Cancels the lock renewal operation.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
if (status.compareAndSet(LockRenewalStatus.RUNNING, LockRenewalStatus.CANCELLED)) {
logger.verbose("token[{}] Cancelled operation.", lockToken);
}
cancellationProcessor.onComplete();
subscription.dispose();
}
/**
* Gets the lock renewal operation. if the {@code maxLockRenewalDuration} is {@link Duration
* lock is never renewed.
*
* @param initialLockedUntil When the initial call is locked until.
* @param maxLockRenewalDuration Duration to renew lock for.
* @return The subscription for the operation.
*/
} |
is this messaging correct ?, the lockToken can be for Message Lock or session id. | private Disposable getRenewLockOperation(Instant initialLockedUntil, Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration.isZero()) {
status.set(LockRenewalStatus.COMPLETE);
return Disposables.single();
}
final Instant now = Instant.now();
Duration initialInterval = Duration.between(now, initialLockedUntil);
if (initialInterval.isNegative()) {
logger.info("Duration was negative. now[{}] lockedUntil[{}]", now, initialLockedUntil);
initialInterval = Duration.ZERO;
} else {
final Duration adjusted = MessageUtils.adjustServerTimeout(initialInterval);
if (adjusted.isNegative()) {
logger.info("Adjusted duration is negative. Adjusted: {}ms", initialInterval.toMillis());
} else {
initialInterval = adjusted;
}
}
final EmitterProcessor<Duration> emitterProcessor = EmitterProcessor.create();
final FluxSink<Duration> sink = emitterProcessor.sink();
sink.next(initialInterval);
final Flux<Object> cancellationSignals = Flux.first(cancellationProcessor, Mono.delay(maxLockRenewalDuration));
return Flux.switchOnNext(emitterProcessor.map(Flux::interval))
.takeUntilOther(cancellationSignals)
.flatMap(delay -> {
final String id = lockToken;
logger.info("token[{}]. now[{}]. Starting lock renewal.", id, Instant.now());
if (CoreUtils.isNullOrEmpty(id)) {
return Mono.error(new IllegalStateException("Cannot renew session lock without session id."));
}
return renewalOperation.apply(lockToken);
})
.map(instant -> {
final Duration next = Duration.between(Instant.now(), instant);
logger.info("token[{}]. nextExpiration[{}]. next: [{}]. isSession[{}]", lockToken, instant, next,
isSession);
sink.next(MessageUtils.adjustServerTimeout(next));
return instant;
})
.subscribe(until -> lockedUntil.set(until),
error -> {
logger.error("token[{}]. Error occurred while renewing lock token.", error);
status.set(LockRenewalStatus.FAILED);
throwable.set(error);
cancellationProcessor.onComplete();
}, () -> {
if (status.compareAndSet(LockRenewalStatus.RUNNING, LockRenewalStatus.COMPLETE)) {
logger.verbose("token[{}]. Renewing session lock task completed.", lockToken);
}
cancellationProcessor.onComplete();
});
} | return Mono.error(new IllegalStateException("Cannot renew session lock without session id.")); | private Disposable getRenewLockOperation(Instant initialLockedUntil, Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration.isZero()) {
status.set(LockRenewalStatus.COMPLETE);
return Disposables.single();
}
final Instant now = Instant.now();
Duration initialInterval = Duration.between(now, initialLockedUntil);
if (initialInterval.isNegative()) {
logger.info("Duration was negative. now[{}] lockedUntil[{}]", now, initialLockedUntil);
initialInterval = Duration.ZERO;
} else {
final Duration adjusted = MessageUtils.adjustServerTimeout(initialInterval);
if (adjusted.isNegative()) {
logger.info("Adjusted duration is negative. Adjusted: {}ms", initialInterval.toMillis());
} else {
initialInterval = adjusted;
}
}
final EmitterProcessor<Duration> emitterProcessor = EmitterProcessor.create();
final FluxSink<Duration> sink = emitterProcessor.sink();
sink.next(initialInterval);
final Flux<Object> cancellationSignals = Flux.first(cancellationProcessor, Mono.delay(maxLockRenewalDuration));
return Flux.switchOnNext(emitterProcessor.map(interval -> Mono.delay(interval)
.thenReturn(Flux.create(s -> s.next(interval)))))
.takeUntilOther(cancellationSignals)
.flatMap(delay -> {
logger.info("token[{}]. now[{}]. Starting lock renewal.", lockToken, Instant.now());
return renewalOperation.apply(lockToken);
})
.map(instant -> {
final Duration next = Duration.between(Instant.now(), instant);
logger.info("token[{}]. nextExpiration[{}]. next: [{}]. isSession[{}]", lockToken, instant, next,
isSession);
sink.next(MessageUtils.adjustServerTimeout(next));
return instant;
})
.subscribe(until -> lockedUntil.set(until),
error -> {
logger.error("token[{}]. Error occurred while renewing lock token.", error);
status.set(LockRenewalStatus.FAILED);
throwable.set(error);
cancellationProcessor.onComplete();
}, () -> {
if (status.compareAndSet(LockRenewalStatus.RUNNING, LockRenewalStatus.COMPLETE)) {
logger.verbose("token[{}]. Renewing session lock task completed.", lockToken);
}
cancellationProcessor.onComplete();
});
} | class LockRenewalOperation implements AutoCloseable {
private final ClientLogger logger = new ClientLogger(LockRenewalOperation.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicReference<Instant> lockedUntil = new AtomicReference<>();
private final AtomicReference<Throwable> throwable = new AtomicReference<>();
private final AtomicReference<LockRenewalStatus> status = new AtomicReference<>(LockRenewalStatus.RUNNING);
private final MonoProcessor<Void> cancellationProcessor = MonoProcessor.create();
private final String lockToken;
private final boolean isSession;
private final Function<String, Mono<Instant>> renewalOperation;
private final Disposable subscription;
/**
* Creates a new lock renewal operation. The lock is initially renewed.
*
* @param lockToken Lock or session id to renew.
* @param maxLockRenewalDuration The maximum duration this lock should be renewed.
* @param isSession Whether the lock represents a session lock or message lock.
* @param renewalOperation The renewal operation to call.
*/
LockRenewalOperation(String lockToken, Duration maxLockRenewalDuration, boolean isSession,
Function<String, Mono<Instant>> renewalOperation) {
this(lockToken, maxLockRenewalDuration, isSession, renewalOperation, Instant.now());
}
/**
* Creates a new lock renewal operation.
*
* @param lockToken Lock or session id to renew.
* @param lockedUntil The initial period the message or session is locked until.
* @param maxLockRenewalDuration The maximum duration this lock should be renewed.
* @param isSession Whether the lock represents a session lock or message lock.
* @param renewalOperation The renewal operation to call.
*/
LockRenewalOperation(String lockToken, Duration maxLockRenewalDuration, boolean isSession,
Function<String, Mono<Instant>> renewalOperation, Instant lockedUntil) {
this.lockToken = Objects.requireNonNull(lockToken, "'lockToken' cannot be null.");
this.renewalOperation = Objects.requireNonNull(renewalOperation, "'renewalOperation' cannot be null.");
this.isSession = isSession;
Objects.requireNonNull(lockedUntil, "'lockedUntil cannot be null.'");
Objects.requireNonNull(maxLockRenewalDuration, "'maxLockRenewalDuration' cannot be null.");
if (maxLockRenewalDuration.isNegative()) {
throw logger.logThrowableAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
this.lockedUntil.set(lockedUntil);
this.subscription = getRenewLockOperation(lockedUntil, maxLockRenewalDuration);
}
/**
* Gets the current instant the message or session is locked until.
*
* @return the instant the message or session is locked until.
*/
public Instant getLockedUntil() {
return lockedUntil.get();
}
/**
* Gets the message lock token for the renewal operation.
*
* @return The message lock token or {@code null} if a session is being renewed instead.
*/
public String getLockToken() {
return isSession ? null : lockToken;
}
/**
* Gets the session id for this lock renewal operation.
*
* @return The session id or {@code null} if it is not a session renewal.
*/
public String getSessionId() {
return isSession ? lockToken : null;
}
/**
* Gets the current status of the renewal operation.
*
* @return The current status of the renewal operation.
*/
public LockRenewalStatus getStatus() {
return status.get();
}
/**
* Gets the exception if an error occurred whilst renewing the message or session lock.
*
* @return the exception if an error occurred whilst renewing the message or session lock, otherwise {@code null}.
*/
public Throwable getThrowable() {
return throwable.get();
}
/**
* Cancels the lock renewal operation.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
if (status.compareAndSet(LockRenewalStatus.RUNNING, LockRenewalStatus.CANCELLED)) {
logger.verbose("token[{}] Cancelled operation.", lockToken);
}
cancellationProcessor.onComplete();
subscription.dispose();
}
/**
* Gets the lock renewal operation. if the {@code maxLockRenewalDuration} is {@link Duration
* lock is never renewed.
*
* @param initialLockedUntil When the initial call is locked until.
* @param maxLockRenewalDuration Duration to renew lock for.
* @return The subscription for the operation.
*/
} | class LockRenewalOperation implements AutoCloseable {
private final ClientLogger logger = new ClientLogger(LockRenewalOperation.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicReference<Instant> lockedUntil = new AtomicReference<>();
private final AtomicReference<Throwable> throwable = new AtomicReference<>();
private final AtomicReference<LockRenewalStatus> status = new AtomicReference<>(LockRenewalStatus.RUNNING);
private final MonoProcessor<Void> cancellationProcessor = MonoProcessor.create();
private final String lockToken;
private final boolean isSession;
private final Function<String, Mono<Instant>> renewalOperation;
private final Disposable subscription;
/**
* Creates a new lock renewal operation. The lock is initially renewed.
*
* @param lockToken Message lock or session id to renew.
* @param maxLockRenewalDuration The maximum duration this lock should be renewed.
* @param isSession Whether the lock represents a session lock or message lock.
* @param renewalOperation The renewal operation to call.
*/
LockRenewalOperation(String lockToken, Duration maxLockRenewalDuration, boolean isSession,
Function<String, Mono<Instant>> renewalOperation) {
this(lockToken, maxLockRenewalDuration, isSession, renewalOperation, Instant.now());
}
/**
* Creates a new lock renewal operation.
*
* @param lockToken Lock or session id to renew.
* @param lockedUntil The initial period the message or session is locked until.
* @param maxLockRenewalDuration The maximum duration this lock should be renewed.
* @param isSession Whether the lock represents a session lock or message lock.
* @param renewalOperation The renewal operation to call.
*/
LockRenewalOperation(String lockToken, Duration maxLockRenewalDuration, boolean isSession,
Function<String, Mono<Instant>> renewalOperation, Instant lockedUntil) {
this.lockToken = Objects.requireNonNull(lockToken, "'lockToken' cannot be null.");
this.renewalOperation = Objects.requireNonNull(renewalOperation, "'renewalOperation' cannot be null.");
this.isSession = isSession;
Objects.requireNonNull(lockedUntil, "'lockedUntil cannot be null.'");
Objects.requireNonNull(maxLockRenewalDuration, "'maxLockRenewalDuration' cannot be null.");
if (maxLockRenewalDuration.isNegative()) {
throw logger.logThrowableAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
this.lockedUntil.set(lockedUntil);
this.subscription = getRenewLockOperation(lockedUntil, maxLockRenewalDuration);
}
/**
* Gets the current instant the message or session is locked until.
*
* @return the instant the message or session is locked until.
*/
public Instant getLockedUntil() {
return lockedUntil.get();
}
/**
* Gets the message lock token for the renewal operation.
*
* @return The message lock token or {@code null} if a session is being renewed instead.
*/
public String getLockToken() {
return isSession ? null : lockToken;
}
/**
* Gets the session id for this lock renewal operation.
*
* @return The session id or {@code null} if it is not a session renewal.
*/
public String getSessionId() {
return isSession ? lockToken : null;
}
/**
* Gets the current status of the renewal operation.
*
* @return The current status of the renewal operation.
*/
public LockRenewalStatus getStatus() {
return status.get();
}
/**
* Gets the exception if an error occurred whilst renewing the message or session lock.
*
* @return the exception if an error occurred whilst renewing the message or session lock, otherwise {@code null}.
*/
public Throwable getThrowable() {
return throwable.get();
}
/**
* Cancels the lock renewal operation.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
if (status.compareAndSet(LockRenewalStatus.RUNNING, LockRenewalStatus.CANCELLED)) {
logger.verbose("token[{}] Cancelled operation.", lockToken);
}
cancellationProcessor.onComplete();
subscription.dispose();
}
/**
* Gets the lock renewal operation. if the {@code maxLockRenewalDuration} is {@link Duration
* lock is never renewed.
*
* @param initialLockedUntil When the initial call is locked until.
* @param maxLockRenewalDuration Duration to renew lock for.
* @return The subscription for the operation.
*/
} |
Shouldn't we check for empty or null session id and throw Exception as needed? | public LockRenewalOperation getAutoRenewSessionLock(String sessionId, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
throw logger.logThrowableAsError(new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
throw logger.logThrowableAsError(new IllegalStateException(
"Cannot renew session lock on a non-session receiver."));
} else if (maxLockRenewalDuration == null) {
throw logger.logThrowableAsError(new NullPointerException("'maxLockRenewalDuration' cannot be null."));
} else if (maxLockRenewalDuration.isNegative()) {
throw logger.logThrowableAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
return new LockRenewalOperation(sessionId, maxLockRenewalDuration, true, this::renewSessionLock);
} | String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock"))); | public LockRenewalOperation getAutoRenewSessionLock(String sessionId, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
throw logger.logExceptionAsError(new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
throw logger.logExceptionAsError(new IllegalStateException(
"Cannot renew session lock on a non-session receiver."));
} else if (maxLockRenewalDuration == null) {
throw logger.logExceptionAsError(new NullPointerException("'maxLockRenewalDuration' cannot be null."));
} else if (maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
} else if (Objects.isNull(sessionId)) {
throw logger.logExceptionAsError(new NullPointerException("'sessionId' cannot be null."));
} else if (sessionId.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'sessionId' cannot be empty."));
}
final LockRenewalOperation operation = new LockRenewalOperation(sessionId, maxLockRenewalDuration, true,
this::renewSessionLock);
renewalContainer.addOrUpdate(sessionId, Instant.now().plus(maxLockRenewalDuration), operation);
return operation;
} | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final MessageLockContainer managementNodeLocks;
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class);
private final String fullyQualifiedNamespace;
private final String entityPath;
private final MessagingEntityType entityType;
private final ReceiverOptions receiverOptions;
private final ServiceBusConnectionProcessor connectionProcessor;
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
private final Runnable onClientClose;
private final UnnamedSessionManager unnamedSessionManager;
private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1);
private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>();
/**
* Creates a receiver that listens to a Service Bus resource.
*
* @param fullyQualifiedNamespace The fully qualified domain name for the Service Bus resource.
* @param entityPath The name of the topic or queue.
* @param entityType The type of the Service Bus resource.
* @param receiverOptions Options when receiving messages.
* @param connectionProcessor The AMQP connection to the Service Bus resource.
* @param tracerProvider Tracer for telemetry.
* @param messageSerializer Serializes and deserializes Service Bus messages.
* @param onClientClose Operation to run when the client completes.
*/
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null.");
this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null.");
this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'");
this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null.");
this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.managementNodeLocks = new MessageLockContainer(cleanupInterval);
this.unnamedSessionManager = null;
}
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose,
UnnamedSessionManager unnamedSessionManager) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null.");
this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null.");
this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'");
this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null.");
this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.unnamedSessionManager = Objects.requireNonNull(unnamedSessionManager, "'sessionManager' cannot be null.");
this.managementNodeLocks = new MessageLockContainer(cleanupInterval);
}
/**
* Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to
* {@code {yournamespace}.servicebus.windows.net}.
*
* @return The fully qualified Service Bus namespace that the connection is associated with.
*/
public String getFullyQualifiedNamespace() {
return fullyQualifiedNamespace;
}
/**
* Gets the Service Bus resource this client interacts with.
*
* @return The Service Bus resource this client interacts with.
*/
public String getEntityPath() {
return entityPath;
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available
* again for processing. Abandoning a message will increase the delivery count on the message.
*
* @param lockToken Lock token of the message.
*
* @return A {@link Mono} that completes when the Service Bus abandon operation completes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken) {
return abandon(lockToken, receiverOptions.getSessionId());
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available
* again for processing. Abandoning a message will increase the delivery count on the message.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to abandon. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the Service Bus abandon operation completes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken, String sessionId) {
return abandon(lockToken, null, sessionId);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties.
* This will make the message available again for processing. Abandoning a message will increase the delivery count
* on the message.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Properties to modify on the message.
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken, Map<String, Object> propertiesToModify) {
return abandon(lockToken, propertiesToModify, receiverOptions.getSessionId());
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties.
* This will make the message available again for processing. Abandoning a message will increase the delivery count
* on the message.
* <p><strong>Complete a message with a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.abandonMessageWithTransaction}
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Properties to modify on the message.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
return abandon(lockToken, propertiesToModify, receiverOptions.getSessionId(), transactionContext);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties.
* This will make the message available again for processing. Abandoning a message will increase the delivery count
* on the message.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Properties to modify on the message.
* @param sessionId Session id of the message to abandon. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the Service Bus abandon operation completes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken, Map<String, Object> propertiesToModify, String sessionId) {
return updateDisposition(lockToken, DispositionStatus.ABANDONED, null, null,
propertiesToModify, sessionId, null);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties.
* This will make the message available again for processing. Abandoning a message will increase the delivery count
* on the message.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Properties to modify on the message.
* @param sessionId Session id of the message to abandon. {@code null} if there is no session.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus abandon operation completes.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken, Map<String, Object> propertiesToModify, String sessionId,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return updateDisposition(lockToken, DispositionStatus.ABANDONED, null, null,
propertiesToModify, sessionId, transactionContext);
}
/**
* Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the
* service.
*
* @param lockToken Lock token of the message.
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> complete(String lockToken) {
return updateDisposition(lockToken, DispositionStatus.COMPLETED, null, null,
null, receiverOptions.getSessionId(), null);
}
/**
* Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the
* service.
* <p><strong>Complete a message with a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.completeMessageWithTransaction}
*
* @param lockToken Lock token of the message.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> complete(String lockToken, ServiceBusTransactionContext transactionContext) {
return complete(lockToken, receiverOptions.getSessionId(), transactionContext);
}
/**
* Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the
* service.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to complete. {@code null} if there is no session.
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> complete(String lockToken, String sessionId) {
return updateDisposition(lockToken, DispositionStatus.COMPLETED, null, null,
null, sessionId, null);
}
/**
* Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the
* service.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to complete. {@code null} if there is no session.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> complete(String lockToken, String sessionId,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return updateDisposition(lockToken, DispositionStatus.COMPLETED, null, null,
null, sessionId, transactionContext);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred
* subqueue.
*
* @param lockToken Lock token of the message.
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken) {
return defer(lockToken, receiverOptions.getSessionId());
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred
* subqueue.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to defer. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken, String sessionId) {
return defer(lockToken, null, sessionId);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will
* move message into the deferred subqueue.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Message properties to modify.
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken, Map<String, Object> propertiesToModify) {
return defer(lockToken, propertiesToModify, receiverOptions.getSessionId());
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will
* move message into the deferred subqueue.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Message properties to modify.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
return defer(lockToken, propertiesToModify, receiverOptions.getSessionId(), transactionContext);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will
* move message into the deferred subqueue.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Message properties to modify.
* @param sessionId Session id of the message to defer. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken, Map<String, Object> propertiesToModify, String sessionId) {
return updateDisposition(lockToken, DispositionStatus.DEFERRED, null, null,
propertiesToModify, sessionId, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will
* move message into the deferred subqueue.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Message properties to modify.
* @param sessionId Session id of the message to defer. {@code null} if there is no session.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken, Map<String, Object> propertiesToModify, String sessionId,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return updateDisposition(lockToken, DispositionStatus.DEFERRED, null, null,
propertiesToModify, sessionId, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue.
*
* @param lockToken Lock token of the message.
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(String lockToken) {
return deadLetter(lockToken, receiverOptions.getSessionId());
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to deadletter. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(String lockToken, String sessionId) {
return deadLetter(lockToken, DEFAULT_DEAD_LETTER_OPTIONS, sessionId);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to deadletter. {@code null} if there is no session.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(String lockToken, String sessionId,
ServiceBusTransactionContext transactionContext) {
return deadLetter(lockToken, DEFAULT_DEAD_LETTER_OPTIONS, sessionId, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param lockToken Lock token of the message.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken} or {@code deadLetterOptions} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> deadLetter(String lockToken, DeadLetterOptions deadLetterOptions) {
return deadLetter(lockToken, deadLetterOptions, receiverOptions.getSessionId());
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param lockToken Lock token of the message.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken}, {@code deadLetterOptions}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> deadLetter(String lockToken, DeadLetterOptions deadLetterOptions,
ServiceBusTransactionContext transactionContext) {
return deadLetter(lockToken, deadLetterOptions, receiverOptions.getSessionId(), transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param lockToken Lock token of the message.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param sessionId Session id of the message to deadletter. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> deadLetter(String lockToken, DeadLetterOptions deadLetterOptions, String sessionId) {
if (Objects.isNull(deadLetterOptions)) {
return monoError(logger, new NullPointerException("'deadLetterOptions' cannot be null."));
}
return updateDisposition(lockToken, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(), sessionId,
null);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param lockToken Lock token of the message.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param sessionId Session id of the message to deadletter. {@code null} if there is no session.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> deadLetter(String lockToken, DeadLetterOptions deadLetterOptions, String sessionId,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return updateDisposition(lockToken, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(), sessionId,
transactionContext);
}
/**
* Gets and starts the auto lock renewal for a message with the given lock.
*
* @param lockToken Lock token of the message.
* @param maxLockRenewalDuration Maximum duration to keep renewing the lock token.
* @return A lock renewal operation for the message.
*/
public LockRenewalOperation getAutoRenewMessageLock(String lockToken, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
throw logger.logThrowableAsError(new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewMessageLock")));
} else if (Objects.isNull(lockToken)) {
throw logger.logThrowableAsError(new NullPointerException("'lockToken' cannot be null."));
} else if (lockToken.isEmpty()) {
throw logger.logThrowableAsError(new IllegalArgumentException("'lockToken' cannot be empty."));
} else if (receiverOptions.isSessionReceiver()) {
throw logger.logThrowableAsError(new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", lockToken)));
} else if (maxLockRenewalDuration == null) {
throw logger.logThrowableAsError(new NullPointerException("'maxLockRenewalDuration' cannot be null."));
} else if (maxLockRenewalDuration.isNegative()) {
throw logger.logThrowableAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
return new LockRenewalOperation(lockToken, maxLockRenewalDuration, false, this::renewMessageLock);
}
/**
* Gets and starts the auto lock renewal for a session with the given lock.
*
* @param sessionId Id for the session to renew.
* @param maxLockRenewalDuration Maximum duration to keep renewing the lock token.
* @return A lock renewal operation for the message.
* @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed.
*/
/**
* Gets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @return The session state or an empty Mono if there is no state set for the session.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<byte[]> getSessionState(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot get session state on a non-session receiver."));
}
if (unnamedSessionManager != null) {
return unnamedSessionManager.getSessionState(sessionId);
} else {
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId)));
}
}
/**
* Reads the next active message without changing the state of the receiver or the message source. The first call to
* {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent
* message in the entity.
*
* @return A peeked {@link ServiceBusReceivedMessage}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessage() {
return peekMessage(receiverOptions.getSessionId());
}
/**
* Reads the next active message without changing the state of the receiver or the message source. The first call to
* {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent
* message in the entity.
*
* @param sessionId Session id of the message to peek from. {@code null} if there is no session.
*
* @return A peeked {@link ServiceBusReceivedMessage}.
* @see <a href="https:
*
* @throws IllegalStateException if the receiver is disposed.
*/
public Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> {
final long sequence = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek message from sequence number: {}", sequence);
return channel.peek(sequence, sessionId, getLinkName(sessionId));
})
.handle((message, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, message.getSequenceNumber()));
logger.verbose("Updating last peeked sequence number: {}", current);
sink.next(message);
});
}
/**
* Starting from the given sequence number, reads next the active message without changing the state of the receiver
* or the message source.
*
* @param sequenceNumber The sequence number from where to read the message.
*
* @return A peeked {@link ServiceBusReceivedMessage}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber) {
return peekMessageAt(sequenceNumber, receiverOptions.getSessionId());
}
/**
* Starting from the given sequence number, reads next the active message without changing the state of the receiver
* or the message source.
*
* @param sequenceNumber The sequence number from where to read the message.
* @param sessionId Session id of the message to peek from. {@code null} if there is no session.
*
* @return A peeked {@link ServiceBusReceivedMessage}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId)));
}
/**
* Reads the next batch of active messages without changing the state of the receiver or the message source.
*
* @param maxMessages The number of messages.
*
* @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} that are peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) {
return peekMessages(maxMessages, receiverOptions.getSessionId());
}
/**
* Reads the next batch of active messages without changing the state of the receiver or the message source.
*
* @param maxMessages The number of messages.
* @param sessionId Session id of the messages to peek from. {@code null} if there is no session.
*
* @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> {
final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek batch from sequence number: {}", nextSequenceNumber);
final Flux<ServiceBusReceivedMessage> messages =
node.peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages);
final Mono<ServiceBusReceivedMessage> handle = messages
.switchIfEmpty(Mono.fromCallable(() -> {
ServiceBusReceivedMessage emptyMessage = new ServiceBusReceivedMessage(new byte[0]);
emptyMessage.setSequenceNumber(lastPeekedSequenceNumber.get());
return emptyMessage;
}))
.last()
.handle((last, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, last.getSequenceNumber()));
logger.verbose("Last peeked sequence number in batch: {}", current);
sink.complete();
});
return Flux.merge(messages, handle);
});
}
/**
* Starting from the given sequence number, reads the next batch of active messages without changing the state of
* the receiver or the message source.
*
* @param maxMessages The number of messages.
* @param sequenceNumber The sequence number from where to start reading messages.
*
* @return A {@link Flux} of {@link ServiceBusReceivedMessage} peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber) {
return peekMessagesAt(maxMessages, sequenceNumber, receiverOptions.getSessionId());
}
/**
* Starting from the given sequence number, reads the next batch of active messages without changing the state of
* the receiver or the message source.
*
* @param maxMessages The number of messages.
* @param sequenceNumber The sequence number from where to start reading messages.
* @param sessionId Session id of the messages to peek from. {@code null} if there is no session.
*
* @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages));
}
/**
* Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus
* entity. This Flux continuously receives messages from a Service Bus entity until either:
*
* <ul>
* <li>The receiver is closed.</li>
* <li>The subscription to the Flux is disposed.</li>
* <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux
* {@link Flux
* <li>An {@link AmqpException} occurs that causes the receive link to stop.</li>
* </ul>
*
* @return An <b>infinite</b> stream of messages from the Service Bus entity.
*/
public Flux<ServiceBusReceivedMessageContext> receiveMessages() {
if (unnamedSessionManager != null) {
return unnamedSessionManager.receive();
} else {
return getOrCreateConsumer().receive().map(ServiceBusReceivedMessageContext::new);
}
}
/**
* Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using
* sequence number.
*
* @param sequenceNumber The {@link ServiceBusReceivedMessage
* message.
*
* @return A deferred message with the matching {@code sequenceNumber}.
*/
public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) {
return receiveDeferredMessage(sequenceNumber, receiverOptions.getSessionId());
}
/**
* Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using
* sequence number.
*
* @param sequenceNumber The {@link ServiceBusReceivedMessage
* message.
* @param sessionId Session id of the deferred message. {@code null} if there is no session.
*
* @return A deferred message with the matching {@code sequenceNumber}.
*/
public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) {
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(),
sessionId, getLinkName(sessionId), Collections.singleton(sequenceNumber)).last())
.map(receivedMessage -> {
if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) {
return receivedMessage;
}
if (receiverOptions.getReceiveMode() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil()));
}
return receivedMessage;
});
}
/**
* Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received
* by using sequence number.
*
* @param sequenceNumbers The sequence numbers of the deferred messages.
*
* @return A {@link Flux} of deferred {@link ServiceBusReceivedMessage messages}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) {
return receiveDeferredMessages(sequenceNumbers, receiverOptions.getSessionId());
}
/**
* Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received
* by using sequence number.
*
* @param sequenceNumbers The sequence numbers of the deferred messages.
* @param sessionId Session id of the deferred messages. {@code null} if there is no session.
*
* @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers,
String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(),
sessionId, getLinkName(sessionId), sequenceNumbers))
.map(receivedMessage -> {
if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) {
return receivedMessage;
}
if (receiverOptions.getReceiveMode() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil()));
}
return receivedMessage;
});
}
/**
* Asynchronously renews the lock on the specified message. The lock will be renewed based on the setting specified
* on the entity. When a message is received in {@link ReceiveMode
* server for this receiver instance for a duration as specified during the Queue creation (LockDuration). If
* processing of the message requires longer than this duration, the lock needs to be renewed. For each renewal, the
* lock is reset to the entity's LockDuration value.
*
* @param lockToken Lock token of the message to renew.
*
* @return The new expiration time for the message.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalStateException if the receiver is a session receiver.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Instant> renewMessageLock(String lockToken) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock")));
} else if (Objects.isNull(lockToken)) {
return monoError(logger, new NullPointerException("'lockToken' cannot be null."));
} else if (lockToken.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'lockToken' cannot be empty."));
} else if (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", lockToken)));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(serviceBusManagementNode ->
serviceBusManagementNode.renewMessageLock(lockToken, getLinkName(null)))
.map(instant -> managementNodeLocks.addOrUpdate(lockToken, instant));
}
/**
* Sets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @return The next expiration time for the session lock.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<Instant> renewSessionLock(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot renew session lock on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.renewSessionLock(sessionId, linkName));
}
/**
* Sets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
* @param sessionState State to set on the session.
*
* @return A Mono that completes when the session is set
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<Void> setSessionState(String sessionId, byte[] sessionState) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot set session state on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName));
}
/**
* Starts a new service side transaction. The {@link ServiceBusTransactionContext} should be passed to all
* operations that needs to be in this transaction.
*
* <p><strong>Create a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.createTransaction}
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<ServiceBusTransactionContext> createTransaction() {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.createTransaction())
.map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()));
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Commit a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.commitTransaction}
*
* @param transactionContext to be committed.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<Void> commitTransaction(ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "commitTransaction")));
}
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Rollbacks the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Rollback a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.rollbackTransaction}
*
* @param transactionContext to be rollbacked.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<Void> rollbackTransaction(ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "rollbackTransaction")));
}
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Disposes of the consumer by closing the underlying connection to the service.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
logger.info("Removing receiver links.");
final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null);
if (disposed != null) {
disposed.close();
}
if (unnamedSessionManager != null) {
unnamedSessionManager.close();
}
onClientClose.run();
}
/**
* @return receiver options set by user;
*/
ReceiverOptions getReceiverOptions() {
return receiverOptions;
}
/**
* Gets whether or not the management node contains the message lock token and it has not expired. Lock tokens are
* held by the management node when they are received from the management node or management operations are
* performed using that {@code lockToken}.
*
* @param lockToken Lock token to check for.
*
* @return {@code true} if the management node contains the lock token and false otherwise.
*/
private boolean isManagementToken(String lockToken) {
return managementNodeLocks.contains(lockToken);
}
private Mono<Void> updateDisposition(String lockToken, DispositionStatus dispositionStatus,
String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify,
String sessionId, ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, dispositionStatus.getValue())));
} else if (Objects.isNull(lockToken)) {
return monoError(logger, new NullPointerException("'lockToken' cannot be null."));
} else if (lockToken.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'lockToken' cannot be empty."));
}
if (receiverOptions.getReceiveMode() != ReceiveMode.PEEK_LOCK) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format(
"'%s' is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE.", dispositionStatus))));
}
final String sessionIdToUse;
if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) {
sessionIdToUse = receiverOptions.getSessionId();
} else {
sessionIdToUse = sessionId;
}
logger.info("{}: Update started. Disposition: {}. Lock: {}. SessionId {}.", entityPath, dispositionStatus,
lockToken, sessionIdToUse);
final Mono<Void> performOnManagement = connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.updateDisposition(lockToken, dispositionStatus, deadLetterReason,
deadLetterErrorDescription, propertiesToModify, sessionId, getLinkName(sessionId), transactionContext))
.then(Mono.fromRunnable(() -> {
logger.info("{}: Management node Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
managementNodeLocks.remove(lockToken);
}));
if (unnamedSessionManager != null) {
return unnamedSessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify,
deadLetterReason, deadLetterErrorDescription, transactionContext)
.flatMap(isSuccess -> {
if (isSuccess) {
return Mono.empty();
}
logger.info("Could not perform on session manger. Performing on management node.");
return performOnManagement;
});
}
final ServiceBusAsyncConsumer existingConsumer = consumer.get();
if (isManagementToken(lockToken) || existingConsumer == null) {
return performOnManagement;
} else {
return existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason,
deadLetterErrorDescription, propertiesToModify, transactionContext)
.then(Mono.fromRunnable(() -> logger.info("{}: Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken)));
}
}
private ServiceBusAsyncConsumer getOrCreateConsumer() {
final ServiceBusAsyncConsumer existing = consumer.get();
if (existing != null) {
return existing;
}
final String linkName = StringUtil.getRandomString(entityPath);
logger.info("{}: Creating consumer for link '{}'", entityPath, linkName);
final Flux<ServiceBusReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> {
if (receiverOptions.isSessionReceiver()) {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType, receiverOptions.getSessionId());
} else {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType);
}
})
.doOnNext(next -> {
final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]"
+ " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]";
logger.verbose(format, next.getEntityPath(), receiverOptions.getReceiveMode(),
CoreUtils.isNullOrEmpty(receiverOptions.getSessionId()), "N/A", entityType);
})
.repeat();
final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions());
final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith(
new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy,
receiverOptions.getReceiveMode()));
final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor,
messageSerializer, receiverOptions.getPrefetchCount());
if (consumer.compareAndSet(null, newConsumer)) {
return newConsumer;
} else {
newConsumer.close();
return consumer.get();
}
}
/**
* If the receiver has not connected via {@link
* through the management node.
*
* @return The name of the receive link, or null of it has not connected via a receive link.
*/
private String getLinkName(String sessionId) {
if (unnamedSessionManager != null && !CoreUtils.isNullOrEmpty(sessionId)) {
return unnamedSessionManager.getLinkName(sessionId);
} else if (!CoreUtils.isNullOrEmpty(sessionId) && !receiverOptions.isSessionReceiver()) {
return null;
} else {
final ServiceBusAsyncConsumer existing = consumer.get();
return existing != null ? existing.getLinkName() : null;
}
}
} | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final LockContainer<LockRenewalOperation> renewalContainer;
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final LockContainer<Instant> managementNodeLocks;
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class);
private final String fullyQualifiedNamespace;
private final String entityPath;
private final MessagingEntityType entityType;
private final ReceiverOptions receiverOptions;
private final ServiceBusConnectionProcessor connectionProcessor;
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
private final Runnable onClientClose;
private final UnnamedSessionManager unnamedSessionManager;
private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1);
private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>();
/**
* Creates a receiver that listens to a Service Bus resource.
*
* @param fullyQualifiedNamespace The fully qualified domain name for the Service Bus resource.
* @param entityPath The name of the topic or queue.
* @param entityType The type of the Service Bus resource.
* @param receiverOptions Options when receiving messages.
* @param connectionProcessor The AMQP connection to the Service Bus resource.
* @param tracerProvider Tracer for telemetry.
* @param messageSerializer Serializes and deserializes Service Bus messages.
* @param onClientClose Operation to run when the client completes.
*/
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null.");
this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null.");
this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'");
this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null.");
this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. lockToken[{}]. status[{}]. throwable[{}].",
renewal.getLockToken(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
this.unnamedSessionManager = null;
}
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose,
UnnamedSessionManager unnamedSessionManager) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null.");
this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null.");
this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'");
this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null.");
this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.unnamedSessionManager = Objects.requireNonNull(unnamedSessionManager, "'sessionManager' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. sessionId[{}]. status[{}]. throwable[{}]",
renewal.getSessionId(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
}
/**
* Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to
* {@code {yournamespace}.servicebus.windows.net}.
*
* @return The fully qualified Service Bus namespace that the connection is associated with.
*/
public String getFullyQualifiedNamespace() {
return fullyQualifiedNamespace;
}
/**
* Gets the Service Bus resource this client interacts with.
*
* @return The Service Bus resource this client interacts with.
*/
public String getEntityPath() {
return entityPath;
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available
* again for processing. Abandoning a message will increase the delivery count on the message.
*
* @param lockToken Lock token of the message.
*
* @return A {@link Mono} that completes when the Service Bus abandon operation completes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken) {
return abandon(lockToken, receiverOptions.getSessionId());
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available
* again for processing. Abandoning a message will increase the delivery count on the message.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to abandon. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the Service Bus abandon operation completes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken, String sessionId) {
return abandon(lockToken, null, sessionId);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties.
* This will make the message available again for processing. Abandoning a message will increase the delivery count
* on the message.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Properties to modify on the message.
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken, Map<String, Object> propertiesToModify) {
return abandon(lockToken, propertiesToModify, receiverOptions.getSessionId());
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties.
* This will make the message available again for processing. Abandoning a message will increase the delivery count
* on the message.
* <p><strong>Complete a message with a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.abandonMessageWithTransaction}
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Properties to modify on the message.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
return abandon(lockToken, propertiesToModify, receiverOptions.getSessionId(), transactionContext);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties.
* This will make the message available again for processing. Abandoning a message will increase the delivery count
* on the message.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Properties to modify on the message.
* @param sessionId Session id of the message to abandon. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the Service Bus abandon operation completes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken, Map<String, Object> propertiesToModify, String sessionId) {
return updateDisposition(lockToken, DispositionStatus.ABANDONED, null, null,
propertiesToModify, sessionId, null);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties.
* This will make the message available again for processing. Abandoning a message will increase the delivery count
* on the message.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Properties to modify on the message.
* @param sessionId Session id of the message to abandon. {@code null} if there is no session.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus abandon operation completes.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken, Map<String, Object> propertiesToModify, String sessionId,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return updateDisposition(lockToken, DispositionStatus.ABANDONED, null, null,
propertiesToModify, sessionId, transactionContext);
}
/**
* Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the
* service.
*
* @param lockToken Lock token of the message.
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> complete(String lockToken) {
return updateDisposition(lockToken, DispositionStatus.COMPLETED, null, null,
null, receiverOptions.getSessionId(), null);
}
/**
* Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the
* service.
* <p><strong>Complete a message with a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.completeMessageWithTransaction}
*
* @param lockToken Lock token of the message.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> complete(String lockToken, ServiceBusTransactionContext transactionContext) {
return complete(lockToken, receiverOptions.getSessionId(), transactionContext);
}
/**
* Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the
* service.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to complete. {@code null} if there is no session.
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> complete(String lockToken, String sessionId) {
return updateDisposition(lockToken, DispositionStatus.COMPLETED, null, null,
null, sessionId, null);
}
/**
* Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the
* service.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to complete. {@code null} if there is no session.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> complete(String lockToken, String sessionId,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return updateDisposition(lockToken, DispositionStatus.COMPLETED, null, null,
null, sessionId, transactionContext);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred
* subqueue.
*
* @param lockToken Lock token of the message.
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken) {
return defer(lockToken, receiverOptions.getSessionId());
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred
* subqueue.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to defer. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken, String sessionId) {
return defer(lockToken, null, sessionId);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will
* move message into the deferred subqueue.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Message properties to modify.
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken, Map<String, Object> propertiesToModify) {
return defer(lockToken, propertiesToModify, receiverOptions.getSessionId());
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will
* move message into the deferred subqueue.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Message properties to modify.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
return defer(lockToken, propertiesToModify, receiverOptions.getSessionId(), transactionContext);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will
* move message into the deferred subqueue.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Message properties to modify.
* @param sessionId Session id of the message to defer. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken, Map<String, Object> propertiesToModify, String sessionId) {
return updateDisposition(lockToken, DispositionStatus.DEFERRED, null, null,
propertiesToModify, sessionId, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will
* move message into the deferred subqueue.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Message properties to modify.
* @param sessionId Session id of the message to defer. {@code null} if there is no session.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken, Map<String, Object> propertiesToModify, String sessionId,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return updateDisposition(lockToken, DispositionStatus.DEFERRED, null, null,
propertiesToModify, sessionId, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue.
*
* @param lockToken Lock token of the message.
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(String lockToken) {
return deadLetter(lockToken, receiverOptions.getSessionId());
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to deadletter. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(String lockToken, String sessionId) {
return deadLetter(lockToken, DEFAULT_DEAD_LETTER_OPTIONS, sessionId);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to deadletter. {@code null} if there is no session.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(String lockToken, String sessionId,
ServiceBusTransactionContext transactionContext) {
return deadLetter(lockToken, DEFAULT_DEAD_LETTER_OPTIONS, sessionId, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param lockToken Lock token of the message.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken} or {@code deadLetterOptions} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> deadLetter(String lockToken, DeadLetterOptions deadLetterOptions) {
return deadLetter(lockToken, deadLetterOptions, receiverOptions.getSessionId());
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param lockToken Lock token of the message.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken}, {@code deadLetterOptions}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> deadLetter(String lockToken, DeadLetterOptions deadLetterOptions,
ServiceBusTransactionContext transactionContext) {
return deadLetter(lockToken, deadLetterOptions, receiverOptions.getSessionId(), transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param lockToken Lock token of the message.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param sessionId Session id of the message to deadletter. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> deadLetter(String lockToken, DeadLetterOptions deadLetterOptions, String sessionId) {
if (Objects.isNull(deadLetterOptions)) {
return monoError(logger, new NullPointerException("'deadLetterOptions' cannot be null."));
}
return updateDisposition(lockToken, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(), sessionId,
null);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param lockToken Lock token of the message.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param sessionId Session id of the message to deadletter. {@code null} if there is no session.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> deadLetter(String lockToken, DeadLetterOptions deadLetterOptions, String sessionId,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return updateDisposition(lockToken, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(), sessionId,
transactionContext);
}
/**
* Gets and starts the auto lock renewal for a message with the given lock.
*
* @param lockToken Lock token of the message.
* @param maxLockRenewalDuration Maximum duration to keep renewing the lock token.
*
* @return A lock renewal operation for the message.
* @throws NullPointerException if {@code lockToken} or {@code maxLockRenewalDuration} is null.
* @throws IllegalArgumentException if {@code lockToken} is an empty string.
* @throws IllegalStateException if the receiver is a session receiver or the receiver is disposed.
*/
public LockRenewalOperation getAutoRenewMessageLock(String lockToken, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
throw logger.logExceptionAsError(new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewMessageLock")));
} else if (Objects.isNull(lockToken)) {
throw logger.logExceptionAsError(new NullPointerException("'lockToken' cannot be null."));
} else if (lockToken.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'lockToken' cannot be empty."));
} else if (receiverOptions.isSessionReceiver()) {
throw logger.logExceptionAsError(new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", lockToken)));
} else if (maxLockRenewalDuration == null) {
throw logger.logExceptionAsError(new NullPointerException("'maxLockRenewalDuration' cannot be null."));
} else if (maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
final LockRenewalOperation operation = new LockRenewalOperation(lockToken, maxLockRenewalDuration, false,
this::renewMessageLock);
renewalContainer.addOrUpdate(lockToken, Instant.now().plus(maxLockRenewalDuration), operation);
return operation;
}
/**
* Gets and starts the auto lock renewal for a session with the given lock.
*
* @param sessionId Id for the session to renew.
* @param maxLockRenewalDuration Maximum duration to keep renewing the lock token.
*
* @return A lock renewal operation for the message.
* @throws NullPointerException if {@code sessionId} or {@code maxLockRenewalDuration} is null.
* @throws IllegalArgumentException if {@code lockToken} is an empty string.
* @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed.
*/
/**
* Gets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @return The session state or an empty Mono if there is no state set for the session.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<byte[]> getSessionState(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot get session state on a non-session receiver."));
}
if (unnamedSessionManager != null) {
return unnamedSessionManager.getSessionState(sessionId);
} else {
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId)));
}
}
/**
* Reads the next active message without changing the state of the receiver or the message source. The first call to
* {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent
* message in the entity.
*
* @return A peeked {@link ServiceBusReceivedMessage}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessage() {
return peekMessage(receiverOptions.getSessionId());
}
/**
* Reads the next active message without changing the state of the receiver or the message source. The first call to
* {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent
* message in the entity.
*
* @param sessionId Session id of the message to peek from. {@code null} if there is no session.
*
* @return A peeked {@link ServiceBusReceivedMessage}.
* @throws IllegalStateException if the receiver is disposed.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> {
final long sequence = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek message from sequence number: {}", sequence);
return channel.peek(sequence, sessionId, getLinkName(sessionId));
})
.handle((message, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, message.getSequenceNumber()));
logger.verbose("Updating last peeked sequence number: {}", current);
sink.next(message);
});
}
/**
* Starting from the given sequence number, reads next the active message without changing the state of the receiver
* or the message source.
*
* @param sequenceNumber The sequence number from where to read the message.
*
* @return A peeked {@link ServiceBusReceivedMessage}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber) {
return peekMessageAt(sequenceNumber, receiverOptions.getSessionId());
}
/**
* Starting from the given sequence number, reads next the active message without changing the state of the receiver
* or the message source.
*
* @param sequenceNumber The sequence number from where to read the message.
* @param sessionId Session id of the message to peek from. {@code null} if there is no session.
*
* @return A peeked {@link ServiceBusReceivedMessage}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId)));
}
/**
* Reads the next batch of active messages without changing the state of the receiver or the message source.
*
* @param maxMessages The number of messages.
*
* @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} that are peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) {
return peekMessages(maxMessages, receiverOptions.getSessionId());
}
/**
* Reads the next batch of active messages without changing the state of the receiver or the message source.
*
* @param maxMessages The number of messages.
* @param sessionId Session id of the messages to peek from. {@code null} if there is no session.
*
* @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> {
final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek batch from sequence number: {}", nextSequenceNumber);
final Flux<ServiceBusReceivedMessage> messages =
node.peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages);
final Mono<ServiceBusReceivedMessage> handle = messages
.switchIfEmpty(Mono.fromCallable(() -> {
ServiceBusReceivedMessage emptyMessage = new ServiceBusReceivedMessage(new byte[0]);
emptyMessage.setSequenceNumber(lastPeekedSequenceNumber.get());
return emptyMessage;
}))
.last()
.handle((last, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, last.getSequenceNumber()));
logger.verbose("Last peeked sequence number in batch: {}", current);
sink.complete();
});
return Flux.merge(messages, handle);
});
}
/**
* Starting from the given sequence number, reads the next batch of active messages without changing the state of
* the receiver or the message source.
*
* @param maxMessages The number of messages.
* @param sequenceNumber The sequence number from where to start reading messages.
*
* @return A {@link Flux} of {@link ServiceBusReceivedMessage} peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber) {
return peekMessagesAt(maxMessages, sequenceNumber, receiverOptions.getSessionId());
}
/**
* Starting from the given sequence number, reads the next batch of active messages without changing the state of
* the receiver or the message source.
*
* @param maxMessages The number of messages.
* @param sequenceNumber The sequence number from where to start reading messages.
* @param sessionId Session id of the messages to peek from. {@code null} if there is no session.
*
* @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages));
}
/**
* Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity.
* This Flux continuously receives messages from a Service Bus entity until either:
*
* <ul>
* <li>The receiver is closed.</li>
* <li>The subscription to the Flux is disposed.</li>
* <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux
* {@link Flux
* <li>An {@link AmqpException} occurs that causes the receive link to stop.</li>
* </ul>
*
* @return An <b>infinite</b> stream of messages from the Service Bus entity.
*/
public Flux<ServiceBusReceivedMessageContext> receiveMessages() {
if (unnamedSessionManager != null) {
return unnamedSessionManager.receive();
} else {
return getOrCreateConsumer().receive().map(ServiceBusReceivedMessageContext::new);
}
}
/**
* Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using
* sequence number.
*
* @param sequenceNumber The {@link ServiceBusReceivedMessage
* message.
*
* @return A deferred message with the matching {@code sequenceNumber}.
*/
public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) {
return receiveDeferredMessage(sequenceNumber, receiverOptions.getSessionId());
}
/**
* Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using
* sequence number.
*
* @param sequenceNumber The {@link ServiceBusReceivedMessage
* message.
* @param sessionId Session id of the deferred message. {@code null} if there is no session.
*
* @return A deferred message with the matching {@code sequenceNumber}.
*/
public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) {
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(),
sessionId, getLinkName(sessionId), Collections.singleton(sequenceNumber)).last())
.map(receivedMessage -> {
if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) {
return receivedMessage;
}
if (receiverOptions.getReceiveMode() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil(), receivedMessage.getLockedUntil()));
}
return receivedMessage;
});
}
/**
* Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received
* by using sequence number.
*
* @param sequenceNumbers The sequence numbers of the deferred messages.
*
* @return A {@link Flux} of deferred {@link ServiceBusReceivedMessage messages}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) {
return receiveDeferredMessages(sequenceNumbers, receiverOptions.getSessionId());
}
/**
* Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received
* by using sequence number.
*
* @param sequenceNumbers The sequence numbers of the deferred messages.
* @param sessionId Session id of the deferred messages. {@code null} if there is no session.
*
* @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers,
String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(),
sessionId, getLinkName(sessionId), sequenceNumbers))
.map(receivedMessage -> {
if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) {
return receivedMessage;
}
if (receiverOptions.getReceiveMode() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil(), receivedMessage.getLockedUntil()));
}
return receivedMessage;
});
}
/**
* Asynchronously renews the lock on the specified message. The lock will be renewed based on the setting specified
* on the entity. When a message is received in {@link ReceiveMode
* server for this receiver instance for a duration as specified during the Queue creation (LockDuration). If
* processing of the message requires longer than this duration, the lock needs to be renewed. For each renewal, the
* lock is reset to the entity's LockDuration value.
*
* @param lockToken Lock token of the message to renew.
*
* @return The new expiration time for the message.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalStateException if the receiver is a session receiver.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Instant> renewMessageLock(String lockToken) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock")));
} else if (Objects.isNull(lockToken)) {
return monoError(logger, new NullPointerException("'lockToken' cannot be null."));
} else if (lockToken.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'lockToken' cannot be empty."));
} else if (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", lockToken)));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(serviceBusManagementNode ->
serviceBusManagementNode.renewMessageLock(lockToken, getLinkName(null)))
.map(instant -> managementNodeLocks.addOrUpdate(lockToken, instant, instant));
}
/**
* Sets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @return The next expiration time for the session lock.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<Instant> renewSessionLock(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot renew session lock on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.renewSessionLock(sessionId, linkName));
}
/**
* Sets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
* @param sessionState State to set on the session.
*
* @return A Mono that completes when the session is set
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<Void> setSessionState(String sessionId, byte[] sessionState) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot set session state on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName));
}
/**
* Starts a new service side transaction. The {@link ServiceBusTransactionContext} should be passed to all
* operations that needs to be in this transaction.
*
* <p><strong>Create a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.createTransaction}
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<ServiceBusTransactionContext> createTransaction() {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.createTransaction())
.map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()));
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Commit a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.commitTransaction}
*
* @param transactionContext to be committed.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
public Mono<Void> commitTransaction(ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "commitTransaction")));
}
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Rollbacks the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Rollback a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.rollbackTransaction}
*
* @param transactionContext to be rollbacked.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
public Mono<Void> rollbackTransaction(ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "rollbackTransaction")));
}
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Disposes of the consumer by closing the underlying connection to the service.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
logger.info("Removing receiver links.");
final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null);
if (disposed != null) {
disposed.close();
}
if (unnamedSessionManager != null) {
unnamedSessionManager.close();
}
onClientClose.run();
}
/**
* @return receiver options set by user;
*/
ReceiverOptions getReceiverOptions() {
return receiverOptions;
}
/**
* Gets whether or not the management node contains the message lock token and it has not expired. Lock tokens are
* held by the management node when they are received from the management node or management operations are
* performed using that {@code lockToken}.
*
* @param lockToken Lock token to check for.
*
* @return {@code true} if the management node contains the lock token and false otherwise.
*/
private boolean isManagementToken(String lockToken) {
return managementNodeLocks.containsUnexpired(lockToken);
}
private Mono<Void> updateDisposition(String lockToken, DispositionStatus dispositionStatus,
String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify,
String sessionId, ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, dispositionStatus.getValue())));
} else if (Objects.isNull(lockToken)) {
return monoError(logger, new NullPointerException("'lockToken' cannot be null."));
} else if (lockToken.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'lockToken' cannot be empty."));
}
if (receiverOptions.getReceiveMode() != ReceiveMode.PEEK_LOCK) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format(
"'%s' is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE.", dispositionStatus))));
}
final String sessionIdToUse;
if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) {
sessionIdToUse = receiverOptions.getSessionId();
} else {
sessionIdToUse = sessionId;
}
logger.info("{}: Update started. Disposition: {}. Lock: {}. SessionId {}.", entityPath, dispositionStatus,
lockToken, sessionIdToUse);
final Mono<Void> performOnManagement = connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.updateDisposition(lockToken, dispositionStatus, deadLetterReason,
deadLetterErrorDescription, propertiesToModify, sessionId, getLinkName(sessionId), transactionContext))
.then(Mono.fromRunnable(() -> {
logger.info("{}: Management node Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
managementNodeLocks.remove(lockToken);
renewalContainer.remove(lockToken);
}));
if (unnamedSessionManager != null) {
return unnamedSessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify,
deadLetterReason, deadLetterErrorDescription, transactionContext)
.flatMap(isSuccess -> {
if (isSuccess) {
renewalContainer.remove(lockToken);
return Mono.empty();
}
logger.info("Could not perform on session manger. Performing on management node.");
return performOnManagement;
});
}
final ServiceBusAsyncConsumer existingConsumer = consumer.get();
if (isManagementToken(lockToken) || existingConsumer == null) {
return performOnManagement;
} else {
return existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason,
deadLetterErrorDescription, propertiesToModify, transactionContext)
.then(Mono.fromRunnable(() -> {
logger.info("{}: Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
renewalContainer.remove(lockToken);
}));
}
}
private ServiceBusAsyncConsumer getOrCreateConsumer() {
final ServiceBusAsyncConsumer existing = consumer.get();
if (existing != null) {
return existing;
}
final String linkName = StringUtil.getRandomString(entityPath);
logger.info("{}: Creating consumer for link '{}'", entityPath, linkName);
final Flux<ServiceBusReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> {
if (receiverOptions.isSessionReceiver()) {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType, receiverOptions.getSessionId());
} else {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType);
}
})
.doOnNext(next -> {
final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]"
+ " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]";
logger.verbose(format, next.getEntityPath(), receiverOptions.getReceiveMode(),
CoreUtils.isNullOrEmpty(receiverOptions.getSessionId()), "N/A", entityType);
})
.repeat();
final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions());
final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith(
new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy,
receiverOptions.getReceiveMode()));
final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor,
messageSerializer, receiverOptions.getPrefetchCount());
if (consumer.compareAndSet(null, newConsumer)) {
return newConsumer;
} else {
newConsumer.close();
return consumer.get();
}
}
/**
* If the receiver has not connected via {@link
* through the management node.
*
* @return The name of the receive link, or null of it has not connected via a receive link.
*/
private String getLinkName(String sessionId) {
if (unnamedSessionManager != null && !CoreUtils.isNullOrEmpty(sessionId)) {
return unnamedSessionManager.getLinkName(sessionId);
} else if (!CoreUtils.isNullOrEmpty(sessionId) && !receiverOptions.isSessionReceiver()) {
return null;
} else {
final ServiceBusAsyncConsumer existing = consumer.get();
return existing != null ? existing.getLinkName() : null;
}
}
} |
The other code in the builder allows for `retryPolicy` to be `null`. I would remove the `null` check and just document that if this is `null` a default `RetryPolicy` will be used. | public DigitalTwinsClientBuilder retryOptions(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
return this;
} | this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null."); | public DigitalTwinsClientBuilder retryOptions(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
return this;
} | class DigitalTwinsClientBuilder {
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions logOptions;
private RetryPolicy retryPolicy;
private static HttpPipeline buildPipeline(TokenCredential tokenCredential, String endpoint,
HttpLogOptions logOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, RetryPolicy retryPolicy) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential, GetAuthorizationScopes(endpoint));
policies.add(credentialPolicy);
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(logOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private static String[] GetAuthorizationScopes(String endpoint) {
String adtPublicCloudAppId = "https:
String defaultPermissionConsent = "/.default";
if (endpoint.indexOf("azure.net") > 0
|| endpoint.indexOf("ppe.net") > 0) {
return new String[]{adtPublicCloudAppId + defaultPermissionConsent};
}
throw new IllegalArgumentException(String.format("Azure digital twins instance endpoint %s is not valid.", endpoint));
}
/**
* Create a {@link DigitalTwinsClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsClient
*/
public DigitalTwinsClient buildClient() {
return new DigitalTwinsClient(buildAsyncClient());
}
/**
* Create a {@link DigitalTwinsAsyncClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsAsyncClient
*/
public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPolicy = this.retryPolicy != null ? this.retryPolicy : new RetryPolicy();
if (this.httpPipeline == null)
{
this.httpPipeline = buildPipeline(
this.tokenCredential,
this.endpoint,
this.logOptions,
this.httpClient,
this.additionalPolicies,
this.retryPolicy);
}
return new DigitalTwinsAsyncClient(this.httpPipeline, this.serviceVersion, this.endpoint);
}
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Set the authentication token provider that the built client will use for all service requests. This field is
* mandatory to set unless you set the http pipeline directly and that set pipeline has an authentication policy configured.
*
* @param tokenCredential the authentication token provider.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder tokenCredential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link DigitalTwinsServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder serviceVersion(DigitalTwinsServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code logOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public DigitalTwinsClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the request retry options for all the requests made through the client. By default, the pipeline will
* use an exponential backoff retry value as detailed in {@link RetryPolicy
*
* @param retryPolicy {@link RetryPolicy}.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code retryOptions} is {@code null}.
*/
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpPipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
} | class DigitalTwinsClientBuilder {
private static final String[] adtPublicScope = new String[]{"https:
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions logOptions;
private RetryPolicy retryPolicy;
private static HttpPipeline buildPipeline(TokenCredential tokenCredential, String endpoint,
HttpLogOptions logOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, RetryPolicy retryPolicy) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential, getAuthorizationScopes(endpoint));
policies.add(credentialPolicy);
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(logOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private static String[] getAuthorizationScopes(String endpoint) {
if (endpoint.indexOf("azure.net") > 0
|| endpoint.indexOf("ppe.net") > 0) {
return adtPublicScope;
}
throw new IllegalArgumentException(String.format("Azure digital twins instance endpoint %s is not valid.", endpoint));
}
/**
* Create a {@link DigitalTwinsClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsClient
*/
public DigitalTwinsClient buildClient() {
return new DigitalTwinsClient(buildAsyncClient());
}
/**
* Create a {@link DigitalTwinsAsyncClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsAsyncClient
*/
public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPolicy = this.retryPolicy != null ? this.retryPolicy : new RetryPolicy();
if (this.httpPipeline == null) {
this.httpPipeline = buildPipeline(
this.tokenCredential,
this.endpoint,
this.logOptions,
this.httpClient,
this.additionalPolicies,
this.retryPolicy);
}
return new DigitalTwinsAsyncClient(this.httpPipeline, this.serviceVersion, this.endpoint);
}
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Set the authentication token provider that the built client will use for all service requests. This field is
* mandatory to set unless you set the http pipeline directly and that set pipeline has an authentication policy configured.
*
* @param tokenCredential the authentication token provider.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder tokenCredential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link DigitalTwinsServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder serviceVersion(DigitalTwinsServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code logOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = logOptions;
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public DigitalTwinsClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the request retry options for all the requests made through the client. By default, the pipeline will
* use an exponential backoff retry value as detailed in {@link RetryPolicy
*
* @param retryPolicy {@link RetryPolicy}.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code retryOptions} is {@code null}.
*/
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpPipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
} |
Are we also taking care of situation when , user complete a message but renew operation still try to renew and keep getting error in logs. After settlement of the message by user, How does that lock is not renewing automatically in background and filling the logs ? | void errors() throws InterruptedException {
final boolean isSession = true;
final Duration renewalPeriod = Duration.ofSeconds(2);
final Instant lockedUntil = Instant.now().plus(renewalPeriod);
final Duration maxDuration = Duration.ofSeconds(6);
final Duration totalSleepPeriod = renewalPeriod.plus(renewalPeriod).plusMillis(500);
final Throwable testError = new IllegalAccessException("A test error");
final AtomicReference<Instant> lastLockedUntil = new AtomicReference<>();
final Deque<Mono<Instant>> responses = new ArrayDeque<>();
responses.add(Mono.fromCallable(() -> {
final Instant plus = Instant.now().plus(renewalPeriod);
lastLockedUntil.set(plus);
return plus;
}));
responses.add(Mono.error(testError));
responses.add(Mono.fromCallable(() -> {
fail("Should not have been called.");
return Instant.now();
}));
when(renewalOperation.apply(A_LOCK_TOKEN)).thenAnswer(invocation -> {
final Mono<Instant> instantMono = responses.pollFirst();
return instantMono != null
? instantMono
: Mono.error(new IllegalStateException("Should have fetched an item."));
});
operation = new LockRenewalOperation(A_LOCK_TOKEN, maxDuration, isSession, renewalOperation, lockedUntil);
TimeUnit.MILLISECONDS.sleep(totalSleepPeriod.toMillis());
assertEquals(LockRenewalStatus.FAILED, operation.getStatus());
assertEquals(testError, operation.getThrowable());
assertEquals(lastLockedUntil.get(), operation.getLockedUntil());
} | void errors() throws InterruptedException {
final boolean isSession = true;
final Duration renewalPeriod = Duration.ofSeconds(2);
final Instant lockedUntil = Instant.now().plus(renewalPeriod);
final Duration maxDuration = Duration.ofSeconds(6);
final Duration totalSleepPeriod = renewalPeriod.plus(renewalPeriod).plusMillis(500);
final Throwable testError = new IllegalAccessException("A test error");
final AtomicReference<Instant> lastLockedUntil = new AtomicReference<>();
final Deque<Mono<Instant>> responses = new ArrayDeque<>();
responses.add(Mono.fromCallable(() -> {
final Instant plus = Instant.now().plus(renewalPeriod);
lastLockedUntil.set(plus);
return plus;
}));
responses.add(Mono.error(testError));
responses.add(Mono.fromCallable(() -> {
fail("Should not have been called.");
return Instant.now();
}));
when(renewalOperation.apply(A_LOCK_TOKEN)).thenAnswer(invocation -> {
final Mono<Instant> instantMono = responses.pollFirst();
return instantMono != null
? instantMono
: Mono.error(new IllegalStateException("Should have fetched an item."));
});
operation = new LockRenewalOperation(A_LOCK_TOKEN, maxDuration, isSession, renewalOperation, lockedUntil);
TimeUnit.MILLISECONDS.sleep(totalSleepPeriod.toMillis());
assertEquals(LockRenewalStatus.FAILED, operation.getStatus());
assertEquals(testError, operation.getThrowable());
assertEquals(lastLockedUntil.get(), operation.getLockedUntil());
} | class LockRenewalOperationTest {
private static final String A_LOCK_TOKEN = "a-lock-token";
private final ClientLogger logger = new ClientLogger(LockRenewalOperationTest.class);
private LockRenewalOperation operation;
@Mock
private Function<String, Mono<Instant>> renewalOperation;
@BeforeEach
void beforeEach() {
MockitoAnnotations.initMocks(this);
}
@AfterEach
void afterEach() {
if (operation != null) {
operation.close();
}
}
@ValueSource(booleans = {true, false})
@ParameterizedTest
void constructor(boolean isSession) {
final Duration renewalPeriod = Duration.ofSeconds(4);
final Instant lockedUntil = Instant.now().plus(renewalPeriod);
final Duration maxDuration = Duration.ofSeconds(20);
when(renewalOperation.apply(A_LOCK_TOKEN))
.thenReturn(Mono.fromCallable(() -> Instant.now().plus(renewalPeriod)));
operation = new LockRenewalOperation(A_LOCK_TOKEN, maxDuration, isSession, renewalOperation, lockedUntil);
if (isSession) {
assertEquals(A_LOCK_TOKEN, operation.getSessionId());
assertNull(operation.getLockToken());
} else {
assertEquals(A_LOCK_TOKEN, operation.getLockToken());
assertNull(operation.getSessionId());
}
assertEquals(lockedUntil, operation.getLockedUntil());
assertEquals(LockRenewalStatus.RUNNING, operation.getStatus());
assertNull(operation.getThrowable());
}
/**
* Verify that when an error occurs, it is displayed.
*/
@Test
/**
* Verifies that it stops renewing after the duration has elapsed.
*/
@Test
void completes() throws InterruptedException {
final Duration maxDuration = Duration.ofSeconds(8);
final Duration renewalPeriod = Duration.ofSeconds(3);
final int atMost = 4;
final Instant lockedUntil = Instant.now().plus(renewalPeriod);
final Duration totalSleepPeriod = maxDuration.plusMillis(500);
when(renewalOperation.apply(A_LOCK_TOKEN))
.thenReturn(Mono.fromCallable(() -> Instant.now().plus(renewalPeriod)));
operation = new LockRenewalOperation(A_LOCK_TOKEN, maxDuration, false, renewalOperation, lockedUntil);
Thread.sleep(totalSleepPeriod.toMillis());
logger.info("Finished renewals for first sleep.");
Thread.sleep(2000);
System.out.println("Finished second sleep. Should not have any more renewals.");
assertEquals(LockRenewalStatus.COMPLETE, operation.getStatus());
assertNull(operation.getThrowable());
assertTrue(lockedUntil.isBefore(operation.getLockedUntil()), String.format(
"initial lockedUntil[%s] is not before lockedUntil[%s]", lockedUntil, operation.getLockedUntil()));
verify(renewalOperation, atMost(atMost)).apply(A_LOCK_TOKEN);
}
/**
* Verify that we can cancel the operation.
*/
@Test
void cancellation() throws InterruptedException {
final Duration maxDuration = Duration.ofSeconds(20);
final Duration renewalPeriod = Duration.ofSeconds(3);
final int atMost = 2;
final Instant lockedUntil = Instant.now().plus(renewalPeriod);
final Duration totalSleepPeriod = renewalPeriod.plusMillis(1000);
when(renewalOperation.apply(A_LOCK_TOKEN))
.thenReturn(Mono.fromCallable(() -> Instant.now().plus(renewalPeriod)));
operation = new LockRenewalOperation(A_LOCK_TOKEN, maxDuration, false, renewalOperation, lockedUntil);
Thread.sleep(totalSleepPeriod.toMillis());
logger.info("Finished renewals for first sleep. Cancelling");
operation.close();
Thread.sleep(2000);
System.out.println("Finished second sleep. Should not have any more renewals.");
assertEquals(LockRenewalStatus.CANCELLED, operation.getStatus());
assertNull(operation.getThrowable());
assertTrue(lockedUntil.isBefore(operation.getLockedUntil()), String.format(
"initial lockedUntil[%s] is not before lockedUntil[%s]", lockedUntil, operation.getLockedUntil()));
verify(renewalOperation, atMost(atMost)).apply(A_LOCK_TOKEN);
}
/**
* Verify that when a duration of Duration.ZERO is passed, then we do not renew at all.
*/
@Test
void renewDurationZero() throws InterruptedException {
final Duration maxDuration = Duration.ZERO;
final Duration renewalPeriod = Duration.ofSeconds(3);
final Instant lockedUntil = Instant.now().plus(renewalPeriod);
when(renewalOperation.apply(A_LOCK_TOKEN))
.thenReturn(Mono.fromCallable(() -> Instant.now().plus(renewalPeriod)));
operation = new LockRenewalOperation(A_LOCK_TOKEN, maxDuration, false, renewalOperation, lockedUntil);
Thread.sleep(renewalPeriod.toMillis());
assertEquals(LockRenewalStatus.COMPLETE, operation.getStatus());
assertNull(operation.getThrowable());
assertEquals(lockedUntil, operation.getLockedUntil(), String.format(
"initial lockedUntil[%s] is not equal to lockedUntil[%s]", lockedUntil, operation.getLockedUntil()));
verify(renewalOperation, never()).apply(A_LOCK_TOKEN);
}
} | class LockRenewalOperationTest {
private static final String A_LOCK_TOKEN = "a-lock-token";
private final ClientLogger logger = new ClientLogger(LockRenewalOperationTest.class);
private LockRenewalOperation operation;
@Mock
private Function<String, Mono<Instant>> renewalOperation;
@BeforeEach
void beforeEach() {
MockitoAnnotations.initMocks(this);
}
@AfterEach
void afterEach() {
if (operation != null) {
operation.close();
}
}
@ValueSource(booleans = {true, false})
@ParameterizedTest
void constructor(boolean isSession) {
final Duration renewalPeriod = Duration.ofSeconds(4);
final Instant lockedUntil = Instant.now().plus(renewalPeriod);
final Duration maxDuration = Duration.ofSeconds(20);
when(renewalOperation.apply(A_LOCK_TOKEN))
.thenReturn(Mono.fromCallable(() -> Instant.now().plus(renewalPeriod)));
operation = new LockRenewalOperation(A_LOCK_TOKEN, maxDuration, isSession, renewalOperation, lockedUntil);
if (isSession) {
assertEquals(A_LOCK_TOKEN, operation.getSessionId());
assertNull(operation.getLockToken());
} else {
assertEquals(A_LOCK_TOKEN, operation.getLockToken());
assertNull(operation.getSessionId());
}
assertEquals(lockedUntil, operation.getLockedUntil());
assertEquals(LockRenewalStatus.RUNNING, operation.getStatus());
assertNull(operation.getThrowable());
}
/**
* Verify that when an error occurs, it is displayed.
*/
@Test
/**
* Verifies that it stops renewing after the duration has elapsed.
*/
@Test
void completes() throws InterruptedException {
final Duration maxDuration = Duration.ofSeconds(8);
final Duration renewalPeriod = Duration.ofSeconds(3);
final int atMost = 4;
final Instant lockedUntil = Instant.now().plus(renewalPeriod);
final Duration totalSleepPeriod = maxDuration.plusMillis(500);
when(renewalOperation.apply(A_LOCK_TOKEN))
.thenReturn(Mono.fromCallable(() -> Instant.now().plus(renewalPeriod)));
operation = new LockRenewalOperation(A_LOCK_TOKEN, maxDuration, false, renewalOperation, lockedUntil);
Thread.sleep(totalSleepPeriod.toMillis());
logger.info("Finished renewals for first sleep.");
Thread.sleep(2000);
System.out.println("Finished second sleep. Should not have any more renewals.");
assertEquals(LockRenewalStatus.COMPLETE, operation.getStatus());
assertNull(operation.getThrowable());
assertTrue(lockedUntil.isBefore(operation.getLockedUntil()), String.format(
"initial lockedUntil[%s] is not before lockedUntil[%s]", lockedUntil, operation.getLockedUntil()));
verify(renewalOperation, atMost(atMost)).apply(A_LOCK_TOKEN);
}
/**
* Verify that we can cancel the operation.
*/
@Test
void cancellation() throws InterruptedException {
final Duration maxDuration = Duration.ofSeconds(20);
final Duration renewalPeriod = Duration.ofSeconds(3);
final int atMost = 2;
final Instant lockedUntil = Instant.now().plus(renewalPeriod);
final Duration totalSleepPeriod = renewalPeriod.plusMillis(1000);
when(renewalOperation.apply(A_LOCK_TOKEN))
.thenReturn(Mono.fromCallable(() -> Instant.now().plus(renewalPeriod)));
operation = new LockRenewalOperation(A_LOCK_TOKEN, maxDuration, false, renewalOperation, lockedUntil);
Thread.sleep(totalSleepPeriod.toMillis());
logger.info("Finished renewals for first sleep. Cancelling");
operation.close();
Thread.sleep(2000);
System.out.println("Finished second sleep. Should not have any more renewals.");
assertEquals(LockRenewalStatus.CANCELLED, operation.getStatus());
assertNull(operation.getThrowable());
assertTrue(lockedUntil.isBefore(operation.getLockedUntil()), String.format(
"initial lockedUntil[%s] is not before lockedUntil[%s]", lockedUntil, operation.getLockedUntil()));
verify(renewalOperation, atMost(atMost)).apply(A_LOCK_TOKEN);
}
/**
* Verify that when a duration of Duration.ZERO is passed, then we do not renew at all.
*/
@Test
void renewDurationZero() throws InterruptedException {
final Duration maxDuration = Duration.ZERO;
final Duration renewalPeriod = Duration.ofSeconds(3);
final Instant lockedUntil = Instant.now().plus(renewalPeriod);
when(renewalOperation.apply(A_LOCK_TOKEN))
.thenReturn(Mono.fromCallable(() -> Instant.now().plus(renewalPeriod)));
operation = new LockRenewalOperation(A_LOCK_TOKEN, maxDuration, false, renewalOperation, lockedUntil);
Thread.sleep(renewalPeriod.toMillis());
assertEquals(LockRenewalStatus.COMPLETE, operation.getStatus());
assertNull(operation.getThrowable());
assertEquals(lockedUntil, operation.getLockedUntil(), String.format(
"initial lockedUntil[%s] is not equal to lockedUntil[%s]", lockedUntil, operation.getLockedUntil()));
verify(renewalOperation, never()).apply(A_LOCK_TOKEN);
}
/**
* Verifies that if we do not pass in the lockedUntil parameter, it immediately tries to renew the lock.
*/
@Test
void completesRenewFirst() throws InterruptedException {
final Duration maxDuration = Duration.ofSeconds(8);
final Duration renewalPeriod = Duration.ofSeconds(3);
final int atLeast = 4;
final Instant lockedUntil = Instant.now();
final Duration totalSleepPeriod = maxDuration.plusMillis(500);
when(renewalOperation.apply(A_LOCK_TOKEN))
.thenReturn(Mono.fromCallable(() -> Instant.now().plus(renewalPeriod)));
operation = new LockRenewalOperation(A_LOCK_TOKEN, maxDuration, false, renewalOperation);
Thread.sleep(totalSleepPeriod.toMillis());
logger.info("Finished renewals for first sleep.");
Thread.sleep(2000);
logger.info("Finished second sleep. Should not have any more renewals.");
assertEquals(LockRenewalStatus.COMPLETE, operation.getStatus());
assertNull(operation.getThrowable());
assertTrue(lockedUntil.isBefore(operation.getLockedUntil()), String.format(
"initial lockedUntil[%s] is not before lockedUntil[%s]", lockedUntil, operation.getLockedUntil()));
verify(renewalOperation, Mockito.atLeast(atLeast)).apply(A_LOCK_TOKEN);
}
} | |
IsNegative is an invalid operation. I'll throw before it even gets here. | private Disposable getRenewLockOperation(Instant initialLockedUntil, Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration.isZero()) {
status.set(LockRenewalStatus.COMPLETE);
return Disposables.single();
}
final Instant now = Instant.now();
Duration initialInterval = Duration.between(now, initialLockedUntil);
if (initialInterval.isNegative()) {
logger.info("Duration was negative. now[{}] lockedUntil[{}]", now, initialLockedUntil);
initialInterval = Duration.ZERO;
} else {
final Duration adjusted = MessageUtils.adjustServerTimeout(initialInterval);
if (adjusted.isNegative()) {
logger.info("Adjusted duration is negative. Adjusted: {}ms", initialInterval.toMillis());
} else {
initialInterval = adjusted;
}
}
final EmitterProcessor<Duration> emitterProcessor = EmitterProcessor.create();
final FluxSink<Duration> sink = emitterProcessor.sink();
sink.next(initialInterval);
final Flux<Object> cancellationSignals = Flux.first(cancellationProcessor, Mono.delay(maxLockRenewalDuration));
return Flux.switchOnNext(emitterProcessor.map(Flux::interval))
.takeUntilOther(cancellationSignals)
.flatMap(delay -> {
final String id = lockToken;
logger.info("token[{}]. now[{}]. Starting lock renewal.", id, Instant.now());
if (CoreUtils.isNullOrEmpty(id)) {
return Mono.error(new IllegalStateException("Cannot renew session lock without session id."));
}
return renewalOperation.apply(lockToken);
})
.map(instant -> {
final Duration next = Duration.between(Instant.now(), instant);
logger.info("token[{}]. nextExpiration[{}]. next: [{}]. isSession[{}]", lockToken, instant, next,
isSession);
sink.next(MessageUtils.adjustServerTimeout(next));
return instant;
})
.subscribe(until -> lockedUntil.set(until),
error -> {
logger.error("token[{}]. Error occurred while renewing lock token.", error);
status.set(LockRenewalStatus.FAILED);
throwable.set(error);
cancellationProcessor.onComplete();
}, () -> {
if (status.compareAndSet(LockRenewalStatus.RUNNING, LockRenewalStatus.COMPLETE)) {
logger.verbose("token[{}]. Renewing session lock task completed.", lockToken);
}
cancellationProcessor.onComplete();
});
} | if (maxLockRenewalDuration.isZero()) { | private Disposable getRenewLockOperation(Instant initialLockedUntil, Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration.isZero()) {
status.set(LockRenewalStatus.COMPLETE);
return Disposables.single();
}
final Instant now = Instant.now();
Duration initialInterval = Duration.between(now, initialLockedUntil);
if (initialInterval.isNegative()) {
logger.info("Duration was negative. now[{}] lockedUntil[{}]", now, initialLockedUntil);
initialInterval = Duration.ZERO;
} else {
final Duration adjusted = MessageUtils.adjustServerTimeout(initialInterval);
if (adjusted.isNegative()) {
logger.info("Adjusted duration is negative. Adjusted: {}ms", initialInterval.toMillis());
} else {
initialInterval = adjusted;
}
}
final EmitterProcessor<Duration> emitterProcessor = EmitterProcessor.create();
final FluxSink<Duration> sink = emitterProcessor.sink();
sink.next(initialInterval);
final Flux<Object> cancellationSignals = Flux.first(cancellationProcessor, Mono.delay(maxLockRenewalDuration));
return Flux.switchOnNext(emitterProcessor.map(interval -> Mono.delay(interval)
.thenReturn(Flux.create(s -> s.next(interval)))))
.takeUntilOther(cancellationSignals)
.flatMap(delay -> {
logger.info("token[{}]. now[{}]. Starting lock renewal.", lockToken, Instant.now());
return renewalOperation.apply(lockToken);
})
.map(instant -> {
final Duration next = Duration.between(Instant.now(), instant);
logger.info("token[{}]. nextExpiration[{}]. next: [{}]. isSession[{}]", lockToken, instant, next,
isSession);
sink.next(MessageUtils.adjustServerTimeout(next));
return instant;
})
.subscribe(until -> lockedUntil.set(until),
error -> {
logger.error("token[{}]. Error occurred while renewing lock token.", error);
status.set(LockRenewalStatus.FAILED);
throwable.set(error);
cancellationProcessor.onComplete();
}, () -> {
if (status.compareAndSet(LockRenewalStatus.RUNNING, LockRenewalStatus.COMPLETE)) {
logger.verbose("token[{}]. Renewing session lock task completed.", lockToken);
}
cancellationProcessor.onComplete();
});
} | class LockRenewalOperation implements AutoCloseable {
private final ClientLogger logger = new ClientLogger(LockRenewalOperation.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicReference<Instant> lockedUntil = new AtomicReference<>();
private final AtomicReference<Throwable> throwable = new AtomicReference<>();
private final AtomicReference<LockRenewalStatus> status = new AtomicReference<>(LockRenewalStatus.RUNNING);
private final MonoProcessor<Void> cancellationProcessor = MonoProcessor.create();
private final String lockToken;
private final boolean isSession;
private final Function<String, Mono<Instant>> renewalOperation;
private final Disposable subscription;
/**
* Creates a new lock renewal operation. The lock is initially renewed.
*
* @param lockToken Lock or session id to renew.
* @param maxLockRenewalDuration The maximum duration this lock should be renewed.
* @param isSession Whether the lock represents a session lock or message lock.
* @param renewalOperation The renewal operation to call.
*/
LockRenewalOperation(String lockToken, Duration maxLockRenewalDuration, boolean isSession,
Function<String, Mono<Instant>> renewalOperation) {
this(lockToken, maxLockRenewalDuration, isSession, renewalOperation, Instant.now());
}
/**
* Creates a new lock renewal operation.
*
* @param lockToken Lock or session id to renew.
* @param lockedUntil The initial period the message or session is locked until.
* @param maxLockRenewalDuration The maximum duration this lock should be renewed.
* @param isSession Whether the lock represents a session lock or message lock.
* @param renewalOperation The renewal operation to call.
*/
LockRenewalOperation(String lockToken, Duration maxLockRenewalDuration, boolean isSession,
Function<String, Mono<Instant>> renewalOperation, Instant lockedUntil) {
this.lockToken = Objects.requireNonNull(lockToken, "'lockToken' cannot be null.");
this.renewalOperation = Objects.requireNonNull(renewalOperation, "'renewalOperation' cannot be null.");
this.isSession = isSession;
Objects.requireNonNull(lockedUntil, "'lockedUntil cannot be null.'");
Objects.requireNonNull(maxLockRenewalDuration, "'maxLockRenewalDuration' cannot be null.");
if (maxLockRenewalDuration.isNegative()) {
throw logger.logThrowableAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
this.lockedUntil.set(lockedUntil);
this.subscription = getRenewLockOperation(lockedUntil, maxLockRenewalDuration);
}
/**
* Gets the current instant the message or session is locked until.
*
* @return the instant the message or session is locked until.
*/
public Instant getLockedUntil() {
return lockedUntil.get();
}
/**
* Gets the message lock token for the renewal operation.
*
* @return The message lock token or {@code null} if a session is being renewed instead.
*/
public String getLockToken() {
return isSession ? null : lockToken;
}
/**
* Gets the session id for this lock renewal operation.
*
* @return The session id or {@code null} if it is not a session renewal.
*/
public String getSessionId() {
return isSession ? lockToken : null;
}
/**
* Gets the current status of the renewal operation.
*
* @return The current status of the renewal operation.
*/
public LockRenewalStatus getStatus() {
return status.get();
}
/**
* Gets the exception if an error occurred whilst renewing the message or session lock.
*
* @return the exception if an error occurred whilst renewing the message or session lock, otherwise {@code null}.
*/
public Throwable getThrowable() {
return throwable.get();
}
/**
* Cancels the lock renewal operation.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
if (status.compareAndSet(LockRenewalStatus.RUNNING, LockRenewalStatus.CANCELLED)) {
logger.verbose("token[{}] Cancelled operation.", lockToken);
}
cancellationProcessor.onComplete();
subscription.dispose();
}
/**
* Gets the lock renewal operation. if the {@code maxLockRenewalDuration} is {@link Duration
* lock is never renewed.
*
* @param initialLockedUntil When the initial call is locked until.
* @param maxLockRenewalDuration Duration to renew lock for.
* @return The subscription for the operation.
*/
} | class LockRenewalOperation implements AutoCloseable {
private final ClientLogger logger = new ClientLogger(LockRenewalOperation.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicReference<Instant> lockedUntil = new AtomicReference<>();
private final AtomicReference<Throwable> throwable = new AtomicReference<>();
private final AtomicReference<LockRenewalStatus> status = new AtomicReference<>(LockRenewalStatus.RUNNING);
private final MonoProcessor<Void> cancellationProcessor = MonoProcessor.create();
private final String lockToken;
private final boolean isSession;
private final Function<String, Mono<Instant>> renewalOperation;
private final Disposable subscription;
/**
* Creates a new lock renewal operation. The lock is initially renewed.
*
* @param lockToken Message lock or session id to renew.
* @param maxLockRenewalDuration The maximum duration this lock should be renewed.
* @param isSession Whether the lock represents a session lock or message lock.
* @param renewalOperation The renewal operation to call.
*/
LockRenewalOperation(String lockToken, Duration maxLockRenewalDuration, boolean isSession,
Function<String, Mono<Instant>> renewalOperation) {
this(lockToken, maxLockRenewalDuration, isSession, renewalOperation, Instant.now());
}
/**
* Creates a new lock renewal operation.
*
* @param lockToken Lock or session id to renew.
* @param lockedUntil The initial period the message or session is locked until.
* @param maxLockRenewalDuration The maximum duration this lock should be renewed.
* @param isSession Whether the lock represents a session lock or message lock.
* @param renewalOperation The renewal operation to call.
*/
LockRenewalOperation(String lockToken, Duration maxLockRenewalDuration, boolean isSession,
Function<String, Mono<Instant>> renewalOperation, Instant lockedUntil) {
this.lockToken = Objects.requireNonNull(lockToken, "'lockToken' cannot be null.");
this.renewalOperation = Objects.requireNonNull(renewalOperation, "'renewalOperation' cannot be null.");
this.isSession = isSession;
Objects.requireNonNull(lockedUntil, "'lockedUntil cannot be null.'");
Objects.requireNonNull(maxLockRenewalDuration, "'maxLockRenewalDuration' cannot be null.");
if (maxLockRenewalDuration.isNegative()) {
throw logger.logThrowableAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
this.lockedUntil.set(lockedUntil);
this.subscription = getRenewLockOperation(lockedUntil, maxLockRenewalDuration);
}
/**
* Gets the current instant the message or session is locked until.
*
* @return the instant the message or session is locked until.
*/
public Instant getLockedUntil() {
return lockedUntil.get();
}
/**
* Gets the message lock token for the renewal operation.
*
* @return The message lock token or {@code null} if a session is being renewed instead.
*/
public String getLockToken() {
return isSession ? null : lockToken;
}
/**
* Gets the session id for this lock renewal operation.
*
* @return The session id or {@code null} if it is not a session renewal.
*/
public String getSessionId() {
return isSession ? lockToken : null;
}
/**
* Gets the current status of the renewal operation.
*
* @return The current status of the renewal operation.
*/
public LockRenewalStatus getStatus() {
return status.get();
}
/**
* Gets the exception if an error occurred whilst renewing the message or session lock.
*
* @return the exception if an error occurred whilst renewing the message or session lock, otherwise {@code null}.
*/
public Throwable getThrowable() {
return throwable.get();
}
/**
* Cancels the lock renewal operation.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
if (status.compareAndSet(LockRenewalStatus.RUNNING, LockRenewalStatus.CANCELLED)) {
logger.verbose("token[{}] Cancelled operation.", lockToken);
}
cancellationProcessor.onComplete();
subscription.dispose();
}
/**
* Gets the lock renewal operation. if the {@code maxLockRenewalDuration} is {@link Duration
* lock is never renewed.
*
* @param initialLockedUntil When the initial call is locked until.
* @param maxLockRenewalDuration Duration to renew lock for.
* @return The subscription for the operation.
*/
} |
It's checked in the constructor for LockRenewalOperation. | public LockRenewalOperation getAutoRenewSessionLock(String sessionId, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
throw logger.logThrowableAsError(new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
throw logger.logThrowableAsError(new IllegalStateException(
"Cannot renew session lock on a non-session receiver."));
} else if (maxLockRenewalDuration == null) {
throw logger.logThrowableAsError(new NullPointerException("'maxLockRenewalDuration' cannot be null."));
} else if (maxLockRenewalDuration.isNegative()) {
throw logger.logThrowableAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
return new LockRenewalOperation(sessionId, maxLockRenewalDuration, true, this::renewSessionLock);
} | String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock"))); | public LockRenewalOperation getAutoRenewSessionLock(String sessionId, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
throw logger.logExceptionAsError(new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
throw logger.logExceptionAsError(new IllegalStateException(
"Cannot renew session lock on a non-session receiver."));
} else if (maxLockRenewalDuration == null) {
throw logger.logExceptionAsError(new NullPointerException("'maxLockRenewalDuration' cannot be null."));
} else if (maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
} else if (Objects.isNull(sessionId)) {
throw logger.logExceptionAsError(new NullPointerException("'sessionId' cannot be null."));
} else if (sessionId.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'sessionId' cannot be empty."));
}
final LockRenewalOperation operation = new LockRenewalOperation(sessionId, maxLockRenewalDuration, true,
this::renewSessionLock);
renewalContainer.addOrUpdate(sessionId, Instant.now().plus(maxLockRenewalDuration), operation);
return operation;
} | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final MessageLockContainer managementNodeLocks;
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class);
private final String fullyQualifiedNamespace;
private final String entityPath;
private final MessagingEntityType entityType;
private final ReceiverOptions receiverOptions;
private final ServiceBusConnectionProcessor connectionProcessor;
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
private final Runnable onClientClose;
private final UnnamedSessionManager unnamedSessionManager;
private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1);
private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>();
/**
* Creates a receiver that listens to a Service Bus resource.
*
* @param fullyQualifiedNamespace The fully qualified domain name for the Service Bus resource.
* @param entityPath The name of the topic or queue.
* @param entityType The type of the Service Bus resource.
* @param receiverOptions Options when receiving messages.
* @param connectionProcessor The AMQP connection to the Service Bus resource.
* @param tracerProvider Tracer for telemetry.
* @param messageSerializer Serializes and deserializes Service Bus messages.
* @param onClientClose Operation to run when the client completes.
*/
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null.");
this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null.");
this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'");
this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null.");
this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.managementNodeLocks = new MessageLockContainer(cleanupInterval);
this.unnamedSessionManager = null;
}
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose,
UnnamedSessionManager unnamedSessionManager) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null.");
this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null.");
this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'");
this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null.");
this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.unnamedSessionManager = Objects.requireNonNull(unnamedSessionManager, "'sessionManager' cannot be null.");
this.managementNodeLocks = new MessageLockContainer(cleanupInterval);
}
/**
* Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to
* {@code {yournamespace}.servicebus.windows.net}.
*
* @return The fully qualified Service Bus namespace that the connection is associated with.
*/
public String getFullyQualifiedNamespace() {
return fullyQualifiedNamespace;
}
/**
* Gets the Service Bus resource this client interacts with.
*
* @return The Service Bus resource this client interacts with.
*/
public String getEntityPath() {
return entityPath;
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available
* again for processing. Abandoning a message will increase the delivery count on the message.
*
* @param lockToken Lock token of the message.
*
* @return A {@link Mono} that completes when the Service Bus abandon operation completes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken) {
return abandon(lockToken, receiverOptions.getSessionId());
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available
* again for processing. Abandoning a message will increase the delivery count on the message.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to abandon. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the Service Bus abandon operation completes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken, String sessionId) {
return abandon(lockToken, null, sessionId);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties.
* This will make the message available again for processing. Abandoning a message will increase the delivery count
* on the message.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Properties to modify on the message.
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken, Map<String, Object> propertiesToModify) {
return abandon(lockToken, propertiesToModify, receiverOptions.getSessionId());
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties.
* This will make the message available again for processing. Abandoning a message will increase the delivery count
* on the message.
* <p><strong>Complete a message with a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.abandonMessageWithTransaction}
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Properties to modify on the message.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
return abandon(lockToken, propertiesToModify, receiverOptions.getSessionId(), transactionContext);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties.
* This will make the message available again for processing. Abandoning a message will increase the delivery count
* on the message.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Properties to modify on the message.
* @param sessionId Session id of the message to abandon. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the Service Bus abandon operation completes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken, Map<String, Object> propertiesToModify, String sessionId) {
return updateDisposition(lockToken, DispositionStatus.ABANDONED, null, null,
propertiesToModify, sessionId, null);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties.
* This will make the message available again for processing. Abandoning a message will increase the delivery count
* on the message.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Properties to modify on the message.
* @param sessionId Session id of the message to abandon. {@code null} if there is no session.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus abandon operation completes.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken, Map<String, Object> propertiesToModify, String sessionId,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return updateDisposition(lockToken, DispositionStatus.ABANDONED, null, null,
propertiesToModify, sessionId, transactionContext);
}
/**
* Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the
* service.
*
* @param lockToken Lock token of the message.
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> complete(String lockToken) {
return updateDisposition(lockToken, DispositionStatus.COMPLETED, null, null,
null, receiverOptions.getSessionId(), null);
}
/**
* Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the
* service.
* <p><strong>Complete a message with a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.completeMessageWithTransaction}
*
* @param lockToken Lock token of the message.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> complete(String lockToken, ServiceBusTransactionContext transactionContext) {
return complete(lockToken, receiverOptions.getSessionId(), transactionContext);
}
/**
* Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the
* service.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to complete. {@code null} if there is no session.
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> complete(String lockToken, String sessionId) {
return updateDisposition(lockToken, DispositionStatus.COMPLETED, null, null,
null, sessionId, null);
}
/**
* Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the
* service.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to complete. {@code null} if there is no session.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> complete(String lockToken, String sessionId,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return updateDisposition(lockToken, DispositionStatus.COMPLETED, null, null,
null, sessionId, transactionContext);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred
* subqueue.
*
* @param lockToken Lock token of the message.
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken) {
return defer(lockToken, receiverOptions.getSessionId());
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred
* subqueue.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to defer. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken, String sessionId) {
return defer(lockToken, null, sessionId);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will
* move message into the deferred subqueue.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Message properties to modify.
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken, Map<String, Object> propertiesToModify) {
return defer(lockToken, propertiesToModify, receiverOptions.getSessionId());
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will
* move message into the deferred subqueue.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Message properties to modify.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
return defer(lockToken, propertiesToModify, receiverOptions.getSessionId(), transactionContext);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will
* move message into the deferred subqueue.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Message properties to modify.
* @param sessionId Session id of the message to defer. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken, Map<String, Object> propertiesToModify, String sessionId) {
return updateDisposition(lockToken, DispositionStatus.DEFERRED, null, null,
propertiesToModify, sessionId, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will
* move message into the deferred subqueue.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Message properties to modify.
* @param sessionId Session id of the message to defer. {@code null} if there is no session.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken, Map<String, Object> propertiesToModify, String sessionId,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return updateDisposition(lockToken, DispositionStatus.DEFERRED, null, null,
propertiesToModify, sessionId, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue.
*
* @param lockToken Lock token of the message.
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(String lockToken) {
return deadLetter(lockToken, receiverOptions.getSessionId());
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to deadletter. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(String lockToken, String sessionId) {
return deadLetter(lockToken, DEFAULT_DEAD_LETTER_OPTIONS, sessionId);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to deadletter. {@code null} if there is no session.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(String lockToken, String sessionId,
ServiceBusTransactionContext transactionContext) {
return deadLetter(lockToken, DEFAULT_DEAD_LETTER_OPTIONS, sessionId, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param lockToken Lock token of the message.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken} or {@code deadLetterOptions} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> deadLetter(String lockToken, DeadLetterOptions deadLetterOptions) {
return deadLetter(lockToken, deadLetterOptions, receiverOptions.getSessionId());
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param lockToken Lock token of the message.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken}, {@code deadLetterOptions}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> deadLetter(String lockToken, DeadLetterOptions deadLetterOptions,
ServiceBusTransactionContext transactionContext) {
return deadLetter(lockToken, deadLetterOptions, receiverOptions.getSessionId(), transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param lockToken Lock token of the message.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param sessionId Session id of the message to deadletter. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> deadLetter(String lockToken, DeadLetterOptions deadLetterOptions, String sessionId) {
if (Objects.isNull(deadLetterOptions)) {
return monoError(logger, new NullPointerException("'deadLetterOptions' cannot be null."));
}
return updateDisposition(lockToken, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(), sessionId,
null);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param lockToken Lock token of the message.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param sessionId Session id of the message to deadletter. {@code null} if there is no session.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> deadLetter(String lockToken, DeadLetterOptions deadLetterOptions, String sessionId,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return updateDisposition(lockToken, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(), sessionId,
transactionContext);
}
/**
* Gets and starts the auto lock renewal for a message with the given lock.
*
* @param lockToken Lock token of the message.
* @param maxLockRenewalDuration Maximum duration to keep renewing the lock token.
* @return A lock renewal operation for the message.
*/
public LockRenewalOperation getAutoRenewMessageLock(String lockToken, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
throw logger.logThrowableAsError(new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewMessageLock")));
} else if (Objects.isNull(lockToken)) {
throw logger.logThrowableAsError(new NullPointerException("'lockToken' cannot be null."));
} else if (lockToken.isEmpty()) {
throw logger.logThrowableAsError(new IllegalArgumentException("'lockToken' cannot be empty."));
} else if (receiverOptions.isSessionReceiver()) {
throw logger.logThrowableAsError(new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", lockToken)));
} else if (maxLockRenewalDuration == null) {
throw logger.logThrowableAsError(new NullPointerException("'maxLockRenewalDuration' cannot be null."));
} else if (maxLockRenewalDuration.isNegative()) {
throw logger.logThrowableAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
return new LockRenewalOperation(lockToken, maxLockRenewalDuration, false, this::renewMessageLock);
}
/**
* Gets and starts the auto lock renewal for a session with the given lock.
*
* @param sessionId Id for the session to renew.
* @param maxLockRenewalDuration Maximum duration to keep renewing the lock token.
* @return A lock renewal operation for the message.
* @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed.
*/
/**
* Gets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @return The session state or an empty Mono if there is no state set for the session.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<byte[]> getSessionState(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot get session state on a non-session receiver."));
}
if (unnamedSessionManager != null) {
return unnamedSessionManager.getSessionState(sessionId);
} else {
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId)));
}
}
/**
* Reads the next active message without changing the state of the receiver or the message source. The first call to
* {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent
* message in the entity.
*
* @return A peeked {@link ServiceBusReceivedMessage}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessage() {
return peekMessage(receiverOptions.getSessionId());
}
/**
* Reads the next active message without changing the state of the receiver or the message source. The first call to
* {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent
* message in the entity.
*
* @param sessionId Session id of the message to peek from. {@code null} if there is no session.
*
* @return A peeked {@link ServiceBusReceivedMessage}.
* @see <a href="https:
*
* @throws IllegalStateException if the receiver is disposed.
*/
public Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> {
final long sequence = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek message from sequence number: {}", sequence);
return channel.peek(sequence, sessionId, getLinkName(sessionId));
})
.handle((message, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, message.getSequenceNumber()));
logger.verbose("Updating last peeked sequence number: {}", current);
sink.next(message);
});
}
/**
* Starting from the given sequence number, reads next the active message without changing the state of the receiver
* or the message source.
*
* @param sequenceNumber The sequence number from where to read the message.
*
* @return A peeked {@link ServiceBusReceivedMessage}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber) {
return peekMessageAt(sequenceNumber, receiverOptions.getSessionId());
}
/**
* Starting from the given sequence number, reads next the active message without changing the state of the receiver
* or the message source.
*
* @param sequenceNumber The sequence number from where to read the message.
* @param sessionId Session id of the message to peek from. {@code null} if there is no session.
*
* @return A peeked {@link ServiceBusReceivedMessage}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId)));
}
/**
* Reads the next batch of active messages without changing the state of the receiver or the message source.
*
* @param maxMessages The number of messages.
*
* @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} that are peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) {
return peekMessages(maxMessages, receiverOptions.getSessionId());
}
/**
* Reads the next batch of active messages without changing the state of the receiver or the message source.
*
* @param maxMessages The number of messages.
* @param sessionId Session id of the messages to peek from. {@code null} if there is no session.
*
* @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> {
final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek batch from sequence number: {}", nextSequenceNumber);
final Flux<ServiceBusReceivedMessage> messages =
node.peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages);
final Mono<ServiceBusReceivedMessage> handle = messages
.switchIfEmpty(Mono.fromCallable(() -> {
ServiceBusReceivedMessage emptyMessage = new ServiceBusReceivedMessage(new byte[0]);
emptyMessage.setSequenceNumber(lastPeekedSequenceNumber.get());
return emptyMessage;
}))
.last()
.handle((last, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, last.getSequenceNumber()));
logger.verbose("Last peeked sequence number in batch: {}", current);
sink.complete();
});
return Flux.merge(messages, handle);
});
}
/**
* Starting from the given sequence number, reads the next batch of active messages without changing the state of
* the receiver or the message source.
*
* @param maxMessages The number of messages.
* @param sequenceNumber The sequence number from where to start reading messages.
*
* @return A {@link Flux} of {@link ServiceBusReceivedMessage} peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber) {
return peekMessagesAt(maxMessages, sequenceNumber, receiverOptions.getSessionId());
}
/**
* Starting from the given sequence number, reads the next batch of active messages without changing the state of
* the receiver or the message source.
*
* @param maxMessages The number of messages.
* @param sequenceNumber The sequence number from where to start reading messages.
* @param sessionId Session id of the messages to peek from. {@code null} if there is no session.
*
* @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages));
}
/**
* Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus
* entity. This Flux continuously receives messages from a Service Bus entity until either:
*
* <ul>
* <li>The receiver is closed.</li>
* <li>The subscription to the Flux is disposed.</li>
* <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux
* {@link Flux
* <li>An {@link AmqpException} occurs that causes the receive link to stop.</li>
* </ul>
*
* @return An <b>infinite</b> stream of messages from the Service Bus entity.
*/
public Flux<ServiceBusReceivedMessageContext> receiveMessages() {
if (unnamedSessionManager != null) {
return unnamedSessionManager.receive();
} else {
return getOrCreateConsumer().receive().map(ServiceBusReceivedMessageContext::new);
}
}
/**
* Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using
* sequence number.
*
* @param sequenceNumber The {@link ServiceBusReceivedMessage
* message.
*
* @return A deferred message with the matching {@code sequenceNumber}.
*/
public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) {
return receiveDeferredMessage(sequenceNumber, receiverOptions.getSessionId());
}
/**
* Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using
* sequence number.
*
* @param sequenceNumber The {@link ServiceBusReceivedMessage
* message.
* @param sessionId Session id of the deferred message. {@code null} if there is no session.
*
* @return A deferred message with the matching {@code sequenceNumber}.
*/
public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) {
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(),
sessionId, getLinkName(sessionId), Collections.singleton(sequenceNumber)).last())
.map(receivedMessage -> {
if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) {
return receivedMessage;
}
if (receiverOptions.getReceiveMode() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil()));
}
return receivedMessage;
});
}
/**
* Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received
* by using sequence number.
*
* @param sequenceNumbers The sequence numbers of the deferred messages.
*
* @return A {@link Flux} of deferred {@link ServiceBusReceivedMessage messages}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) {
return receiveDeferredMessages(sequenceNumbers, receiverOptions.getSessionId());
}
/**
* Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received
* by using sequence number.
*
* @param sequenceNumbers The sequence numbers of the deferred messages.
* @param sessionId Session id of the deferred messages. {@code null} if there is no session.
*
* @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers,
String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(),
sessionId, getLinkName(sessionId), sequenceNumbers))
.map(receivedMessage -> {
if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) {
return receivedMessage;
}
if (receiverOptions.getReceiveMode() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil()));
}
return receivedMessage;
});
}
/**
* Asynchronously renews the lock on the specified message. The lock will be renewed based on the setting specified
* on the entity. When a message is received in {@link ReceiveMode
* server for this receiver instance for a duration as specified during the Queue creation (LockDuration). If
* processing of the message requires longer than this duration, the lock needs to be renewed. For each renewal, the
* lock is reset to the entity's LockDuration value.
*
* @param lockToken Lock token of the message to renew.
*
* @return The new expiration time for the message.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalStateException if the receiver is a session receiver.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Instant> renewMessageLock(String lockToken) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock")));
} else if (Objects.isNull(lockToken)) {
return monoError(logger, new NullPointerException("'lockToken' cannot be null."));
} else if (lockToken.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'lockToken' cannot be empty."));
} else if (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", lockToken)));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(serviceBusManagementNode ->
serviceBusManagementNode.renewMessageLock(lockToken, getLinkName(null)))
.map(instant -> managementNodeLocks.addOrUpdate(lockToken, instant));
}
/**
* Sets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @return The next expiration time for the session lock.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<Instant> renewSessionLock(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot renew session lock on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.renewSessionLock(sessionId, linkName));
}
/**
* Sets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
* @param sessionState State to set on the session.
*
* @return A Mono that completes when the session is set
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<Void> setSessionState(String sessionId, byte[] sessionState) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot set session state on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName));
}
/**
* Starts a new service side transaction. The {@link ServiceBusTransactionContext} should be passed to all
* operations that needs to be in this transaction.
*
* <p><strong>Create a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.createTransaction}
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<ServiceBusTransactionContext> createTransaction() {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.createTransaction())
.map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()));
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Commit a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.commitTransaction}
*
* @param transactionContext to be committed.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<Void> commitTransaction(ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "commitTransaction")));
}
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Rollbacks the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Rollback a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.rollbackTransaction}
*
* @param transactionContext to be rollbacked.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<Void> rollbackTransaction(ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "rollbackTransaction")));
}
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Disposes of the consumer by closing the underlying connection to the service.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
logger.info("Removing receiver links.");
final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null);
if (disposed != null) {
disposed.close();
}
if (unnamedSessionManager != null) {
unnamedSessionManager.close();
}
onClientClose.run();
}
/**
* @return receiver options set by user;
*/
ReceiverOptions getReceiverOptions() {
return receiverOptions;
}
/**
* Gets whether or not the management node contains the message lock token and it has not expired. Lock tokens are
* held by the management node when they are received from the management node or management operations are
* performed using that {@code lockToken}.
*
* @param lockToken Lock token to check for.
*
* @return {@code true} if the management node contains the lock token and false otherwise.
*/
private boolean isManagementToken(String lockToken) {
return managementNodeLocks.contains(lockToken);
}
private Mono<Void> updateDisposition(String lockToken, DispositionStatus dispositionStatus,
String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify,
String sessionId, ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, dispositionStatus.getValue())));
} else if (Objects.isNull(lockToken)) {
return monoError(logger, new NullPointerException("'lockToken' cannot be null."));
} else if (lockToken.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'lockToken' cannot be empty."));
}
if (receiverOptions.getReceiveMode() != ReceiveMode.PEEK_LOCK) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format(
"'%s' is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE.", dispositionStatus))));
}
final String sessionIdToUse;
if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) {
sessionIdToUse = receiverOptions.getSessionId();
} else {
sessionIdToUse = sessionId;
}
logger.info("{}: Update started. Disposition: {}. Lock: {}. SessionId {}.", entityPath, dispositionStatus,
lockToken, sessionIdToUse);
final Mono<Void> performOnManagement = connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.updateDisposition(lockToken, dispositionStatus, deadLetterReason,
deadLetterErrorDescription, propertiesToModify, sessionId, getLinkName(sessionId), transactionContext))
.then(Mono.fromRunnable(() -> {
logger.info("{}: Management node Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
managementNodeLocks.remove(lockToken);
}));
if (unnamedSessionManager != null) {
return unnamedSessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify,
deadLetterReason, deadLetterErrorDescription, transactionContext)
.flatMap(isSuccess -> {
if (isSuccess) {
return Mono.empty();
}
logger.info("Could not perform on session manger. Performing on management node.");
return performOnManagement;
});
}
final ServiceBusAsyncConsumer existingConsumer = consumer.get();
if (isManagementToken(lockToken) || existingConsumer == null) {
return performOnManagement;
} else {
return existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason,
deadLetterErrorDescription, propertiesToModify, transactionContext)
.then(Mono.fromRunnable(() -> logger.info("{}: Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken)));
}
}
private ServiceBusAsyncConsumer getOrCreateConsumer() {
final ServiceBusAsyncConsumer existing = consumer.get();
if (existing != null) {
return existing;
}
final String linkName = StringUtil.getRandomString(entityPath);
logger.info("{}: Creating consumer for link '{}'", entityPath, linkName);
final Flux<ServiceBusReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> {
if (receiverOptions.isSessionReceiver()) {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType, receiverOptions.getSessionId());
} else {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType);
}
})
.doOnNext(next -> {
final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]"
+ " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]";
logger.verbose(format, next.getEntityPath(), receiverOptions.getReceiveMode(),
CoreUtils.isNullOrEmpty(receiverOptions.getSessionId()), "N/A", entityType);
})
.repeat();
final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions());
final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith(
new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy,
receiverOptions.getReceiveMode()));
final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor,
messageSerializer, receiverOptions.getPrefetchCount());
if (consumer.compareAndSet(null, newConsumer)) {
return newConsumer;
} else {
newConsumer.close();
return consumer.get();
}
}
/**
* If the receiver has not connected via {@link
* through the management node.
*
* @return The name of the receive link, or null of it has not connected via a receive link.
*/
private String getLinkName(String sessionId) {
if (unnamedSessionManager != null && !CoreUtils.isNullOrEmpty(sessionId)) {
return unnamedSessionManager.getLinkName(sessionId);
} else if (!CoreUtils.isNullOrEmpty(sessionId) && !receiverOptions.isSessionReceiver()) {
return null;
} else {
final ServiceBusAsyncConsumer existing = consumer.get();
return existing != null ? existing.getLinkName() : null;
}
}
} | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final LockContainer<LockRenewalOperation> renewalContainer;
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final LockContainer<Instant> managementNodeLocks;
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class);
private final String fullyQualifiedNamespace;
private final String entityPath;
private final MessagingEntityType entityType;
private final ReceiverOptions receiverOptions;
private final ServiceBusConnectionProcessor connectionProcessor;
private final TracerProvider tracerProvider;
private final MessageSerializer messageSerializer;
private final Runnable onClientClose;
private final UnnamedSessionManager unnamedSessionManager;
private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1);
private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>();
/**
* Creates a receiver that listens to a Service Bus resource.
*
* @param fullyQualifiedNamespace The fully qualified domain name for the Service Bus resource.
* @param entityPath The name of the topic or queue.
* @param entityType The type of the Service Bus resource.
* @param receiverOptions Options when receiving messages.
* @param connectionProcessor The AMQP connection to the Service Bus resource.
* @param tracerProvider Tracer for telemetry.
* @param messageSerializer Serializes and deserializes Service Bus messages.
* @param onClientClose Operation to run when the client completes.
*/
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null.");
this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null.");
this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'");
this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null.");
this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. lockToken[{}]. status[{}]. throwable[{}].",
renewal.getLockToken(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
this.unnamedSessionManager = null;
}
ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType,
ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval,
TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose,
UnnamedSessionManager unnamedSessionManager) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null.");
this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null.");
this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'");
this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null.");
this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null.");
this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null.");
this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null.");
this.unnamedSessionManager = Objects.requireNonNull(unnamedSessionManager, "'sessionManager' cannot be null.");
this.managementNodeLocks = new LockContainer<>(cleanupInterval);
this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> {
logger.info("Closing expired renewal operation. sessionId[{}]. status[{}]. throwable[{}]",
renewal.getSessionId(), renewal.getStatus(), renewal.getThrowable());
renewal.close();
});
}
/**
* Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to
* {@code {yournamespace}.servicebus.windows.net}.
*
* @return The fully qualified Service Bus namespace that the connection is associated with.
*/
public String getFullyQualifiedNamespace() {
return fullyQualifiedNamespace;
}
/**
* Gets the Service Bus resource this client interacts with.
*
* @return The Service Bus resource this client interacts with.
*/
public String getEntityPath() {
return entityPath;
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available
* again for processing. Abandoning a message will increase the delivery count on the message.
*
* @param lockToken Lock token of the message.
*
* @return A {@link Mono} that completes when the Service Bus abandon operation completes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken) {
return abandon(lockToken, receiverOptions.getSessionId());
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token. This will make the message available
* again for processing. Abandoning a message will increase the delivery count on the message.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to abandon. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the Service Bus abandon operation completes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken, String sessionId) {
return abandon(lockToken, null, sessionId);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties.
* This will make the message available again for processing. Abandoning a message will increase the delivery count
* on the message.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Properties to modify on the message.
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken, Map<String, Object> propertiesToModify) {
return abandon(lockToken, propertiesToModify, receiverOptions.getSessionId());
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties.
* This will make the message available again for processing. Abandoning a message will increase the delivery count
* on the message.
* <p><strong>Complete a message with a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.abandonMessageWithTransaction}
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Properties to modify on the message.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus operation finishes.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
return abandon(lockToken, propertiesToModify, receiverOptions.getSessionId(), transactionContext);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties.
* This will make the message available again for processing. Abandoning a message will increase the delivery count
* on the message.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Properties to modify on the message.
* @param sessionId Session id of the message to abandon. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the Service Bus abandon operation completes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken, Map<String, Object> propertiesToModify, String sessionId) {
return updateDisposition(lockToken, DispositionStatus.ABANDONED, null, null,
propertiesToModify, sessionId, null);
}
/**
* Abandon a {@link ServiceBusReceivedMessage message} with its lock token and updates the message's properties.
* This will make the message available again for processing. Abandoning a message will increase the delivery count
* on the message.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Properties to modify on the message.
* @param sessionId Session id of the message to abandon. {@code null} if there is no session.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus abandon operation completes.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> abandon(String lockToken, Map<String, Object> propertiesToModify, String sessionId,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return updateDisposition(lockToken, DispositionStatus.ABANDONED, null, null,
propertiesToModify, sessionId, transactionContext);
}
/**
* Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the
* service.
*
* @param lockToken Lock token of the message.
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> complete(String lockToken) {
return updateDisposition(lockToken, DispositionStatus.COMPLETED, null, null,
null, receiverOptions.getSessionId(), null);
}
/**
* Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the
* service.
* <p><strong>Complete a message with a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.completeMessageWithTransaction}
*
* @param lockToken Lock token of the message.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> complete(String lockToken, ServiceBusTransactionContext transactionContext) {
return complete(lockToken, receiverOptions.getSessionId(), transactionContext);
}
/**
* Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the
* service.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to complete. {@code null} if there is no session.
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> complete(String lockToken, String sessionId) {
return updateDisposition(lockToken, DispositionStatus.COMPLETED, null, null,
null, sessionId, null);
}
/**
* Completes a {@link ServiceBusReceivedMessage message} using its lock token. This will delete the message from the
* service.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to complete. {@code null} if there is no session.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that finishes when the message is completed on Service Bus.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> complete(String lockToken, String sessionId,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return updateDisposition(lockToken, DispositionStatus.COMPLETED, null, null,
null, sessionId, transactionContext);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred
* subqueue.
*
* @param lockToken Lock token of the message.
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken) {
return defer(lockToken, receiverOptions.getSessionId());
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token. This will move message into the deferred
* subqueue.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to defer. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken, String sessionId) {
return defer(lockToken, null, sessionId);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will
* move message into the deferred subqueue.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Message properties to modify.
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken, Map<String, Object> propertiesToModify) {
return defer(lockToken, propertiesToModify, receiverOptions.getSessionId());
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will
* move message into the deferred subqueue.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Message properties to modify.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the defer operation finishes.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken, Map<String, Object> propertiesToModify,
ServiceBusTransactionContext transactionContext) {
return defer(lockToken, propertiesToModify, receiverOptions.getSessionId(), transactionContext);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will
* move message into the deferred subqueue.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Message properties to modify.
* @param sessionId Session id of the message to defer. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken, Map<String, Object> propertiesToModify, String sessionId) {
return updateDisposition(lockToken, DispositionStatus.DEFERRED, null, null,
propertiesToModify, sessionId, null);
}
/**
* Defers a {@link ServiceBusReceivedMessage message} using its lock token with modified message property. This will
* move message into the deferred subqueue.
*
* @param lockToken Lock token of the message.
* @param propertiesToModify Message properties to modify.
* @param sessionId Session id of the message to defer. {@code null} if there is no session.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the Service Bus defer operation finishes.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
*/
public Mono<Void> defer(String lockToken, Map<String, Object> propertiesToModify, String sessionId,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return updateDisposition(lockToken, DispositionStatus.DEFERRED, null, null,
propertiesToModify, sessionId, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue.
*
* @param lockToken Lock token of the message.
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(String lockToken) {
return deadLetter(lockToken, receiverOptions.getSessionId());
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to deadletter. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(String lockToken, String sessionId) {
return deadLetter(lockToken, DEFAULT_DEAD_LETTER_OPTIONS, sessionId);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter sub-queue.
*
* @param lockToken Lock token of the message.
* @param sessionId Session id of the message to deadletter. {@code null} if there is no session.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
* @see <a href="https:
* queues</a>
*/
public Mono<Void> deadLetter(String lockToken, String sessionId,
ServiceBusTransactionContext transactionContext) {
return deadLetter(lockToken, DEFAULT_DEAD_LETTER_OPTIONS, sessionId, transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param lockToken Lock token of the message.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken} or {@code deadLetterOptions} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> deadLetter(String lockToken, DeadLetterOptions deadLetterOptions) {
return deadLetter(lockToken, deadLetterOptions, receiverOptions.getSessionId());
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param lockToken Lock token of the message.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken}, {@code deadLetterOptions}, {@code transactionContext} or
* {@code transactionContext.transactionId} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> deadLetter(String lockToken, DeadLetterOptions deadLetterOptions,
ServiceBusTransactionContext transactionContext) {
return deadLetter(lockToken, deadLetterOptions, receiverOptions.getSessionId(), transactionContext);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param lockToken Lock token of the message.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param sessionId Session id of the message to deadletter. {@code null} if there is no session.
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> deadLetter(String lockToken, DeadLetterOptions deadLetterOptions, String sessionId) {
if (Objects.isNull(deadLetterOptions)) {
return monoError(logger, new NullPointerException("'deadLetterOptions' cannot be null."));
}
return updateDisposition(lockToken, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(), sessionId,
null);
}
/**
* Moves a {@link ServiceBusReceivedMessage message} to the deadletter subqueue with deadletter reason, error
* description, and/or modified properties.
*
* @param lockToken Lock token of the message.
* @param deadLetterOptions The options to specify when moving message to the deadletter sub-queue.
* @param sessionId Session id of the message to deadletter. {@code null} if there is no session.
* @param transactionContext in which this operation is taking part in. The transaction should be created first by
* {@link ServiceBusReceiverAsyncClient
* {@link ServiceBusSenderAsyncClient
*
* @return A {@link Mono} that completes when the dead letter operation finishes.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Void> deadLetter(String lockToken, DeadLetterOptions deadLetterOptions, String sessionId,
ServiceBusTransactionContext transactionContext) {
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return updateDisposition(lockToken, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getPropertiesToModify(), sessionId,
transactionContext);
}
/**
* Gets and starts the auto lock renewal for a message with the given lock.
*
* @param lockToken Lock token of the message.
* @param maxLockRenewalDuration Maximum duration to keep renewing the lock token.
*
* @return A lock renewal operation for the message.
* @throws NullPointerException if {@code lockToken} or {@code maxLockRenewalDuration} is null.
* @throws IllegalArgumentException if {@code lockToken} is an empty string.
* @throws IllegalStateException if the receiver is a session receiver or the receiver is disposed.
*/
public LockRenewalOperation getAutoRenewMessageLock(String lockToken, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
throw logger.logExceptionAsError(new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewMessageLock")));
} else if (Objects.isNull(lockToken)) {
throw logger.logExceptionAsError(new NullPointerException("'lockToken' cannot be null."));
} else if (lockToken.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'lockToken' cannot be empty."));
} else if (receiverOptions.isSessionReceiver()) {
throw logger.logExceptionAsError(new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", lockToken)));
} else if (maxLockRenewalDuration == null) {
throw logger.logExceptionAsError(new NullPointerException("'maxLockRenewalDuration' cannot be null."));
} else if (maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
final LockRenewalOperation operation = new LockRenewalOperation(lockToken, maxLockRenewalDuration, false,
this::renewMessageLock);
renewalContainer.addOrUpdate(lockToken, Instant.now().plus(maxLockRenewalDuration), operation);
return operation;
}
/**
* Gets and starts the auto lock renewal for a session with the given lock.
*
* @param sessionId Id for the session to renew.
* @param maxLockRenewalDuration Maximum duration to keep renewing the lock token.
*
* @return A lock renewal operation for the message.
* @throws NullPointerException if {@code sessionId} or {@code maxLockRenewalDuration} is null.
* @throws IllegalArgumentException if {@code lockToken} is an empty string.
* @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed.
*/
/**
* Gets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @return The session state or an empty Mono if there is no state set for the session.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<byte[]> getSessionState(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot get session state on a non-session receiver."));
}
if (unnamedSessionManager != null) {
return unnamedSessionManager.getSessionState(sessionId);
} else {
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId)));
}
}
/**
* Reads the next active message without changing the state of the receiver or the message source. The first call to
* {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent
* message in the entity.
*
* @return A peeked {@link ServiceBusReceivedMessage}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessage() {
return peekMessage(receiverOptions.getSessionId());
}
/**
* Reads the next active message without changing the state of the receiver or the message source. The first call to
* {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent
* message in the entity.
*
* @param sessionId Session id of the message to peek from. {@code null} if there is no session.
*
* @return A peeked {@link ServiceBusReceivedMessage}.
* @throws IllegalStateException if the receiver is disposed.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> {
final long sequence = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek message from sequence number: {}", sequence);
return channel.peek(sequence, sessionId, getLinkName(sessionId));
})
.handle((message, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, message.getSequenceNumber()));
logger.verbose("Updating last peeked sequence number: {}", current);
sink.next(message);
});
}
/**
* Starting from the given sequence number, reads next the active message without changing the state of the receiver
* or the message source.
*
* @param sequenceNumber The sequence number from where to read the message.
*
* @return A peeked {@link ServiceBusReceivedMessage}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber) {
return peekMessageAt(sequenceNumber, receiverOptions.getSessionId());
}
/**
* Starting from the given sequence number, reads next the active message without changing the state of the receiver
* or the message source.
*
* @param sequenceNumber The sequence number from where to read the message.
* @param sessionId Session id of the message to peek from. {@code null} if there is no session.
*
* @return A peeked {@link ServiceBusReceivedMessage}.
* @see <a href="https:
*/
public Mono<ServiceBusReceivedMessage> peekMessageAt(long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId)));
}
/**
* Reads the next batch of active messages without changing the state of the receiver or the message source.
*
* @param maxMessages The number of messages.
*
* @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} that are peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) {
return peekMessages(maxMessages, receiverOptions.getSessionId());
}
/**
* Reads the next batch of active messages without changing the state of the receiver or the message source.
*
* @param maxMessages The number of messages.
* @param sessionId Session id of the messages to peek from. {@code null} if there is no session.
*
* @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> {
final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1;
logger.verbose("Peek batch from sequence number: {}", nextSequenceNumber);
final Flux<ServiceBusReceivedMessage> messages =
node.peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages);
final Mono<ServiceBusReceivedMessage> handle = messages
.switchIfEmpty(Mono.fromCallable(() -> {
ServiceBusReceivedMessage emptyMessage = new ServiceBusReceivedMessage(new byte[0]);
emptyMessage.setSequenceNumber(lastPeekedSequenceNumber.get());
return emptyMessage;
}))
.last()
.handle((last, sink) -> {
final long current = lastPeekedSequenceNumber
.updateAndGet(value -> Math.max(value, last.getSequenceNumber()));
logger.verbose("Last peeked sequence number in batch: {}", current);
sink.complete();
});
return Flux.merge(messages, handle);
});
}
/**
* Starting from the given sequence number, reads the next batch of active messages without changing the state of
* the receiver or the message source.
*
* @param maxMessages The number of messages.
* @param sequenceNumber The sequence number from where to start reading messages.
*
* @return A {@link Flux} of {@link ServiceBusReceivedMessage} peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber) {
return peekMessagesAt(maxMessages, sequenceNumber, receiverOptions.getSessionId());
}
/**
* Starting from the given sequence number, reads the next batch of active messages without changing the state of
* the receiver or the message source.
*
* @param maxMessages The number of messages.
* @param sequenceNumber The sequence number from where to start reading messages.
* @param sessionId Session id of the messages to peek from. {@code null} if there is no session.
*
* @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked.
* @throws IllegalArgumentException if {@code maxMessages} is not a positive integer.
* @see <a href="https:
*/
public Flux<ServiceBusReceivedMessage> peekMessagesAt(int maxMessages, long sequenceNumber, String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages));
}
/**
* Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity.
* This Flux continuously receives messages from a Service Bus entity until either:
*
* <ul>
* <li>The receiver is closed.</li>
* <li>The subscription to the Flux is disposed.</li>
* <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux
* {@link Flux
* <li>An {@link AmqpException} occurs that causes the receive link to stop.</li>
* </ul>
*
* @return An <b>infinite</b> stream of messages from the Service Bus entity.
*/
public Flux<ServiceBusReceivedMessageContext> receiveMessages() {
if (unnamedSessionManager != null) {
return unnamedSessionManager.receive();
} else {
return getOrCreateConsumer().receive().map(ServiceBusReceivedMessageContext::new);
}
}
/**
* Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using
* sequence number.
*
* @param sequenceNumber The {@link ServiceBusReceivedMessage
* message.
*
* @return A deferred message with the matching {@code sequenceNumber}.
*/
public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) {
return receiveDeferredMessage(sequenceNumber, receiverOptions.getSessionId());
}
/**
* Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using
* sequence number.
*
* @param sequenceNumber The {@link ServiceBusReceivedMessage
* message.
* @param sessionId Session id of the deferred message. {@code null} if there is no session.
*
* @return A deferred message with the matching {@code sequenceNumber}.
*/
public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) {
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(),
sessionId, getLinkName(sessionId), Collections.singleton(sequenceNumber)).last())
.map(receivedMessage -> {
if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) {
return receivedMessage;
}
if (receiverOptions.getReceiveMode() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil(), receivedMessage.getLockedUntil()));
}
return receivedMessage;
});
}
/**
* Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received
* by using sequence number.
*
* @param sequenceNumbers The sequence numbers of the deferred messages.
*
* @return A {@link Flux} of deferred {@link ServiceBusReceivedMessage messages}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) {
return receiveDeferredMessages(sequenceNumbers, receiverOptions.getSessionId());
}
/**
* Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received
* by using sequence number.
*
* @param sequenceNumbers The sequence numbers of the deferred messages.
* @param sessionId Session id of the deferred messages. {@code null} if there is no session.
*
* @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}.
*/
public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers,
String sessionId) {
if (isDisposed.get()) {
return fluxError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch")));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMapMany(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(),
sessionId, getLinkName(sessionId), sequenceNumbers))
.map(receivedMessage -> {
if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) {
return receivedMessage;
}
if (receiverOptions.getReceiveMode() == ReceiveMode.PEEK_LOCK) {
receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(),
receivedMessage.getLockedUntil(), receivedMessage.getLockedUntil()));
}
return receivedMessage;
});
}
/**
* Asynchronously renews the lock on the specified message. The lock will be renewed based on the setting specified
* on the entity. When a message is received in {@link ReceiveMode
* server for this receiver instance for a duration as specified during the Queue creation (LockDuration). If
* processing of the message requires longer than this duration, the lock needs to be renewed. For each renewal, the
* lock is reset to the entity's LockDuration value.
*
* @param lockToken Lock token of the message to renew.
*
* @return The new expiration time for the message.
* @throws NullPointerException if {@code lockToken} is null.
* @throws UnsupportedOperationException if the receiver was opened in {@link ReceiveMode
* mode.
* @throws IllegalStateException if the receiver is a session receiver.
* @throws IllegalArgumentException if {@code lockToken} is an empty value.
*/
public Mono<Instant> renewMessageLock(String lockToken) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock")));
} else if (Objects.isNull(lockToken)) {
return monoError(logger, new NullPointerException("'lockToken' cannot be null."));
} else if (lockToken.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'lockToken' cannot be empty."));
} else if (receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException(
String.format("Cannot renew message lock [%s] for a session receiver.", lockToken)));
}
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(serviceBusManagementNode ->
serviceBusManagementNode.renewMessageLock(lockToken, getLinkName(null)))
.map(instant -> managementNodeLocks.addOrUpdate(lockToken, instant, instant));
}
/**
* Sets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
*
* @return The next expiration time for the session lock.
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<Instant> renewSessionLock(String sessionId) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot renew session lock on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.renewSessionLock(sessionId, linkName));
}
/**
* Sets the state of a session given its identifier.
*
* @param sessionId Identifier of session to get.
* @param sessionState State to set on the session.
*
* @return A Mono that completes when the session is set
* @throws IllegalStateException if the receiver is a non-session receiver.
*/
public Mono<Void> setSessionState(String sessionId, byte[] sessionState) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState")));
} else if (!receiverOptions.isSessionReceiver()) {
return monoError(logger, new IllegalStateException("Cannot set session state on a non-session receiver."));
}
final String linkName = unnamedSessionManager != null
? unnamedSessionManager.getLinkName(sessionId)
: null;
return connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName));
}
/**
* Starts a new service side transaction. The {@link ServiceBusTransactionContext} should be passed to all
* operations that needs to be in this transaction.
*
* <p><strong>Create a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.createTransaction}
*
* @return The {@link Mono} that finishes this operation on service bus resource.
*/
public Mono<ServiceBusTransactionContext> createTransaction() {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction")));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.createTransaction())
.map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()));
}
/**
* Commits the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Commit a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.commitTransaction}
*
* @param transactionContext to be committed.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
public Mono<Void> commitTransaction(ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "commitTransaction")));
}
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Rollbacks the transaction given {@link ServiceBusTransactionContext}. This will make a call to Service Bus.
* <p><strong>Rollback a transaction</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusasyncreceiverclient.rollbackTransaction}
*
* @param transactionContext to be rollbacked.
*
* @return The {@link Mono} that finishes this operation on service bus resource.
* @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is
* null.
*/
public Mono<Void> rollbackTransaction(ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "rollbackTransaction")));
}
if (Objects.isNull(transactionContext)) {
return monoError(logger, new NullPointerException("'transactionContext' cannot be null."));
} else if (Objects.isNull(transactionContext.getTransactionId())) {
return monoError(logger, new NullPointerException("'transactionContext.transactionId' cannot be null."));
}
return connectionProcessor
.flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME))
.flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction(
transactionContext.getTransactionId())));
}
/**
* Disposes of the consumer by closing the underlying connection to the service.
*/
@Override
public void close() {
if (isDisposed.getAndSet(true)) {
return;
}
logger.info("Removing receiver links.");
final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null);
if (disposed != null) {
disposed.close();
}
if (unnamedSessionManager != null) {
unnamedSessionManager.close();
}
onClientClose.run();
}
/**
* @return receiver options set by user;
*/
ReceiverOptions getReceiverOptions() {
return receiverOptions;
}
/**
* Gets whether or not the management node contains the message lock token and it has not expired. Lock tokens are
* held by the management node when they are received from the management node or management operations are
* performed using that {@code lockToken}.
*
* @param lockToken Lock token to check for.
*
* @return {@code true} if the management node contains the lock token and false otherwise.
*/
private boolean isManagementToken(String lockToken) {
return managementNodeLocks.containsUnexpired(lockToken);
}
private Mono<Void> updateDisposition(String lockToken, DispositionStatus dispositionStatus,
String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify,
String sessionId, ServiceBusTransactionContext transactionContext) {
if (isDisposed.get()) {
return monoError(logger, new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, dispositionStatus.getValue())));
} else if (Objects.isNull(lockToken)) {
return monoError(logger, new NullPointerException("'lockToken' cannot be null."));
} else if (lockToken.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'lockToken' cannot be empty."));
}
if (receiverOptions.getReceiveMode() != ReceiveMode.PEEK_LOCK) {
return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format(
"'%s' is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE.", dispositionStatus))));
}
final String sessionIdToUse;
if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) {
sessionIdToUse = receiverOptions.getSessionId();
} else {
sessionIdToUse = sessionId;
}
logger.info("{}: Update started. Disposition: {}. Lock: {}. SessionId {}.", entityPath, dispositionStatus,
lockToken, sessionIdToUse);
final Mono<Void> performOnManagement = connectionProcessor
.flatMap(connection -> connection.getManagementNode(entityPath, entityType))
.flatMap(node -> node.updateDisposition(lockToken, dispositionStatus, deadLetterReason,
deadLetterErrorDescription, propertiesToModify, sessionId, getLinkName(sessionId), transactionContext))
.then(Mono.fromRunnable(() -> {
logger.info("{}: Management node Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
managementNodeLocks.remove(lockToken);
renewalContainer.remove(lockToken);
}));
if (unnamedSessionManager != null) {
return unnamedSessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify,
deadLetterReason, deadLetterErrorDescription, transactionContext)
.flatMap(isSuccess -> {
if (isSuccess) {
renewalContainer.remove(lockToken);
return Mono.empty();
}
logger.info("Could not perform on session manger. Performing on management node.");
return performOnManagement;
});
}
final ServiceBusAsyncConsumer existingConsumer = consumer.get();
if (isManagementToken(lockToken) || existingConsumer == null) {
return performOnManagement;
} else {
return existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason,
deadLetterErrorDescription, propertiesToModify, transactionContext)
.then(Mono.fromRunnable(() -> {
logger.info("{}: Update completed. Disposition: {}. Lock: {}.",
entityPath, dispositionStatus, lockToken);
renewalContainer.remove(lockToken);
}));
}
}
private ServiceBusAsyncConsumer getOrCreateConsumer() {
final ServiceBusAsyncConsumer existing = consumer.get();
if (existing != null) {
return existing;
}
final String linkName = StringUtil.getRandomString(entityPath);
logger.info("{}: Creating consumer for link '{}'", entityPath, linkName);
final Flux<ServiceBusReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> {
if (receiverOptions.isSessionReceiver()) {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType, receiverOptions.getSessionId());
} else {
return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(),
null, entityType);
}
})
.doOnNext(next -> {
final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]"
+ " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]";
logger.verbose(format, next.getEntityPath(), receiverOptions.getReceiveMode(),
CoreUtils.isNullOrEmpty(receiverOptions.getSessionId()), "N/A", entityType);
})
.repeat();
final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions());
final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith(
new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy,
receiverOptions.getReceiveMode()));
final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor,
messageSerializer, receiverOptions.getPrefetchCount());
if (consumer.compareAndSet(null, newConsumer)) {
return newConsumer;
} else {
newConsumer.close();
return consumer.get();
}
}
/**
* If the receiver has not connected via {@link
* through the management node.
*
* @return The name of the receive link, or null of it has not connected via a receive link.
*/
private String getLinkName(String sessionId) {
if (unnamedSessionManager != null && !CoreUtils.isNullOrEmpty(sessionId)) {
return unnamedSessionManager.getLinkName(sessionId);
} else if (!CoreUtils.isNullOrEmpty(sessionId) && !receiverOptions.isSessionReceiver()) {
return null;
} else {
final ServiceBusAsyncConsumer existing = consumer.get();
return existing != null ? existing.getLinkName() : null;
}
}
} |
👍 | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPolicy = this.retryPolicy != null ? this.retryPolicy : new RetryPolicy();
this.httpPipeline = this.httpPipeline != null ? httpPipeline : buildPipeline(this.tokenCredential, this.endpoint, this.logOptions, this.httpClient, this.additionalPolicies, this.retryPolicy);
return new DigitalTwinsAsyncClient(this.httpPipeline, this.serviceVersion, this.endpoint);
} | this.retryPolicy = this.retryPolicy != null ? this.retryPolicy : new RetryPolicy(); | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPolicy = this.retryPolicy != null ? this.retryPolicy : new RetryPolicy();
if (this.httpPipeline == null)
{
this.httpPipeline = buildPipeline(
this.tokenCredential,
this.endpoint,
this.logOptions,
this.httpClient,
this.additionalPolicies,
this.retryPolicy);
}
return new DigitalTwinsAsyncClient(this.httpPipeline, this.serviceVersion, this.endpoint);
} | class DigitalTwinsClientBuilder {
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions logOptions;
private RetryPolicy retryPolicy;
private static HttpPipeline buildPipeline(TokenCredential tokenCredential, String endpoint,
HttpLogOptions logOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, RetryPolicy retryPolicy) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential, GetAuthorizationScopes(endpoint));
policies.add(credentialPolicy);
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(logOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private static String[] GetAuthorizationScopes(String endpoint) {
String adtPublicCloudAppId = "https:
String defaultPermissionConsent = "/.default";
if (endpoint.indexOf("azure.net") > 0
|| endpoint.indexOf("ppe.net") > 0) {
return new String[]{adtPublicCloudAppId + defaultPermissionConsent};
}
throw new IllegalArgumentException(String.format("Azure digital twins instance endpoint %s is not valid.", endpoint));
}
/**
* Create a {@link DigitalTwinsClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsClient
*/
public DigitalTwinsClient buildClient() {
return new DigitalTwinsClient(buildAsyncClient());
}
/**
* Create a {@link DigitalTwinsAsyncClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsAsyncClient
*/
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Set the authentication token provider that the built client will use for all service requests. This field is
* mandatory to set unless you set the http pipeline directly and that set pipeline has an authentication policy configured.
*
* @param tokenCredential the authentication token provider.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder tokenCredential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link DigitalTwinsServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder serviceVersion(DigitalTwinsServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code logOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public DigitalTwinsClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the request retry options for all the requests made through the client.
*
* @param retryPolicy {@link RetryPolicy}.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code retryOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder retryOptions(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpPipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
} | class DigitalTwinsClientBuilder {
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions logOptions;
private RetryPolicy retryPolicy;
private static HttpPipeline buildPipeline(TokenCredential tokenCredential, String endpoint,
HttpLogOptions logOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, RetryPolicy retryPolicy) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential, GetAuthorizationScopes(endpoint));
policies.add(credentialPolicy);
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(logOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private static String[] GetAuthorizationScopes(String endpoint) {
String adtPublicCloudAppId = "https:
String defaultPermissionConsent = "/.default";
if (endpoint.indexOf("azure.net") > 0
|| endpoint.indexOf("ppe.net") > 0) {
return new String[]{adtPublicCloudAppId + defaultPermissionConsent};
}
throw new IllegalArgumentException(String.format("Azure digital twins instance endpoint %s is not valid.", endpoint));
}
/**
* Create a {@link DigitalTwinsClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsClient
*/
public DigitalTwinsClient buildClient() {
return new DigitalTwinsClient(buildAsyncClient());
}
/**
* Create a {@link DigitalTwinsAsyncClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsAsyncClient
*/
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Set the authentication token provider that the built client will use for all service requests. This field is
* mandatory to set unless you set the http pipeline directly and that set pipeline has an authentication policy configured.
*
* @param tokenCredential the authentication token provider.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder tokenCredential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link DigitalTwinsServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder serviceVersion(DigitalTwinsServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code logOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public DigitalTwinsClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the request retry options for all the requests made through the client. By default, the pipeline will
* use an exponential backoff retry value as detailed in {@link RetryPolicy
*
* @param retryPolicy {@link RetryPolicy}.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code retryOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder retryOptions(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpPipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
} |
can we split this into multiple lines and add tab support? | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPolicy = this.retryPolicy != null ? this.retryPolicy : new RetryPolicy();
this.httpPipeline = this.httpPipeline != null ? httpPipeline : buildPipeline(this.tokenCredential, this.endpoint, this.logOptions, this.httpClient, this.additionalPolicies, this.retryPolicy);
return new DigitalTwinsAsyncClient(this.httpPipeline, this.serviceVersion, this.endpoint);
} | this.httpPipeline = this.httpPipeline != null ? httpPipeline : buildPipeline(this.tokenCredential, this.endpoint, this.logOptions, this.httpClient, this.additionalPolicies, this.retryPolicy); | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPolicy = this.retryPolicy != null ? this.retryPolicy : new RetryPolicy();
if (this.httpPipeline == null)
{
this.httpPipeline = buildPipeline(
this.tokenCredential,
this.endpoint,
this.logOptions,
this.httpClient,
this.additionalPolicies,
this.retryPolicy);
}
return new DigitalTwinsAsyncClient(this.httpPipeline, this.serviceVersion, this.endpoint);
} | class DigitalTwinsClientBuilder {
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions logOptions;
private RetryPolicy retryPolicy;
private static HttpPipeline buildPipeline(TokenCredential tokenCredential, String endpoint,
HttpLogOptions logOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, RetryPolicy retryPolicy) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential, GetAuthorizationScopes(endpoint));
policies.add(credentialPolicy);
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(logOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private static String[] GetAuthorizationScopes(String endpoint) {
String adtPublicCloudAppId = "https:
String defaultPermissionConsent = "/.default";
if (endpoint.indexOf("azure.net") > 0
|| endpoint.indexOf("ppe.net") > 0) {
return new String[]{adtPublicCloudAppId + defaultPermissionConsent};
}
throw new IllegalArgumentException(String.format("Azure digital twins instance endpoint %s is not valid.", endpoint));
}
/**
* Create a {@link DigitalTwinsClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsClient
*/
public DigitalTwinsClient buildClient() {
return new DigitalTwinsClient(buildAsyncClient());
}
/**
* Create a {@link DigitalTwinsAsyncClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsAsyncClient
*/
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Set the authentication token provider that the built client will use for all service requests. This field is
* mandatory to set unless you set the http pipeline directly and that set pipeline has an authentication policy configured.
*
* @param tokenCredential the authentication token provider.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder tokenCredential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link DigitalTwinsServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder serviceVersion(DigitalTwinsServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code logOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public DigitalTwinsClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the request retry options for all the requests made through the client.
*
* @param retryPolicy {@link RetryPolicy}.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code retryOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder retryOptions(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpPipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
} | class DigitalTwinsClientBuilder {
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions logOptions;
private RetryPolicy retryPolicy;
private static HttpPipeline buildPipeline(TokenCredential tokenCredential, String endpoint,
HttpLogOptions logOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, RetryPolicy retryPolicy) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential, GetAuthorizationScopes(endpoint));
policies.add(credentialPolicy);
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(logOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private static String[] GetAuthorizationScopes(String endpoint) {
String adtPublicCloudAppId = "https:
String defaultPermissionConsent = "/.default";
if (endpoint.indexOf("azure.net") > 0
|| endpoint.indexOf("ppe.net") > 0) {
return new String[]{adtPublicCloudAppId + defaultPermissionConsent};
}
throw new IllegalArgumentException(String.format("Azure digital twins instance endpoint %s is not valid.", endpoint));
}
/**
* Create a {@link DigitalTwinsClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsClient
*/
public DigitalTwinsClient buildClient() {
return new DigitalTwinsClient(buildAsyncClient());
}
/**
* Create a {@link DigitalTwinsAsyncClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsAsyncClient
*/
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Set the authentication token provider that the built client will use for all service requests. This field is
* mandatory to set unless you set the http pipeline directly and that set pipeline has an authentication policy configured.
*
* @param tokenCredential the authentication token provider.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder tokenCredential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link DigitalTwinsServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder serviceVersion(DigitalTwinsServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code logOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public DigitalTwinsClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the request retry options for all the requests made through the client. By default, the pipeline will
* use an exponential backoff retry value as detailed in {@link RetryPolicy
*
* @param retryPolicy {@link RetryPolicy}.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code retryOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder retryOptions(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpPipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
} |
Sure, since this line in particular is a bit long | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPolicy = this.retryPolicy != null ? this.retryPolicy : new RetryPolicy();
this.httpPipeline = this.httpPipeline != null ? httpPipeline : buildPipeline(this.tokenCredential, this.endpoint, this.logOptions, this.httpClient, this.additionalPolicies, this.retryPolicy);
return new DigitalTwinsAsyncClient(this.httpPipeline, this.serviceVersion, this.endpoint);
} | this.httpPipeline = this.httpPipeline != null ? httpPipeline : buildPipeline(this.tokenCredential, this.endpoint, this.logOptions, this.httpClient, this.additionalPolicies, this.retryPolicy); | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPolicy = this.retryPolicy != null ? this.retryPolicy : new RetryPolicy();
if (this.httpPipeline == null)
{
this.httpPipeline = buildPipeline(
this.tokenCredential,
this.endpoint,
this.logOptions,
this.httpClient,
this.additionalPolicies,
this.retryPolicy);
}
return new DigitalTwinsAsyncClient(this.httpPipeline, this.serviceVersion, this.endpoint);
} | class DigitalTwinsClientBuilder {
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions logOptions;
private RetryPolicy retryPolicy;
private static HttpPipeline buildPipeline(TokenCredential tokenCredential, String endpoint,
HttpLogOptions logOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, RetryPolicy retryPolicy) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential, GetAuthorizationScopes(endpoint));
policies.add(credentialPolicy);
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(logOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private static String[] GetAuthorizationScopes(String endpoint) {
String adtPublicCloudAppId = "https:
String defaultPermissionConsent = "/.default";
if (endpoint.indexOf("azure.net") > 0
|| endpoint.indexOf("ppe.net") > 0) {
return new String[]{adtPublicCloudAppId + defaultPermissionConsent};
}
throw new IllegalArgumentException(String.format("Azure digital twins instance endpoint %s is not valid.", endpoint));
}
/**
* Create a {@link DigitalTwinsClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsClient
*/
public DigitalTwinsClient buildClient() {
return new DigitalTwinsClient(buildAsyncClient());
}
/**
* Create a {@link DigitalTwinsAsyncClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsAsyncClient
*/
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Set the authentication token provider that the built client will use for all service requests. This field is
* mandatory to set unless you set the http pipeline directly and that set pipeline has an authentication policy configured.
*
* @param tokenCredential the authentication token provider.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder tokenCredential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link DigitalTwinsServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder serviceVersion(DigitalTwinsServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code logOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public DigitalTwinsClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the request retry options for all the requests made through the client.
*
* @param retryPolicy {@link RetryPolicy}.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code retryOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder retryOptions(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpPipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
} | class DigitalTwinsClientBuilder {
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions logOptions;
private RetryPolicy retryPolicy;
private static HttpPipeline buildPipeline(TokenCredential tokenCredential, String endpoint,
HttpLogOptions logOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, RetryPolicy retryPolicy) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential, GetAuthorizationScopes(endpoint));
policies.add(credentialPolicy);
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(logOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private static String[] GetAuthorizationScopes(String endpoint) {
String adtPublicCloudAppId = "https:
String defaultPermissionConsent = "/.default";
if (endpoint.indexOf("azure.net") > 0
|| endpoint.indexOf("ppe.net") > 0) {
return new String[]{adtPublicCloudAppId + defaultPermissionConsent};
}
throw new IllegalArgumentException(String.format("Azure digital twins instance endpoint %s is not valid.", endpoint));
}
/**
* Create a {@link DigitalTwinsClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsClient
*/
public DigitalTwinsClient buildClient() {
return new DigitalTwinsClient(buildAsyncClient());
}
/**
* Create a {@link DigitalTwinsAsyncClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsAsyncClient
*/
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Set the authentication token provider that the built client will use for all service requests. This field is
* mandatory to set unless you set the http pipeline directly and that set pipeline has an authentication policy configured.
*
* @param tokenCredential the authentication token provider.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder tokenCredential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link DigitalTwinsServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder serviceVersion(DigitalTwinsServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code logOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public DigitalTwinsClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the request retry options for all the requests made through the client. By default, the pipeline will
* use an exponential backoff retry value as detailed in {@link RetryPolicy
*
* @param retryPolicy {@link RetryPolicy}.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code retryOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder retryOptions(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpPipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
} |
It would be useful log a warning if the method has any annotation but is non-public. It will let the users know that the visibility of the method is the reason for ignoring it. Same for field too. | public String convertMemberName(Member member) {
if (Modifier.isTransient(member.getModifiers())) {
return null;
}
VisibilityChecker<?> visibilityChecker = mapper.getVisibilityChecker();
if (member instanceof Field) {
Field f = (Field) member;
if (f.isAnnotationPresent(JsonIgnore.class) || !visibilityChecker.isFieldVisible(f)) {
return null;
}
if (f.isAnnotationPresent(JsonProperty.class)) {
String propertyName = f.getDeclaredAnnotation(JsonProperty.class).value();
return CoreUtils.isNullOrEmpty(propertyName) ? f.getName() : propertyName;
}
return f.getName();
}
if (member instanceof Method) {
Method m = (Method) member;
/*
* If the method isn't a getter, is annotated with JsonIgnore, or isn't visible to the ObjectMapper ignore
* it.
*/
if (!verifyGetter(m)
|| m.isAnnotationPresent(JsonIgnore.class)
|| !visibilityChecker.isGetterVisible(m)) {
return null;
}
String methodNameWithoutJavaBeans = removePrefix(m);
/*
* Prefer JsonGetter over JsonProperty as it is the more targeted annotation.
*/
if (m.isAnnotationPresent(JsonGetter.class)) {
String propertyName = m.getDeclaredAnnotation(JsonGetter.class).value();
return CoreUtils.isNullOrEmpty(propertyName) ? methodNameWithoutJavaBeans : propertyName;
}
if (m.isAnnotationPresent(JsonProperty.class)) {
String propertyName = m.getDeclaredAnnotation(JsonProperty.class).value();
return CoreUtils.isNullOrEmpty(propertyName) ? methodNameWithoutJavaBeans : propertyName;
}
return methodNameWithoutJavaBeans;
}
return null;
} | || !visibilityChecker.isGetterVisible(m)) { | public String convertMemberName(Member member) {
if (Modifier.isTransient(member.getModifiers())) {
return null;
}
VisibilityChecker<?> visibilityChecker = mapper.getVisibilityChecker();
if (member instanceof Field) {
Field f = (Field) member;
if (f.isAnnotationPresent(JsonIgnore.class) || !visibilityChecker.isFieldVisible(f)) {
if (f.isAnnotationPresent(JsonProperty.class)) {
logger.info("Field {} is annotated with JsonProperty but isn't accessible to "
+ "JacksonJsonSerializer.", f.getName());
}
return null;
}
if (f.isAnnotationPresent(JsonProperty.class)) {
String propertyName = f.getDeclaredAnnotation(JsonProperty.class).value();
return CoreUtils.isNullOrEmpty(propertyName) ? f.getName() : propertyName;
}
return f.getName();
}
if (member instanceof Method) {
Method m = (Method) member;
/*
* If the method isn't a getter, is annotated with JsonIgnore, or isn't visible to the ObjectMapper ignore
* it.
*/
if (!verifyGetter(m)
|| m.isAnnotationPresent(JsonIgnore.class)
|| !visibilityChecker.isGetterVisible(m)) {
if (m.isAnnotationPresent(JsonGetter.class) || m.isAnnotationPresent(JsonProperty.class)) {
logger.info("Method {} is annotated with either JsonGetter or JsonProperty but isn't accessible "
+ "to JacksonJsonSerializer.", m.getName());
}
return null;
}
String methodNameWithoutJavaBeans = removePrefix(m);
/*
* Prefer JsonGetter over JsonProperty as it is the more targeted annotation.
*/
if (m.isAnnotationPresent(JsonGetter.class)) {
String propertyName = m.getDeclaredAnnotation(JsonGetter.class).value();
return CoreUtils.isNullOrEmpty(propertyName) ? methodNameWithoutJavaBeans : propertyName;
}
if (m.isAnnotationPresent(JsonProperty.class)) {
String propertyName = m.getDeclaredAnnotation(JsonProperty.class).value();
return CoreUtils.isNullOrEmpty(propertyName) ? methodNameWithoutJavaBeans : propertyName;
}
return methodNameWithoutJavaBeans;
}
return null;
} | class JacksonJsonSerializer implements JsonSerializer, MemberNameConverter {
private final ClientLogger logger = new ClientLogger(JacksonJsonSerializer.class);
private final ObjectMapper mapper;
private final TypeFactory typeFactory;
/**
* Constructs a {@link JsonSerializer} using the passed Jackson serializer.
*
* @param mapper Configured Jackson serializer.
*/
JacksonJsonSerializer(ObjectMapper mapper) {
this.mapper = mapper;
this.typeFactory = mapper.getTypeFactory();
}
@Override
public <T> T deserialize(InputStream stream, TypeReference<T> typeReference) {
if (stream == null) {
return null;
}
try {
return mapper.readValue(stream, typeFactory.constructType(typeReference.getJavaType()));
} catch (IOException ex) {
throw logger.logExceptionAsError(new UncheckedIOException(ex));
}
}
@Override
public <T> Mono<T> deserializeAsync(InputStream stream, TypeReference<T> typeReference) {
return Mono.fromCallable(() -> deserialize(stream, typeReference));
}
@Override
public void serialize(OutputStream stream, Object value) {
try {
mapper.writeValue(stream, value);
} catch (IOException ex) {
throw logger.logExceptionAsError(new UncheckedIOException(ex));
}
}
@Override
public Mono<Void> serializeAsync(OutputStream stream, Object value) {
return Mono.fromRunnable(() -> serialize(stream, value));
}
@Override
/*
* Only consider methods that don't have parameters and aren't void as valid getter methods.
*/
private static boolean verifyGetter(Method method) {
Class<?> returnType = method.getReturnType();
return method.getParameterCount() == 0
&& returnType != void.class
&& returnType != Void.class;
}
private static String removePrefix(Method method) {
return BeanUtil.okNameForGetter(new AnnotatedMethod(null, method, null, null), false);
}
} | class JacksonJsonSerializer implements JsonSerializer, MemberNameConverter {
private final ClientLogger logger = new ClientLogger(JacksonJsonSerializer.class);
private final ObjectMapper mapper;
private final TypeFactory typeFactory;
/**
* Constructs a {@link JsonSerializer} using the passed Jackson serializer.
*
* @param mapper Configured Jackson serializer.
*/
JacksonJsonSerializer(ObjectMapper mapper) {
this.mapper = mapper;
this.typeFactory = mapper.getTypeFactory();
}
@Override
public <T> T deserialize(InputStream stream, TypeReference<T> typeReference) {
if (stream == null) {
return null;
}
try {
return mapper.readValue(stream, typeFactory.constructType(typeReference.getJavaType()));
} catch (IOException ex) {
throw logger.logExceptionAsError(new UncheckedIOException(ex));
}
}
@Override
public <T> Mono<T> deserializeAsync(InputStream stream, TypeReference<T> typeReference) {
return Mono.fromCallable(() -> deserialize(stream, typeReference));
}
@Override
public void serialize(OutputStream stream, Object value) {
try {
mapper.writeValue(stream, value);
} catch (IOException ex) {
throw logger.logExceptionAsError(new UncheckedIOException(ex));
}
}
@Override
public Mono<Void> serializeAsync(OutputStream stream, Object value) {
return Mono.fromRunnable(() -> serialize(stream, value));
}
@Override
/*
* Only consider methods that don't have parameters and aren't void as valid getter methods.
*/
private static boolean verifyGetter(Method method) {
Class<?> returnType = method.getReturnType();
return method.getParameterCount() == 0
&& returnType != void.class
&& returnType != Void.class;
}
private static String removePrefix(Method method) {
return BeanUtil.okNameForGetter(new AnnotatedMethod(null, method, null, null), false);
}
} |
I will make code changes after the first round of team review, I will make a note of this comment. | public DigitalTwinsClientBuilder retryOptions(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
return this;
} | this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null."); | public DigitalTwinsClientBuilder retryOptions(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
return this;
} | class DigitalTwinsClientBuilder {
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions logOptions;
private RetryPolicy retryPolicy;
private static HttpPipeline buildPipeline(TokenCredential tokenCredential, String endpoint,
HttpLogOptions logOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, RetryPolicy retryPolicy) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential, GetAuthorizationScopes(endpoint));
policies.add(credentialPolicy);
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(logOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private static String[] GetAuthorizationScopes(String endpoint) {
String adtPublicCloudAppId = "https:
String defaultPermissionConsent = "/.default";
if (endpoint.indexOf("azure.net") > 0
|| endpoint.indexOf("ppe.net") > 0) {
return new String[]{adtPublicCloudAppId + defaultPermissionConsent};
}
throw new IllegalArgumentException(String.format("Azure digital twins instance endpoint %s is not valid.", endpoint));
}
/**
* Create a {@link DigitalTwinsClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsClient
*/
public DigitalTwinsClient buildClient() {
return new DigitalTwinsClient(buildAsyncClient());
}
/**
* Create a {@link DigitalTwinsAsyncClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsAsyncClient
*/
public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPolicy = this.retryPolicy != null ? this.retryPolicy : new RetryPolicy();
if (this.httpPipeline == null)
{
this.httpPipeline = buildPipeline(
this.tokenCredential,
this.endpoint,
this.logOptions,
this.httpClient,
this.additionalPolicies,
this.retryPolicy);
}
return new DigitalTwinsAsyncClient(this.httpPipeline, this.serviceVersion, this.endpoint);
}
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Set the authentication token provider that the built client will use for all service requests. This field is
* mandatory to set unless you set the http pipeline directly and that set pipeline has an authentication policy configured.
*
* @param tokenCredential the authentication token provider.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder tokenCredential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link DigitalTwinsServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder serviceVersion(DigitalTwinsServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code logOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public DigitalTwinsClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the request retry options for all the requests made through the client. By default, the pipeline will
* use an exponential backoff retry value as detailed in {@link RetryPolicy
*
* @param retryPolicy {@link RetryPolicy}.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code retryOptions} is {@code null}.
*/
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpPipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
} | class DigitalTwinsClientBuilder {
private static final String[] adtPublicScope = new String[]{"https:
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions logOptions;
private RetryPolicy retryPolicy;
private static HttpPipeline buildPipeline(TokenCredential tokenCredential, String endpoint,
HttpLogOptions logOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, RetryPolicy retryPolicy) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential, getAuthorizationScopes(endpoint));
policies.add(credentialPolicy);
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(logOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private static String[] getAuthorizationScopes(String endpoint) {
if (endpoint.indexOf("azure.net") > 0
|| endpoint.indexOf("ppe.net") > 0) {
return adtPublicScope;
}
throw new IllegalArgumentException(String.format("Azure digital twins instance endpoint %s is not valid.", endpoint));
}
/**
* Create a {@link DigitalTwinsClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsClient
*/
public DigitalTwinsClient buildClient() {
return new DigitalTwinsClient(buildAsyncClient());
}
/**
* Create a {@link DigitalTwinsAsyncClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsAsyncClient
*/
public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPolicy = this.retryPolicy != null ? this.retryPolicy : new RetryPolicy();
if (this.httpPipeline == null) {
this.httpPipeline = buildPipeline(
this.tokenCredential,
this.endpoint,
this.logOptions,
this.httpClient,
this.additionalPolicies,
this.retryPolicy);
}
return new DigitalTwinsAsyncClient(this.httpPipeline, this.serviceVersion, this.endpoint);
}
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Set the authentication token provider that the built client will use for all service requests. This field is
* mandatory to set unless you set the http pipeline directly and that set pipeline has an authentication policy configured.
*
* @param tokenCredential the authentication token provider.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder tokenCredential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link DigitalTwinsServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder serviceVersion(DigitalTwinsServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code logOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = logOptions;
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public DigitalTwinsClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the request retry options for all the requests made through the client. By default, the pipeline will
* use an exponential backoff retry value as detailed in {@link RetryPolicy
*
* @param retryPolicy {@link RetryPolicy}.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code retryOptions} is {@code null}.
*/
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpPipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
} |
Only log in the instance of the method/field being ignored due to visibility and not due to annotations? | public String convertMemberName(Member member) {
if (Modifier.isTransient(member.getModifiers())) {
return null;
}
VisibilityChecker<?> visibilityChecker = mapper.getVisibilityChecker();
if (member instanceof Field) {
Field f = (Field) member;
if (f.isAnnotationPresent(JsonIgnore.class) || !visibilityChecker.isFieldVisible(f)) {
return null;
}
if (f.isAnnotationPresent(JsonProperty.class)) {
String propertyName = f.getDeclaredAnnotation(JsonProperty.class).value();
return CoreUtils.isNullOrEmpty(propertyName) ? f.getName() : propertyName;
}
return f.getName();
}
if (member instanceof Method) {
Method m = (Method) member;
/*
* If the method isn't a getter, is annotated with JsonIgnore, or isn't visible to the ObjectMapper ignore
* it.
*/
if (!verifyGetter(m)
|| m.isAnnotationPresent(JsonIgnore.class)
|| !visibilityChecker.isGetterVisible(m)) {
return null;
}
String methodNameWithoutJavaBeans = removePrefix(m);
/*
* Prefer JsonGetter over JsonProperty as it is the more targeted annotation.
*/
if (m.isAnnotationPresent(JsonGetter.class)) {
String propertyName = m.getDeclaredAnnotation(JsonGetter.class).value();
return CoreUtils.isNullOrEmpty(propertyName) ? methodNameWithoutJavaBeans : propertyName;
}
if (m.isAnnotationPresent(JsonProperty.class)) {
String propertyName = m.getDeclaredAnnotation(JsonProperty.class).value();
return CoreUtils.isNullOrEmpty(propertyName) ? methodNameWithoutJavaBeans : propertyName;
}
return methodNameWithoutJavaBeans;
}
return null;
} | || !visibilityChecker.isGetterVisible(m)) { | public String convertMemberName(Member member) {
if (Modifier.isTransient(member.getModifiers())) {
return null;
}
VisibilityChecker<?> visibilityChecker = mapper.getVisibilityChecker();
if (member instanceof Field) {
Field f = (Field) member;
if (f.isAnnotationPresent(JsonIgnore.class) || !visibilityChecker.isFieldVisible(f)) {
if (f.isAnnotationPresent(JsonProperty.class)) {
logger.info("Field {} is annotated with JsonProperty but isn't accessible to "
+ "JacksonJsonSerializer.", f.getName());
}
return null;
}
if (f.isAnnotationPresent(JsonProperty.class)) {
String propertyName = f.getDeclaredAnnotation(JsonProperty.class).value();
return CoreUtils.isNullOrEmpty(propertyName) ? f.getName() : propertyName;
}
return f.getName();
}
if (member instanceof Method) {
Method m = (Method) member;
/*
* If the method isn't a getter, is annotated with JsonIgnore, or isn't visible to the ObjectMapper ignore
* it.
*/
if (!verifyGetter(m)
|| m.isAnnotationPresent(JsonIgnore.class)
|| !visibilityChecker.isGetterVisible(m)) {
if (m.isAnnotationPresent(JsonGetter.class) || m.isAnnotationPresent(JsonProperty.class)) {
logger.info("Method {} is annotated with either JsonGetter or JsonProperty but isn't accessible "
+ "to JacksonJsonSerializer.", m.getName());
}
return null;
}
String methodNameWithoutJavaBeans = removePrefix(m);
/*
* Prefer JsonGetter over JsonProperty as it is the more targeted annotation.
*/
if (m.isAnnotationPresent(JsonGetter.class)) {
String propertyName = m.getDeclaredAnnotation(JsonGetter.class).value();
return CoreUtils.isNullOrEmpty(propertyName) ? methodNameWithoutJavaBeans : propertyName;
}
if (m.isAnnotationPresent(JsonProperty.class)) {
String propertyName = m.getDeclaredAnnotation(JsonProperty.class).value();
return CoreUtils.isNullOrEmpty(propertyName) ? methodNameWithoutJavaBeans : propertyName;
}
return methodNameWithoutJavaBeans;
}
return null;
} | class JacksonJsonSerializer implements JsonSerializer, MemberNameConverter {
private final ClientLogger logger = new ClientLogger(JacksonJsonSerializer.class);
private final ObjectMapper mapper;
private final TypeFactory typeFactory;
/**
* Constructs a {@link JsonSerializer} using the passed Jackson serializer.
*
* @param mapper Configured Jackson serializer.
*/
JacksonJsonSerializer(ObjectMapper mapper) {
this.mapper = mapper;
this.typeFactory = mapper.getTypeFactory();
}
@Override
public <T> T deserialize(InputStream stream, TypeReference<T> typeReference) {
if (stream == null) {
return null;
}
try {
return mapper.readValue(stream, typeFactory.constructType(typeReference.getJavaType()));
} catch (IOException ex) {
throw logger.logExceptionAsError(new UncheckedIOException(ex));
}
}
@Override
public <T> Mono<T> deserializeAsync(InputStream stream, TypeReference<T> typeReference) {
return Mono.fromCallable(() -> deserialize(stream, typeReference));
}
@Override
public void serialize(OutputStream stream, Object value) {
try {
mapper.writeValue(stream, value);
} catch (IOException ex) {
throw logger.logExceptionAsError(new UncheckedIOException(ex));
}
}
@Override
public Mono<Void> serializeAsync(OutputStream stream, Object value) {
return Mono.fromRunnable(() -> serialize(stream, value));
}
@Override
/*
* Only consider methods that don't have parameters and aren't void as valid getter methods.
*/
private static boolean verifyGetter(Method method) {
Class<?> returnType = method.getReturnType();
return method.getParameterCount() == 0
&& returnType != void.class
&& returnType != Void.class;
}
private static String removePrefix(Method method) {
return BeanUtil.okNameForGetter(new AnnotatedMethod(null, method, null, null), false);
}
} | class JacksonJsonSerializer implements JsonSerializer, MemberNameConverter {
private final ClientLogger logger = new ClientLogger(JacksonJsonSerializer.class);
private final ObjectMapper mapper;
private final TypeFactory typeFactory;
/**
* Constructs a {@link JsonSerializer} using the passed Jackson serializer.
*
* @param mapper Configured Jackson serializer.
*/
JacksonJsonSerializer(ObjectMapper mapper) {
this.mapper = mapper;
this.typeFactory = mapper.getTypeFactory();
}
@Override
public <T> T deserialize(InputStream stream, TypeReference<T> typeReference) {
if (stream == null) {
return null;
}
try {
return mapper.readValue(stream, typeFactory.constructType(typeReference.getJavaType()));
} catch (IOException ex) {
throw logger.logExceptionAsError(new UncheckedIOException(ex));
}
}
@Override
public <T> Mono<T> deserializeAsync(InputStream stream, TypeReference<T> typeReference) {
return Mono.fromCallable(() -> deserialize(stream, typeReference));
}
@Override
public void serialize(OutputStream stream, Object value) {
try {
mapper.writeValue(stream, value);
} catch (IOException ex) {
throw logger.logExceptionAsError(new UncheckedIOException(ex));
}
}
@Override
public Mono<Void> serializeAsync(OutputStream stream, Object value) {
return Mono.fromRunnable(() -> serialize(stream, value));
}
@Override
/*
* Only consider methods that don't have parameters and aren't void as valid getter methods.
*/
private static boolean verifyGetter(Method method) {
Class<?> returnType = method.getReturnType();
return method.getParameterCount() == 0
&& returnType != void.class
&& returnType != Void.class;
}
private static String removePrefix(Method method) {
return BeanUtil.okNameForGetter(new AnnotatedMethod(null, method, null, null), false);
}
} |
```suggestion if (this.httpPipeline == null) { ``` | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPolicy = this.retryPolicy != null ? this.retryPolicy : new RetryPolicy();
if (this.httpPipeline == null)
{
this.httpPipeline = buildPipeline(
this.tokenCredential,
this.endpoint,
this.logOptions,
this.httpClient,
this.additionalPolicies,
this.retryPolicy);
}
return new DigitalTwinsAsyncClient(this.httpPipeline, this.serviceVersion, this.endpoint);
} | { | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPolicy = this.retryPolicy != null ? this.retryPolicy : new RetryPolicy();
if (this.httpPipeline == null) {
this.httpPipeline = buildPipeline(
this.tokenCredential,
this.endpoint,
this.logOptions,
this.httpClient,
this.additionalPolicies,
this.retryPolicy);
}
return new DigitalTwinsAsyncClient(this.httpPipeline, this.serviceVersion, this.endpoint);
} | class DigitalTwinsClientBuilder {
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions logOptions;
private RetryPolicy retryPolicy;
private static HttpPipeline buildPipeline(TokenCredential tokenCredential, String endpoint,
HttpLogOptions logOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, RetryPolicy retryPolicy) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential, GetAuthorizationScopes(endpoint));
policies.add(credentialPolicy);
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(logOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private static String[] GetAuthorizationScopes(String endpoint) {
String adtPublicCloudAppId = "https:
String defaultPermissionConsent = "/.default";
if (endpoint.indexOf("azure.net") > 0
|| endpoint.indexOf("ppe.net") > 0) {
return new String[]{adtPublicCloudAppId + defaultPermissionConsent};
}
throw new IllegalArgumentException(String.format("Azure digital twins instance endpoint %s is not valid.", endpoint));
}
/**
* Create a {@link DigitalTwinsClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsClient
*/
public DigitalTwinsClient buildClient() {
return new DigitalTwinsClient(buildAsyncClient());
}
/**
* Create a {@link DigitalTwinsAsyncClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsAsyncClient
*/
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Set the authentication token provider that the built client will use for all service requests. This field is
* mandatory to set unless you set the http pipeline directly and that set pipeline has an authentication policy configured.
*
* @param tokenCredential the authentication token provider.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder tokenCredential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link DigitalTwinsServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder serviceVersion(DigitalTwinsServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code logOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public DigitalTwinsClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the request retry options for all the requests made through the client. By default, the pipeline will
* use an exponential backoff retry value as detailed in {@link RetryPolicy
*
* @param retryPolicy {@link RetryPolicy}.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code retryOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder retryOptions(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpPipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
} | class DigitalTwinsClientBuilder {
private static final String[] adtPublicScope = new String[]{"https:
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions logOptions;
private RetryPolicy retryPolicy;
private static HttpPipeline buildPipeline(TokenCredential tokenCredential, String endpoint,
HttpLogOptions logOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, RetryPolicy retryPolicy) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential, getAuthorizationScopes(endpoint));
policies.add(credentialPolicy);
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(logOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private static String[] getAuthorizationScopes(String endpoint) {
if (endpoint.indexOf("azure.net") > 0
|| endpoint.indexOf("ppe.net") > 0) {
return adtPublicScope;
}
throw new IllegalArgumentException(String.format("Azure digital twins instance endpoint %s is not valid.", endpoint));
}
/**
* Create a {@link DigitalTwinsClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsClient
*/
public DigitalTwinsClient buildClient() {
return new DigitalTwinsClient(buildAsyncClient());
}
/**
* Create a {@link DigitalTwinsAsyncClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsAsyncClient
*/
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Set the authentication token provider that the built client will use for all service requests. This field is
* mandatory to set unless you set the http pipeline directly and that set pipeline has an authentication policy configured.
*
* @param tokenCredential the authentication token provider.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder tokenCredential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link DigitalTwinsServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder serviceVersion(DigitalTwinsServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code logOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = logOptions;
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public DigitalTwinsClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the request retry options for all the requests made through the client. By default, the pipeline will
* use an exponential backoff retry value as detailed in {@link RetryPolicy
*
* @param retryPolicy {@link RetryPolicy}.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code retryOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder retryOptions(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpPipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
} |
`HttpLoggingPolicy` allows for `null` `HttpLogOptions` to effectively be a no-op, don't think it needs to be `null` checked here. | public DigitalTwinsClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
} | this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); | public DigitalTwinsClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = logOptions;
return this;
} | class DigitalTwinsClientBuilder {
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions logOptions;
private RetryPolicy retryPolicy;
private static HttpPipeline buildPipeline(TokenCredential tokenCredential, String endpoint,
HttpLogOptions logOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, RetryPolicy retryPolicy) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential, GetAuthorizationScopes(endpoint));
policies.add(credentialPolicy);
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(logOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private static String[] GetAuthorizationScopes(String endpoint) {
String adtPublicCloudAppId = "https:
String defaultPermissionConsent = "/.default";
if (endpoint.indexOf("azure.net") > 0
|| endpoint.indexOf("ppe.net") > 0) {
return new String[]{adtPublicCloudAppId + defaultPermissionConsent};
}
throw new IllegalArgumentException(String.format("Azure digital twins instance endpoint %s is not valid.", endpoint));
}
/**
* Create a {@link DigitalTwinsClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsClient
*/
public DigitalTwinsClient buildClient() {
return new DigitalTwinsClient(buildAsyncClient());
}
/**
* Create a {@link DigitalTwinsAsyncClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsAsyncClient
*/
public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPolicy = this.retryPolicy != null ? this.retryPolicy : new RetryPolicy();
if (this.httpPipeline == null)
{
this.httpPipeline = buildPipeline(
this.tokenCredential,
this.endpoint,
this.logOptions,
this.httpClient,
this.additionalPolicies,
this.retryPolicy);
}
return new DigitalTwinsAsyncClient(this.httpPipeline, this.serviceVersion, this.endpoint);
}
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Set the authentication token provider that the built client will use for all service requests. This field is
* mandatory to set unless you set the http pipeline directly and that set pipeline has an authentication policy configured.
*
* @param tokenCredential the authentication token provider.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder tokenCredential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link DigitalTwinsServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder serviceVersion(DigitalTwinsServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code logOptions} is {@code null}.
*/
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public DigitalTwinsClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the request retry options for all the requests made through the client. By default, the pipeline will
* use an exponential backoff retry value as detailed in {@link RetryPolicy
*
* @param retryPolicy {@link RetryPolicy}.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code retryOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder retryOptions(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpPipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
} | class DigitalTwinsClientBuilder {
private static final String[] adtPublicScope = new String[]{"https:
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions logOptions;
private RetryPolicy retryPolicy;
private static HttpPipeline buildPipeline(TokenCredential tokenCredential, String endpoint,
HttpLogOptions logOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, RetryPolicy retryPolicy) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential, getAuthorizationScopes(endpoint));
policies.add(credentialPolicy);
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(logOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private static String[] getAuthorizationScopes(String endpoint) {
if (endpoint.indexOf("azure.net") > 0
|| endpoint.indexOf("ppe.net") > 0) {
return adtPublicScope;
}
throw new IllegalArgumentException(String.format("Azure digital twins instance endpoint %s is not valid.", endpoint));
}
/**
* Create a {@link DigitalTwinsClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsClient
*/
public DigitalTwinsClient buildClient() {
return new DigitalTwinsClient(buildAsyncClient());
}
/**
* Create a {@link DigitalTwinsAsyncClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsAsyncClient
*/
public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPolicy = this.retryPolicy != null ? this.retryPolicy : new RetryPolicy();
if (this.httpPipeline == null) {
this.httpPipeline = buildPipeline(
this.tokenCredential,
this.endpoint,
this.logOptions,
this.httpClient,
this.additionalPolicies,
this.retryPolicy);
}
return new DigitalTwinsAsyncClient(this.httpPipeline, this.serviceVersion, this.endpoint);
}
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Set the authentication token provider that the built client will use for all service requests. This field is
* mandatory to set unless you set the http pipeline directly and that set pipeline has an authentication policy configured.
*
* @param tokenCredential the authentication token provider.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder tokenCredential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link DigitalTwinsServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder serviceVersion(DigitalTwinsServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code logOptions} is {@code null}.
*/
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public DigitalTwinsClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the request retry options for all the requests made through the client. By default, the pipeline will
* use an exponential backoff retry value as detailed in {@link RetryPolicy
*
* @param retryPolicy {@link RetryPolicy}.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code retryOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder retryOptions(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpPipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
} |
Another fake LRO? | public Mono<RedisCache> updateResourceAsync() {
updateParameters.withTags(this.inner().tags());
return this.manager().inner().getRedis().updateAsync(resourceGroupName(), name(), updateParameters)
.map(innerToFluentMap(this))
.filter(redisCache -> !redisCache.provisioningState().equalsIgnoreCase(ProvisioningState.SUCCEEDED.toString()))
.flatMap(redisCache -> {
SdkContext.sleep(30 * 1000);
this.patchScheduleAdded = false;
return this.manager().inner().getRedis().getByResourceGroupAsync(resourceGroupName(), name())
.doOnNext( this::setInner)
.filter(redisResourceInner -> redisResourceInner.provisioningState().toString()
.equalsIgnoreCase(ProvisioningState.SUCCEEDED.toString()))
.repeatWhenEmpty(
longFlux -> longFlux.flatMap(
index -> Mono.delay(SdkContext.getDelayDuration(Duration.ofSeconds(30)))
)
);
}
)
.then(this.patchSchedules.commitAndGetAllAsync())
.then(this.firewallRules.commitAndGetAllAsync())
.then(Mono.just(this));
} | return this.manager().inner().getRedis().getByResourceGroupAsync(resourceGroupName(), name()) | public Mono<RedisCache> updateResourceAsync() {
updateParameters.withTags(this.inner().tags());
this.patchScheduleAdded = false;
return this
.manager()
.inner()
.getRedis()
.updateAsync(resourceGroupName(), name(), updateParameters)
.map(innerToFluentMap(this))
.filter(
redisCache -> !redisCache.provisioningState().equalsIgnoreCase(ProvisioningState.SUCCEEDED.toString()))
.flatMapMany(
redisCache ->
Mono
.delay(SdkContext.getDelayDuration(Duration.ofSeconds(30)))
.flatMap(o -> manager().inner().getRedis().getByResourceGroupAsync(resourceGroupName(), name()))
.doOnNext(this::setInner)
.repeat()
.takeUntil(
redisResourceInner ->
redisResourceInner
.provisioningState()
.toString()
.equalsIgnoreCase(ProvisioningState.SUCCEEDED.toString())))
.then(this.patchSchedules.commitAndGetAllAsync())
.then(this.firewallRules.commitAndGetAllAsync())
.then(Mono.just(this));
} | class RedisCacheImpl
extends GroupableResourceImpl<
RedisCache,
RedisResourceInner,
RedisCacheImpl,
RedisManager>
implements
RedisCache,
RedisCachePremium,
RedisCache.Definition,
RedisCache.Update {
private RedisAccessKeys cachedAccessKeys;
private RedisCreateParameters createParameters;
private RedisUpdateParameters updateParameters;
private RedisPatchSchedulesImpl patchSchedules;
private RedisFirewallRulesImpl firewallRules;
private boolean patchScheduleAdded;
RedisCacheImpl(String name,
RedisResourceInner innerModel,
final RedisManager redisManager) {
super(name, innerModel, redisManager);
this.createParameters = new RedisCreateParameters();
this.patchSchedules = new RedisPatchSchedulesImpl(this);
this.firewallRules = new RedisFirewallRulesImpl(this);
this.patchSchedules.enablePostRunMode();
this.firewallRules.enablePostRunMode();
this.patchScheduleAdded = false;
}
@Override
public Map<String, RedisFirewallRule> firewallRules() {
return this.firewallRules.rulesAsMap();
}
@Override
public List<ScheduleEntry> patchSchedules() {
List<ScheduleEntry> patchSchedules = listPatchSchedules();
if (patchSchedules == null) {
return new ArrayList<>();
}
return patchSchedules;
}
@Override
public List<ScheduleEntry> listPatchSchedules() {
RedisPatchScheduleImpl patchSchedule = this.patchSchedules.getPatchSchedule();
if (patchSchedule == null) {
return null;
}
return patchSchedule.scheduleEntries();
}
@Override
public String provisioningState() {
return this.inner().provisioningState().toString();
}
@Override
public String hostname() {
return this.inner().hostname();
}
@Override
public int port() {
return Utils.toPrimitiveInt(this.inner().port());
}
@Override
public int sslPort() {
return Utils.toPrimitiveInt(this.inner().sslPort());
}
@Override
public String redisVersion() {
return this.inner().redisVersion();
}
@Override
public Sku sku() {
return this.inner().sku();
}
@Override
public boolean nonSslPort() {
return this.inner().enableNonSslPort();
}
@Override
public int shardCount() {
return Utils.toPrimitiveInt(this.inner().shardCount());
}
@Override
public String subnetId() {
return this.inner().subnetId();
}
@Override
public String staticIp() {
return this.inner().staticIp();
}
@Override
public TlsVersion minimumTlsVersion() {
return this.inner().minimumTlsVersion();
}
@Override
public Map<String, String> redisConfiguration() {
return Collections.unmodifiableMap(this.inner().redisConfiguration());
}
@Override
public RedisCachePremium asPremium() {
if (this.isPremium()) {
return this;
}
return null;
}
@Override
public boolean isPremium() {
return this.sku().name().equals(SkuName.PREMIUM);
}
@Override
public RedisAccessKeys keys() {
if (cachedAccessKeys == null) {
cachedAccessKeys = refreshKeys();
}
return cachedAccessKeys;
}
@Override
public RedisAccessKeys refreshKeys() {
RedisAccessKeysInner response =
this.manager().inner().getRedis().listKeys(this.resourceGroupName(), this.name());
cachedAccessKeys = new RedisAccessKeysImpl(response);
return cachedAccessKeys;
}
@Override
public RedisAccessKeys regenerateKey(RedisKeyType keyType) {
RedisAccessKeysInner response =
this.manager().inner().getRedis().regenerateKey(this.resourceGroupName(), this.name(), keyType);
cachedAccessKeys = new RedisAccessKeysImpl(response);
return cachedAccessKeys;
}
@Override
public void forceReboot(RebootType rebootType) {
RedisRebootParameters parameters = new RedisRebootParameters()
.withRebootType(rebootType);
this.manager().inner().getRedis().forceReboot(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void forceReboot(RebootType rebootType, int shardId) {
RedisRebootParameters parameters = new RedisRebootParameters()
.withRebootType(rebootType)
.withShardId(shardId);
this.manager().inner().getRedis().forceReboot(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void importData(List<String> files) {
ImportRdbParameters parameters = new ImportRdbParameters()
.withFiles(files);
this.manager().inner().getRedis().importData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void importData(List<String> files, String fileFormat) {
ImportRdbParameters parameters = new ImportRdbParameters()
.withFiles(files)
.withFormat(fileFormat);
this.manager().inner().getRedis().importData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void exportData(String containerSASUrl, String prefix) {
ExportRdbParameters parameters = new ExportRdbParameters()
.withContainer(containerSASUrl)
.withPrefix(prefix);
this.manager().inner().getRedis().exportData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void exportData(String containerSASUrl, String prefix, String fileFormat) {
ExportRdbParameters parameters = new ExportRdbParameters()
.withContainer(containerSASUrl)
.withPrefix(prefix)
.withFormat(fileFormat);
this.manager().inner().getRedis().exportData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public RedisCacheImpl withNonSslPort() {
if (isInCreateMode()) {
createParameters.withEnableNonSslPort(true);
} else {
updateParameters.withEnableNonSslPort(true);
}
return this;
}
@Override
public RedisCacheImpl withoutNonSslPort() {
if (!isInCreateMode()) {
updateParameters.withEnableNonSslPort(false);
}
return this;
}
@Override
public RedisCacheImpl withRedisConfiguration(Map<String, String> redisConfiguration) {
if (isInCreateMode()) {
createParameters.withRedisConfiguration(redisConfiguration);
} else {
updateParameters.withRedisConfiguration(redisConfiguration);
}
return this;
}
@Override
public RedisCacheImpl withRedisConfiguration(String key, String value) {
if (isInCreateMode()) {
if (createParameters.redisConfiguration() == null) {
createParameters.withRedisConfiguration(new TreeMap<>());
}
createParameters.redisConfiguration().put(key, value);
} else {
if (updateParameters.redisConfiguration() == null) {
updateParameters.withRedisConfiguration(new TreeMap<>());
}
updateParameters.redisConfiguration().put(key, value);
}
return this;
}
@Override
public RedisCacheImpl withFirewallRule(String name, String lowestIp, String highestIp) {
RedisFirewallRuleImpl rule = this.firewallRules.defineInlineFirewallRule(name);
rule.inner().withStartIp(lowestIp);
rule.inner().withEndIp(highestIp);
return this.withFirewallRule(rule);
}
@Override
public RedisCacheImpl withFirewallRule(RedisFirewallRule rule) {
this.firewallRules.addRule((RedisFirewallRuleImpl) rule);
return this;
}
@Override
public RedisCacheImpl withMinimumTlsVersion(TlsVersion tlsVersion) {
if (isInCreateMode()) {
createParameters.withMinimumTlsVersion(tlsVersion);
} else {
updateParameters.withMinimumTlsVersion(tlsVersion);
}
return this;
}
@Override
public RedisCacheImpl withoutMinimumTlsVersion() {
updateParameters.withMinimumTlsVersion(null);
return this;
}
@Override
public RedisCacheImpl withoutFirewallRule(String name) {
this.firewallRules.removeRule(name);
return this;
}
@Override
public RedisCacheImpl withoutRedisConfiguration() {
if (updateParameters.redisConfiguration() != null) {
updateParameters.redisConfiguration().clear();
}
return this;
}
@Override
public RedisCacheImpl withoutRedisConfiguration(String key) {
if (updateParameters.redisConfiguration() != null) {
updateParameters.redisConfiguration().remove(key);
}
return this;
}
@Override
public RedisCacheImpl withSubnet(HasId networkResource, String subnetName) {
if (networkResource != null) {
String subnetId = networkResource.id() + "/subnets/" + subnetName;
return withSubnet(subnetId);
} else {
createParameters.withSubnetId(null);
}
return this;
}
@Override
public RedisCacheImpl withSubnet(String subnetId) {
if (subnetId != null) {
if (isInCreateMode()) {
createParameters.withSubnetId(subnetId);
} else {
throw new UnsupportedOperationException("Subnet cannot be modified during update operation.");
}
}
return this;
}
@Override
public RedisCacheImpl withStaticIp(String staticIp) {
if (isInCreateMode()) {
createParameters.withStaticIp(staticIp);
} else {
throw new UnsupportedOperationException("Static IP cannot be modified during update operation.");
}
return this;
}
@Override
public RedisCacheImpl withBasicSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.BASIC)
.withFamily(SkuFamily.C));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.BASIC)
.withFamily(SkuFamily.C));
}
return this;
}
@Override
public RedisCacheImpl withBasicSku(int capacity) {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.BASIC)
.withFamily(SkuFamily.C)
.withCapacity(capacity));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.BASIC)
.withFamily(SkuFamily.C)
.withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withStandardSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.STANDARD)
.withFamily(SkuFamily.C));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.STANDARD)
.withFamily(SkuFamily.C));
}
return this;
}
@Override
public RedisCacheImpl withStandardSku(int capacity) {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.STANDARD)
.withFamily(SkuFamily.C)
.withCapacity(capacity));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.STANDARD)
.withFamily(SkuFamily.C)
.withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withPremiumSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.PREMIUM)
.withFamily(SkuFamily.P)
.withCapacity(1));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.PREMIUM)
.withFamily(SkuFamily.P)
.withCapacity(1));
}
return this;
}
@Override
public RedisCacheImpl withPremiumSku(int capacity) {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.PREMIUM)
.withFamily(SkuFamily.P)
.withCapacity(capacity));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.PREMIUM)
.withFamily(SkuFamily.P)
.withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withShardCount(int shardCount) {
if (isInCreateMode()) {
createParameters.withShardCount(shardCount);
} else {
updateParameters.withShardCount(shardCount);
}
return this;
}
@Override
public RedisCacheImpl withPatchSchedule(DayOfWeek dayOfWeek, int startHourUtc) {
return this.withPatchSchedule(new ScheduleEntry()
.withDayOfWeek(dayOfWeek)
.withStartHourUtc(startHourUtc));
}
@Override
public RedisCacheImpl withPatchSchedule(DayOfWeek dayOfWeek, int startHourUtc, Duration maintenanceWindow) {
return this.withPatchSchedule(new ScheduleEntry()
.withDayOfWeek(dayOfWeek)
.withStartHourUtc(startHourUtc)
.withMaintenanceWindow(maintenanceWindow));
}
@Override
public RedisCacheImpl withPatchSchedule(List<ScheduleEntry> scheduleEntries) {
this.patchSchedules.clear();
for (ScheduleEntry entry : scheduleEntries) {
this.withPatchSchedule(entry);
}
return this;
}
@Override
public RedisCacheImpl withPatchSchedule(ScheduleEntry scheduleEntry) {
RedisPatchScheduleImpl psch;
if (this.patchSchedules.patchSchedulesAsMap().isEmpty()) {
psch = this.patchSchedules.defineInlinePatchSchedule();
this.patchScheduleAdded = true;
psch.inner().withScheduleEntries(new ArrayList<>());
this.patchSchedules.addPatchSchedule(psch);
} else if (!this.patchScheduleAdded) {
psch = this.patchSchedules.updateInlinePatchSchedule();
} else {
psch = this.patchSchedules.getPatchSchedule();
}
psch.inner().scheduleEntries().add(scheduleEntry);
return this;
}
@Override
public RedisCacheImpl withoutPatchSchedule() {
if (this.patchSchedules.patchSchedulesAsMap().isEmpty()) {
return this;
} else {
this.patchSchedules.deleteInlinePatchSchedule();
}
return this;
}
@Override
public void deletePatchSchedule() {
this.patchSchedules.removePatchSchedule();
this.patchSchedules.refresh();
}
@Override
public Mono<RedisCache> refreshAsync() {
return super.refreshAsync()
.then(this.firewallRules.refreshAsync())
.then(this.patchSchedules.refreshAsync())
.then(Mono.just(this));
}
@Override
protected Mono<RedisResourceInner> getInnerAsync() {
return this.manager().inner().getRedis().getByResourceGroupAsync(this.resourceGroupName(), this.name());
}
@Override
public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) {
this.firewallRules.clear();
this.patchSchedules.clear();
this.patchScheduleAdded = false;
if (isGroupFaulted) {
return Mono.empty();
} else {
return this.refreshAsync().then();
}
}
@Override
public RedisCacheImpl update() {
this.updateParameters = new RedisUpdateParameters();
this.patchSchedules.enableCommitMode();
this.firewallRules.enableCommitMode();
return super.update();
}
@Override
@Override
public Mono<RedisCache> createResourceAsync() {
createParameters.withLocation(this.regionName());
createParameters.withTags(this.inner().tags());
this.patchScheduleAdded = false;
return this.manager().inner().getRedis().createAsync(this.resourceGroupName(), this.name(), createParameters)
.map(innerToFluentMap(this));
}
@Override
public String addLinkedServer(String linkedRedisCacheId, String linkedServerLocation, ReplicationRole role) {
String linkedRedisName = ResourceUtils.nameFromResourceId(linkedRedisCacheId);
RedisLinkedServerCreateParameters params = new RedisLinkedServerCreateParameters()
.withLinkedRedisCacheId(linkedRedisCacheId)
.withLinkedRedisCacheLocation(linkedServerLocation)
.withServerRole(role);
RedisLinkedServerWithPropertiesInner linkedServerInner = this.manager().inner().getLinkedServers().create(
this.resourceGroupName(),
this.name(),
linkedRedisName,
params);
return linkedServerInner.name();
}
@Override
public void removeLinkedServer(String linkedServerName) {
RedisLinkedServerWithPropertiesInner linkedServer = this.manager().inner().getLinkedServers().get(this.resourceGroupName(), this.name(), linkedServerName);
this.manager().inner().getLinkedServers().delete(
this.resourceGroupName(),
this.name(),
linkedServerName);
RedisResourceInner innerLinkedResource = null;
RedisResourceInner innerResource = null;
while (innerLinkedResource == null
|| innerLinkedResource.provisioningState() != ProvisioningState.SUCCEEDED
|| innerResource == null
|| innerResource.provisioningState() != ProvisioningState.SUCCEEDED) {
SdkContext.sleep(30 * 1000);
innerLinkedResource = this.manager().inner().getRedis().getByResourceGroup(
ResourceUtils.groupFromResourceId(linkedServer.id()),
ResourceUtils.nameFromResourceId(linkedServer.id()));
innerResource = this.manager().inner().getRedis().getByResourceGroup(resourceGroupName(), name());
}
}
@Override
public ReplicationRole getLinkedServerRole(String linkedServerName) {
RedisLinkedServerWithPropertiesInner linkedServer = this.manager().inner().getLinkedServers().get(
this.resourceGroupName(),
this.name(),
linkedServerName);
if (linkedServer == null) {
throw new IllegalArgumentException("Server returned `null` value for Linked Server '"
+ linkedServerName + "' for Redis Cache '" + this.name()
+ "' in Resource Group '" + this.resourceGroupName() + "'.");
}
return linkedServer.serverRole();
}
@Override
public Map<String, ReplicationRole> listLinkedServers() {
Map<String, ReplicationRole> result = new TreeMap<>();
PagedIterable<RedisLinkedServerWithPropertiesInner> paginatedResponse = this.manager().inner().getLinkedServers().list(
this.resourceGroupName(),
this.name());
for (RedisLinkedServerWithPropertiesInner linkedServer : paginatedResponse) {
result.put(linkedServer.name(), linkedServer.serverRole());
}
return result;
}
} | class RedisCacheImpl extends GroupableResourceImpl<RedisCache, RedisResourceInner, RedisCacheImpl, RedisManager>
implements RedisCache, RedisCachePremium, RedisCache.Definition, RedisCache.Update {
private final ClientLogger logger = new ClientLogger(getClass());
private RedisAccessKeys cachedAccessKeys;
private RedisCreateParameters createParameters;
private RedisUpdateParameters updateParameters;
private RedisPatchSchedulesImpl patchSchedules;
private RedisFirewallRulesImpl firewallRules;
private boolean patchScheduleAdded;
RedisCacheImpl(String name, RedisResourceInner innerModel, final RedisManager redisManager) {
super(name, innerModel, redisManager);
this.createParameters = new RedisCreateParameters();
this.patchSchedules = new RedisPatchSchedulesImpl(this);
this.firewallRules = new RedisFirewallRulesImpl(this);
this.patchSchedules.enablePostRunMode();
this.firewallRules.enablePostRunMode();
this.patchScheduleAdded = false;
}
@Override
public Map<String, RedisFirewallRule> firewallRules() {
return this.firewallRules.rulesAsMap();
}
@Override
public List<ScheduleEntry> patchSchedules() {
List<ScheduleEntry> patchSchedules = listPatchSchedules();
if (patchSchedules == null) {
return new ArrayList<>();
}
return patchSchedules;
}
@Override
public List<ScheduleEntry> listPatchSchedules() {
RedisPatchScheduleImpl patchSchedule = this.patchSchedules.getPatchSchedule();
if (patchSchedule == null) {
return null;
}
return patchSchedule.scheduleEntries();
}
@Override
public String provisioningState() {
return this.inner().provisioningState().toString();
}
@Override
public String hostname() {
return this.inner().hostname();
}
@Override
public int port() {
return Utils.toPrimitiveInt(this.inner().port());
}
@Override
public int sslPort() {
return Utils.toPrimitiveInt(this.inner().sslPort());
}
@Override
public String redisVersion() {
return this.inner().redisVersion();
}
@Override
public Sku sku() {
return this.inner().sku();
}
@Override
public boolean nonSslPort() {
return this.inner().enableNonSslPort();
}
@Override
public int shardCount() {
return Utils.toPrimitiveInt(this.inner().shardCount());
}
@Override
public String subnetId() {
return this.inner().subnetId();
}
@Override
public String staticIp() {
return this.inner().staticIp();
}
@Override
public TlsVersion minimumTlsVersion() {
return this.inner().minimumTlsVersion();
}
@Override
public Map<String, String> redisConfiguration() {
return Collections.unmodifiableMap(this.inner().redisConfiguration());
}
@Override
public RedisCachePremium asPremium() {
if (this.isPremium()) {
return this;
}
return null;
}
@Override
public boolean isPremium() {
return this.sku().name().equals(SkuName.PREMIUM);
}
@Override
public RedisAccessKeys keys() {
if (cachedAccessKeys == null) {
cachedAccessKeys = refreshKeys();
}
return cachedAccessKeys;
}
@Override
public RedisAccessKeys refreshKeys() {
RedisAccessKeysInner response =
this.manager().inner().getRedis().listKeys(this.resourceGroupName(), this.name());
cachedAccessKeys = new RedisAccessKeysImpl(response);
return cachedAccessKeys;
}
@Override
public RedisAccessKeys regenerateKey(RedisKeyType keyType) {
RedisAccessKeysInner response =
this.manager().inner().getRedis().regenerateKey(this.resourceGroupName(), this.name(), keyType);
cachedAccessKeys = new RedisAccessKeysImpl(response);
return cachedAccessKeys;
}
@Override
public void forceReboot(RebootType rebootType) {
RedisRebootParameters parameters = new RedisRebootParameters().withRebootType(rebootType);
this.manager().inner().getRedis().forceReboot(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void forceReboot(RebootType rebootType, int shardId) {
RedisRebootParameters parameters = new RedisRebootParameters().withRebootType(rebootType).withShardId(shardId);
this.manager().inner().getRedis().forceReboot(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void importData(List<String> files) {
ImportRdbParameters parameters = new ImportRdbParameters().withFiles(files);
this.manager().inner().getRedis().importData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void importData(List<String> files, String fileFormat) {
ImportRdbParameters parameters = new ImportRdbParameters().withFiles(files).withFormat(fileFormat);
this.manager().inner().getRedis().importData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void exportData(String containerSASUrl, String prefix) {
ExportRdbParameters parameters = new ExportRdbParameters().withContainer(containerSASUrl).withPrefix(prefix);
this.manager().inner().getRedis().exportData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void exportData(String containerSASUrl, String prefix, String fileFormat) {
ExportRdbParameters parameters =
new ExportRdbParameters().withContainer(containerSASUrl).withPrefix(prefix).withFormat(fileFormat);
this.manager().inner().getRedis().exportData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public RedisCacheImpl withNonSslPort() {
if (isInCreateMode()) {
createParameters.withEnableNonSslPort(true);
} else {
updateParameters.withEnableNonSslPort(true);
}
return this;
}
@Override
public RedisCacheImpl withoutNonSslPort() {
if (!isInCreateMode()) {
updateParameters.withEnableNonSslPort(false);
}
return this;
}
@Override
public RedisCacheImpl withRedisConfiguration(Map<String, String> redisConfiguration) {
if (isInCreateMode()) {
createParameters.withRedisConfiguration(redisConfiguration);
} else {
updateParameters.withRedisConfiguration(redisConfiguration);
}
return this;
}
@Override
public RedisCacheImpl withRedisConfiguration(String key, String value) {
if (isInCreateMode()) {
if (createParameters.redisConfiguration() == null) {
createParameters.withRedisConfiguration(new TreeMap<>());
}
createParameters.redisConfiguration().put(key, value);
} else {
if (updateParameters.redisConfiguration() == null) {
updateParameters.withRedisConfiguration(new TreeMap<>());
}
updateParameters.redisConfiguration().put(key, value);
}
return this;
}
@Override
public RedisCacheImpl withFirewallRule(String name, String lowestIp, String highestIp) {
RedisFirewallRuleImpl rule = this.firewallRules.defineInlineFirewallRule(name);
rule.inner().withStartIp(lowestIp);
rule.inner().withEndIp(highestIp);
return this.withFirewallRule(rule);
}
@Override
public RedisCacheImpl withFirewallRule(RedisFirewallRule rule) {
this.firewallRules.addRule((RedisFirewallRuleImpl) rule);
return this;
}
@Override
public RedisCacheImpl withMinimumTlsVersion(TlsVersion tlsVersion) {
if (isInCreateMode()) {
createParameters.withMinimumTlsVersion(tlsVersion);
} else {
updateParameters.withMinimumTlsVersion(tlsVersion);
}
return this;
}
@Override
public RedisCacheImpl withoutMinimumTlsVersion() {
updateParameters.withMinimumTlsVersion(null);
return this;
}
@Override
public RedisCacheImpl withoutFirewallRule(String name) {
this.firewallRules.removeRule(name);
return this;
}
@Override
public RedisCacheImpl withoutRedisConfiguration() {
if (updateParameters.redisConfiguration() != null) {
updateParameters.redisConfiguration().clear();
}
return this;
}
@Override
public RedisCacheImpl withoutRedisConfiguration(String key) {
if (updateParameters.redisConfiguration() != null) {
updateParameters.redisConfiguration().remove(key);
}
return this;
}
@Override
public RedisCacheImpl withSubnet(HasId networkResource, String subnetName) {
if (networkResource != null) {
String subnetId = networkResource.id() + "/subnets/" + subnetName;
return withSubnet(subnetId);
} else {
createParameters.withSubnetId(null);
}
return this;
}
@Override
public RedisCacheImpl withSubnet(String subnetId) {
if (subnetId != null) {
if (isInCreateMode()) {
createParameters.withSubnetId(subnetId);
} else {
throw logger
.logExceptionAsError(
new UnsupportedOperationException("Subnet cannot be modified during update operation."));
}
}
return this;
}
@Override
public RedisCacheImpl withStaticIp(String staticIp) {
if (isInCreateMode()) {
createParameters.withStaticIp(staticIp);
} else {
throw logger
.logExceptionAsError(
new UnsupportedOperationException("Static IP cannot be modified during update operation."));
}
return this;
}
@Override
public RedisCacheImpl withBasicSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku().withName(SkuName.BASIC).withFamily(SkuFamily.C));
} else {
updateParameters.withSku(new Sku().withName(SkuName.BASIC).withFamily(SkuFamily.C));
}
return this;
}
@Override
public RedisCacheImpl withBasicSku(int capacity) {
if (isInCreateMode()) {
createParameters.withSku(new Sku().withName(SkuName.BASIC).withFamily(SkuFamily.C).withCapacity(capacity));
} else {
updateParameters.withSku(new Sku().withName(SkuName.BASIC).withFamily(SkuFamily.C).withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withStandardSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku().withName(SkuName.STANDARD).withFamily(SkuFamily.C));
} else {
updateParameters.withSku(new Sku().withName(SkuName.STANDARD).withFamily(SkuFamily.C));
}
return this;
}
@Override
public RedisCacheImpl withStandardSku(int capacity) {
if (isInCreateMode()) {
createParameters
.withSku(new Sku().withName(SkuName.STANDARD).withFamily(SkuFamily.C).withCapacity(capacity));
} else {
updateParameters
.withSku(new Sku().withName(SkuName.STANDARD).withFamily(SkuFamily.C).withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withPremiumSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku().withName(SkuName.PREMIUM).withFamily(SkuFamily.P).withCapacity(1));
} else {
updateParameters.withSku(new Sku().withName(SkuName.PREMIUM).withFamily(SkuFamily.P).withCapacity(1));
}
return this;
}
@Override
public RedisCacheImpl withPremiumSku(int capacity) {
if (isInCreateMode()) {
createParameters
.withSku(new Sku().withName(SkuName.PREMIUM).withFamily(SkuFamily.P).withCapacity(capacity));
} else {
updateParameters
.withSku(new Sku().withName(SkuName.PREMIUM).withFamily(SkuFamily.P).withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withShardCount(int shardCount) {
if (isInCreateMode()) {
createParameters.withShardCount(shardCount);
} else {
updateParameters.withShardCount(shardCount);
}
return this;
}
@Override
public RedisCacheImpl withPatchSchedule(DayOfWeek dayOfWeek, int startHourUtc) {
return this.withPatchSchedule(new ScheduleEntry().withDayOfWeek(dayOfWeek).withStartHourUtc(startHourUtc));
}
@Override
public RedisCacheImpl withPatchSchedule(DayOfWeek dayOfWeek, int startHourUtc, Duration maintenanceWindow) {
return this
.withPatchSchedule(
new ScheduleEntry()
.withDayOfWeek(dayOfWeek)
.withStartHourUtc(startHourUtc)
.withMaintenanceWindow(maintenanceWindow));
}
@Override
public RedisCacheImpl withPatchSchedule(List<ScheduleEntry> scheduleEntries) {
this.patchSchedules.clear();
for (ScheduleEntry entry : scheduleEntries) {
this.withPatchSchedule(entry);
}
return this;
}
@Override
public RedisCacheImpl withPatchSchedule(ScheduleEntry scheduleEntry) {
RedisPatchScheduleImpl psch;
if (this.patchSchedules.patchSchedulesAsMap().isEmpty()) {
psch = this.patchSchedules.defineInlinePatchSchedule();
this.patchScheduleAdded = true;
psch.inner().withScheduleEntries(new ArrayList<>());
this.patchSchedules.addPatchSchedule(psch);
} else if (!this.patchScheduleAdded) {
psch = this.patchSchedules.updateInlinePatchSchedule();
} else {
psch = this.patchSchedules.getPatchSchedule();
}
psch.inner().scheduleEntries().add(scheduleEntry);
return this;
}
@Override
public RedisCacheImpl withoutPatchSchedule() {
if (this.patchSchedules.patchSchedulesAsMap().isEmpty()) {
return this;
} else {
this.patchSchedules.deleteInlinePatchSchedule();
}
return this;
}
@Override
public void deletePatchSchedule() {
this.patchSchedules.removePatchSchedule();
this.patchSchedules.refresh();
}
@Override
public Mono<RedisCache> refreshAsync() {
return super
.refreshAsync()
.then(this.firewallRules.refreshAsync())
.then(this.patchSchedules.refreshAsync())
.then(Mono.just(this));
}
@Override
protected Mono<RedisResourceInner> getInnerAsync() {
return this.manager().inner().getRedis().getByResourceGroupAsync(this.resourceGroupName(), this.name());
}
@Override
public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) {
this.firewallRules.clear();
this.patchSchedules.clear();
this.patchScheduleAdded = false;
if (isGroupFaulted) {
return Mono.empty();
} else {
return this.refreshAsync().then();
}
}
@Override
public RedisCacheImpl update() {
this.updateParameters = new RedisUpdateParameters();
this.patchSchedules.enableCommitMode();
this.firewallRules.enableCommitMode();
return super.update();
}
@Override
@Override
public Mono<RedisCache> createResourceAsync() {
createParameters.withLocation(this.regionName());
createParameters.withTags(this.inner().tags());
this.patchScheduleAdded = false;
return this
.manager()
.inner()
.getRedis()
.createAsync(this.resourceGroupName(), this.name(), createParameters)
.map(innerToFluentMap(this));
}
@Override
public String addLinkedServer(String linkedRedisCacheId, String linkedServerLocation, ReplicationRole role) {
String linkedRedisName = ResourceUtils.nameFromResourceId(linkedRedisCacheId);
RedisLinkedServerCreateParameters params =
new RedisLinkedServerCreateParameters()
.withLinkedRedisCacheId(linkedRedisCacheId)
.withLinkedRedisCacheLocation(linkedServerLocation)
.withServerRole(role);
RedisLinkedServerWithPropertiesInner linkedServerInner =
this
.manager()
.inner()
.getLinkedServers()
.create(this.resourceGroupName(), this.name(), linkedRedisName, params);
return linkedServerInner.name();
}
@Override
public void removeLinkedServer(String linkedServerName) {
RedisLinkedServerWithPropertiesInner linkedServer =
this.manager().inner().getLinkedServers().get(this.resourceGroupName(), this.name(), linkedServerName);
this.manager().inner().getLinkedServers().delete(this.resourceGroupName(), this.name(), linkedServerName);
RedisResourceInner innerLinkedResource = null;
RedisResourceInner innerResource = null;
while (innerLinkedResource == null
|| innerLinkedResource.provisioningState() != ProvisioningState.SUCCEEDED
|| innerResource == null
|| innerResource.provisioningState() != ProvisioningState.SUCCEEDED) {
SdkContext.sleep(30 * 1000);
innerLinkedResource =
this
.manager()
.inner()
.getRedis()
.getByResourceGroup(
ResourceUtils.groupFromResourceId(linkedServer.id()),
ResourceUtils.nameFromResourceId(linkedServer.id()));
innerResource = this.manager().inner().getRedis().getByResourceGroup(resourceGroupName(), name());
}
}
@Override
public ReplicationRole getLinkedServerRole(String linkedServerName) {
RedisLinkedServerWithPropertiesInner linkedServer =
this.manager().inner().getLinkedServers().get(this.resourceGroupName(), this.name(), linkedServerName);
if (linkedServer == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"Server returned `null` value for Linked Server '"
+ linkedServerName
+ "' for Redis Cache '"
+ this.name()
+ "' in Resource Group '"
+ this.resourceGroupName()
+ "'."));
}
return linkedServer.serverRole();
}
@Override
public Map<String, ReplicationRole> listLinkedServers() {
Map<String, ReplicationRole> result = new TreeMap<>();
PagedIterable<RedisLinkedServerWithPropertiesInner> paginatedResponse =
this.manager().inner().getLinkedServers().list(this.resourceGroupName(), this.name());
for (RedisLinkedServerWithPropertiesInner linkedServer : paginatedResponse) {
result.put(linkedServer.name(), linkedServer.serverRole());
}
return result;
}
} |
Yes, the redis doesn't go through official LRO, like cosmos | public Mono<RedisCache> updateResourceAsync() {
updateParameters.withTags(this.inner().tags());
return this.manager().inner().getRedis().updateAsync(resourceGroupName(), name(), updateParameters)
.map(innerToFluentMap(this))
.filter(redisCache -> !redisCache.provisioningState().equalsIgnoreCase(ProvisioningState.SUCCEEDED.toString()))
.flatMap(redisCache -> {
SdkContext.sleep(30 * 1000);
this.patchScheduleAdded = false;
return this.manager().inner().getRedis().getByResourceGroupAsync(resourceGroupName(), name())
.doOnNext( this::setInner)
.filter(redisResourceInner -> redisResourceInner.provisioningState().toString()
.equalsIgnoreCase(ProvisioningState.SUCCEEDED.toString()))
.repeatWhenEmpty(
longFlux -> longFlux.flatMap(
index -> Mono.delay(SdkContext.getDelayDuration(Duration.ofSeconds(30)))
)
);
}
)
.then(this.patchSchedules.commitAndGetAllAsync())
.then(this.firewallRules.commitAndGetAllAsync())
.then(Mono.just(this));
} | return this.manager().inner().getRedis().getByResourceGroupAsync(resourceGroupName(), name()) | public Mono<RedisCache> updateResourceAsync() {
updateParameters.withTags(this.inner().tags());
this.patchScheduleAdded = false;
return this
.manager()
.inner()
.getRedis()
.updateAsync(resourceGroupName(), name(), updateParameters)
.map(innerToFluentMap(this))
.filter(
redisCache -> !redisCache.provisioningState().equalsIgnoreCase(ProvisioningState.SUCCEEDED.toString()))
.flatMapMany(
redisCache ->
Mono
.delay(SdkContext.getDelayDuration(Duration.ofSeconds(30)))
.flatMap(o -> manager().inner().getRedis().getByResourceGroupAsync(resourceGroupName(), name()))
.doOnNext(this::setInner)
.repeat()
.takeUntil(
redisResourceInner ->
redisResourceInner
.provisioningState()
.toString()
.equalsIgnoreCase(ProvisioningState.SUCCEEDED.toString())))
.then(this.patchSchedules.commitAndGetAllAsync())
.then(this.firewallRules.commitAndGetAllAsync())
.then(Mono.just(this));
} | class RedisCacheImpl
extends GroupableResourceImpl<
RedisCache,
RedisResourceInner,
RedisCacheImpl,
RedisManager>
implements
RedisCache,
RedisCachePremium,
RedisCache.Definition,
RedisCache.Update {
private RedisAccessKeys cachedAccessKeys;
private RedisCreateParameters createParameters;
private RedisUpdateParameters updateParameters;
private RedisPatchSchedulesImpl patchSchedules;
private RedisFirewallRulesImpl firewallRules;
private boolean patchScheduleAdded;
RedisCacheImpl(String name,
RedisResourceInner innerModel,
final RedisManager redisManager) {
super(name, innerModel, redisManager);
this.createParameters = new RedisCreateParameters();
this.patchSchedules = new RedisPatchSchedulesImpl(this);
this.firewallRules = new RedisFirewallRulesImpl(this);
this.patchSchedules.enablePostRunMode();
this.firewallRules.enablePostRunMode();
this.patchScheduleAdded = false;
}
@Override
public Map<String, RedisFirewallRule> firewallRules() {
return this.firewallRules.rulesAsMap();
}
@Override
public List<ScheduleEntry> patchSchedules() {
List<ScheduleEntry> patchSchedules = listPatchSchedules();
if (patchSchedules == null) {
return new ArrayList<>();
}
return patchSchedules;
}
@Override
public List<ScheduleEntry> listPatchSchedules() {
RedisPatchScheduleImpl patchSchedule = this.patchSchedules.getPatchSchedule();
if (patchSchedule == null) {
return null;
}
return patchSchedule.scheduleEntries();
}
@Override
public String provisioningState() {
return this.inner().provisioningState().toString();
}
@Override
public String hostname() {
return this.inner().hostname();
}
@Override
public int port() {
return Utils.toPrimitiveInt(this.inner().port());
}
@Override
public int sslPort() {
return Utils.toPrimitiveInt(this.inner().sslPort());
}
@Override
public String redisVersion() {
return this.inner().redisVersion();
}
@Override
public Sku sku() {
return this.inner().sku();
}
@Override
public boolean nonSslPort() {
return this.inner().enableNonSslPort();
}
@Override
public int shardCount() {
return Utils.toPrimitiveInt(this.inner().shardCount());
}
@Override
public String subnetId() {
return this.inner().subnetId();
}
@Override
public String staticIp() {
return this.inner().staticIp();
}
@Override
public TlsVersion minimumTlsVersion() {
return this.inner().minimumTlsVersion();
}
@Override
public Map<String, String> redisConfiguration() {
return Collections.unmodifiableMap(this.inner().redisConfiguration());
}
@Override
public RedisCachePremium asPremium() {
if (this.isPremium()) {
return this;
}
return null;
}
@Override
public boolean isPremium() {
return this.sku().name().equals(SkuName.PREMIUM);
}
@Override
public RedisAccessKeys keys() {
if (cachedAccessKeys == null) {
cachedAccessKeys = refreshKeys();
}
return cachedAccessKeys;
}
@Override
public RedisAccessKeys refreshKeys() {
RedisAccessKeysInner response =
this.manager().inner().getRedis().listKeys(this.resourceGroupName(), this.name());
cachedAccessKeys = new RedisAccessKeysImpl(response);
return cachedAccessKeys;
}
@Override
public RedisAccessKeys regenerateKey(RedisKeyType keyType) {
RedisAccessKeysInner response =
this.manager().inner().getRedis().regenerateKey(this.resourceGroupName(), this.name(), keyType);
cachedAccessKeys = new RedisAccessKeysImpl(response);
return cachedAccessKeys;
}
@Override
public void forceReboot(RebootType rebootType) {
RedisRebootParameters parameters = new RedisRebootParameters()
.withRebootType(rebootType);
this.manager().inner().getRedis().forceReboot(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void forceReboot(RebootType rebootType, int shardId) {
RedisRebootParameters parameters = new RedisRebootParameters()
.withRebootType(rebootType)
.withShardId(shardId);
this.manager().inner().getRedis().forceReboot(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void importData(List<String> files) {
ImportRdbParameters parameters = new ImportRdbParameters()
.withFiles(files);
this.manager().inner().getRedis().importData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void importData(List<String> files, String fileFormat) {
ImportRdbParameters parameters = new ImportRdbParameters()
.withFiles(files)
.withFormat(fileFormat);
this.manager().inner().getRedis().importData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void exportData(String containerSASUrl, String prefix) {
ExportRdbParameters parameters = new ExportRdbParameters()
.withContainer(containerSASUrl)
.withPrefix(prefix);
this.manager().inner().getRedis().exportData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void exportData(String containerSASUrl, String prefix, String fileFormat) {
ExportRdbParameters parameters = new ExportRdbParameters()
.withContainer(containerSASUrl)
.withPrefix(prefix)
.withFormat(fileFormat);
this.manager().inner().getRedis().exportData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public RedisCacheImpl withNonSslPort() {
if (isInCreateMode()) {
createParameters.withEnableNonSslPort(true);
} else {
updateParameters.withEnableNonSslPort(true);
}
return this;
}
@Override
public RedisCacheImpl withoutNonSslPort() {
if (!isInCreateMode()) {
updateParameters.withEnableNonSslPort(false);
}
return this;
}
@Override
public RedisCacheImpl withRedisConfiguration(Map<String, String> redisConfiguration) {
if (isInCreateMode()) {
createParameters.withRedisConfiguration(redisConfiguration);
} else {
updateParameters.withRedisConfiguration(redisConfiguration);
}
return this;
}
@Override
public RedisCacheImpl withRedisConfiguration(String key, String value) {
if (isInCreateMode()) {
if (createParameters.redisConfiguration() == null) {
createParameters.withRedisConfiguration(new TreeMap<>());
}
createParameters.redisConfiguration().put(key, value);
} else {
if (updateParameters.redisConfiguration() == null) {
updateParameters.withRedisConfiguration(new TreeMap<>());
}
updateParameters.redisConfiguration().put(key, value);
}
return this;
}
@Override
public RedisCacheImpl withFirewallRule(String name, String lowestIp, String highestIp) {
RedisFirewallRuleImpl rule = this.firewallRules.defineInlineFirewallRule(name);
rule.inner().withStartIp(lowestIp);
rule.inner().withEndIp(highestIp);
return this.withFirewallRule(rule);
}
@Override
public RedisCacheImpl withFirewallRule(RedisFirewallRule rule) {
this.firewallRules.addRule((RedisFirewallRuleImpl) rule);
return this;
}
@Override
public RedisCacheImpl withMinimumTlsVersion(TlsVersion tlsVersion) {
if (isInCreateMode()) {
createParameters.withMinimumTlsVersion(tlsVersion);
} else {
updateParameters.withMinimumTlsVersion(tlsVersion);
}
return this;
}
@Override
public RedisCacheImpl withoutMinimumTlsVersion() {
updateParameters.withMinimumTlsVersion(null);
return this;
}
@Override
public RedisCacheImpl withoutFirewallRule(String name) {
this.firewallRules.removeRule(name);
return this;
}
@Override
public RedisCacheImpl withoutRedisConfiguration() {
if (updateParameters.redisConfiguration() != null) {
updateParameters.redisConfiguration().clear();
}
return this;
}
@Override
public RedisCacheImpl withoutRedisConfiguration(String key) {
if (updateParameters.redisConfiguration() != null) {
updateParameters.redisConfiguration().remove(key);
}
return this;
}
@Override
public RedisCacheImpl withSubnet(HasId networkResource, String subnetName) {
if (networkResource != null) {
String subnetId = networkResource.id() + "/subnets/" + subnetName;
return withSubnet(subnetId);
} else {
createParameters.withSubnetId(null);
}
return this;
}
@Override
public RedisCacheImpl withSubnet(String subnetId) {
if (subnetId != null) {
if (isInCreateMode()) {
createParameters.withSubnetId(subnetId);
} else {
throw new UnsupportedOperationException("Subnet cannot be modified during update operation.");
}
}
return this;
}
@Override
public RedisCacheImpl withStaticIp(String staticIp) {
if (isInCreateMode()) {
createParameters.withStaticIp(staticIp);
} else {
throw new UnsupportedOperationException("Static IP cannot be modified during update operation.");
}
return this;
}
@Override
public RedisCacheImpl withBasicSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.BASIC)
.withFamily(SkuFamily.C));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.BASIC)
.withFamily(SkuFamily.C));
}
return this;
}
@Override
public RedisCacheImpl withBasicSku(int capacity) {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.BASIC)
.withFamily(SkuFamily.C)
.withCapacity(capacity));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.BASIC)
.withFamily(SkuFamily.C)
.withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withStandardSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.STANDARD)
.withFamily(SkuFamily.C));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.STANDARD)
.withFamily(SkuFamily.C));
}
return this;
}
@Override
public RedisCacheImpl withStandardSku(int capacity) {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.STANDARD)
.withFamily(SkuFamily.C)
.withCapacity(capacity));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.STANDARD)
.withFamily(SkuFamily.C)
.withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withPremiumSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.PREMIUM)
.withFamily(SkuFamily.P)
.withCapacity(1));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.PREMIUM)
.withFamily(SkuFamily.P)
.withCapacity(1));
}
return this;
}
@Override
public RedisCacheImpl withPremiumSku(int capacity) {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.PREMIUM)
.withFamily(SkuFamily.P)
.withCapacity(capacity));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.PREMIUM)
.withFamily(SkuFamily.P)
.withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withShardCount(int shardCount) {
if (isInCreateMode()) {
createParameters.withShardCount(shardCount);
} else {
updateParameters.withShardCount(shardCount);
}
return this;
}
@Override
public RedisCacheImpl withPatchSchedule(DayOfWeek dayOfWeek, int startHourUtc) {
return this.withPatchSchedule(new ScheduleEntry()
.withDayOfWeek(dayOfWeek)
.withStartHourUtc(startHourUtc));
}
@Override
public RedisCacheImpl withPatchSchedule(DayOfWeek dayOfWeek, int startHourUtc, Duration maintenanceWindow) {
return this.withPatchSchedule(new ScheduleEntry()
.withDayOfWeek(dayOfWeek)
.withStartHourUtc(startHourUtc)
.withMaintenanceWindow(maintenanceWindow));
}
@Override
public RedisCacheImpl withPatchSchedule(List<ScheduleEntry> scheduleEntries) {
this.patchSchedules.clear();
for (ScheduleEntry entry : scheduleEntries) {
this.withPatchSchedule(entry);
}
return this;
}
@Override
public RedisCacheImpl withPatchSchedule(ScheduleEntry scheduleEntry) {
RedisPatchScheduleImpl psch;
if (this.patchSchedules.patchSchedulesAsMap().isEmpty()) {
psch = this.patchSchedules.defineInlinePatchSchedule();
this.patchScheduleAdded = true;
psch.inner().withScheduleEntries(new ArrayList<>());
this.patchSchedules.addPatchSchedule(psch);
} else if (!this.patchScheduleAdded) {
psch = this.patchSchedules.updateInlinePatchSchedule();
} else {
psch = this.patchSchedules.getPatchSchedule();
}
psch.inner().scheduleEntries().add(scheduleEntry);
return this;
}
@Override
public RedisCacheImpl withoutPatchSchedule() {
if (this.patchSchedules.patchSchedulesAsMap().isEmpty()) {
return this;
} else {
this.patchSchedules.deleteInlinePatchSchedule();
}
return this;
}
@Override
public void deletePatchSchedule() {
this.patchSchedules.removePatchSchedule();
this.patchSchedules.refresh();
}
@Override
public Mono<RedisCache> refreshAsync() {
return super.refreshAsync()
.then(this.firewallRules.refreshAsync())
.then(this.patchSchedules.refreshAsync())
.then(Mono.just(this));
}
@Override
protected Mono<RedisResourceInner> getInnerAsync() {
return this.manager().inner().getRedis().getByResourceGroupAsync(this.resourceGroupName(), this.name());
}
@Override
public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) {
this.firewallRules.clear();
this.patchSchedules.clear();
this.patchScheduleAdded = false;
if (isGroupFaulted) {
return Mono.empty();
} else {
return this.refreshAsync().then();
}
}
@Override
public RedisCacheImpl update() {
this.updateParameters = new RedisUpdateParameters();
this.patchSchedules.enableCommitMode();
this.firewallRules.enableCommitMode();
return super.update();
}
@Override
@Override
public Mono<RedisCache> createResourceAsync() {
createParameters.withLocation(this.regionName());
createParameters.withTags(this.inner().tags());
this.patchScheduleAdded = false;
return this.manager().inner().getRedis().createAsync(this.resourceGroupName(), this.name(), createParameters)
.map(innerToFluentMap(this));
}
@Override
public String addLinkedServer(String linkedRedisCacheId, String linkedServerLocation, ReplicationRole role) {
String linkedRedisName = ResourceUtils.nameFromResourceId(linkedRedisCacheId);
RedisLinkedServerCreateParameters params = new RedisLinkedServerCreateParameters()
.withLinkedRedisCacheId(linkedRedisCacheId)
.withLinkedRedisCacheLocation(linkedServerLocation)
.withServerRole(role);
RedisLinkedServerWithPropertiesInner linkedServerInner = this.manager().inner().getLinkedServers().create(
this.resourceGroupName(),
this.name(),
linkedRedisName,
params);
return linkedServerInner.name();
}
@Override
public void removeLinkedServer(String linkedServerName) {
RedisLinkedServerWithPropertiesInner linkedServer = this.manager().inner().getLinkedServers().get(this.resourceGroupName(), this.name(), linkedServerName);
this.manager().inner().getLinkedServers().delete(
this.resourceGroupName(),
this.name(),
linkedServerName);
RedisResourceInner innerLinkedResource = null;
RedisResourceInner innerResource = null;
while (innerLinkedResource == null
|| innerLinkedResource.provisioningState() != ProvisioningState.SUCCEEDED
|| innerResource == null
|| innerResource.provisioningState() != ProvisioningState.SUCCEEDED) {
SdkContext.sleep(30 * 1000);
innerLinkedResource = this.manager().inner().getRedis().getByResourceGroup(
ResourceUtils.groupFromResourceId(linkedServer.id()),
ResourceUtils.nameFromResourceId(linkedServer.id()));
innerResource = this.manager().inner().getRedis().getByResourceGroup(resourceGroupName(), name());
}
}
@Override
public ReplicationRole getLinkedServerRole(String linkedServerName) {
RedisLinkedServerWithPropertiesInner linkedServer = this.manager().inner().getLinkedServers().get(
this.resourceGroupName(),
this.name(),
linkedServerName);
if (linkedServer == null) {
throw new IllegalArgumentException("Server returned `null` value for Linked Server '"
+ linkedServerName + "' for Redis Cache '" + this.name()
+ "' in Resource Group '" + this.resourceGroupName() + "'.");
}
return linkedServer.serverRole();
}
@Override
public Map<String, ReplicationRole> listLinkedServers() {
Map<String, ReplicationRole> result = new TreeMap<>();
PagedIterable<RedisLinkedServerWithPropertiesInner> paginatedResponse = this.manager().inner().getLinkedServers().list(
this.resourceGroupName(),
this.name());
for (RedisLinkedServerWithPropertiesInner linkedServer : paginatedResponse) {
result.put(linkedServer.name(), linkedServer.serverRole());
}
return result;
}
} | class RedisCacheImpl extends GroupableResourceImpl<RedisCache, RedisResourceInner, RedisCacheImpl, RedisManager>
implements RedisCache, RedisCachePremium, RedisCache.Definition, RedisCache.Update {
private final ClientLogger logger = new ClientLogger(getClass());
private RedisAccessKeys cachedAccessKeys;
private RedisCreateParameters createParameters;
private RedisUpdateParameters updateParameters;
private RedisPatchSchedulesImpl patchSchedules;
private RedisFirewallRulesImpl firewallRules;
private boolean patchScheduleAdded;
RedisCacheImpl(String name, RedisResourceInner innerModel, final RedisManager redisManager) {
super(name, innerModel, redisManager);
this.createParameters = new RedisCreateParameters();
this.patchSchedules = new RedisPatchSchedulesImpl(this);
this.firewallRules = new RedisFirewallRulesImpl(this);
this.patchSchedules.enablePostRunMode();
this.firewallRules.enablePostRunMode();
this.patchScheduleAdded = false;
}
@Override
public Map<String, RedisFirewallRule> firewallRules() {
return this.firewallRules.rulesAsMap();
}
@Override
public List<ScheduleEntry> patchSchedules() {
List<ScheduleEntry> patchSchedules = listPatchSchedules();
if (patchSchedules == null) {
return new ArrayList<>();
}
return patchSchedules;
}
@Override
public List<ScheduleEntry> listPatchSchedules() {
RedisPatchScheduleImpl patchSchedule = this.patchSchedules.getPatchSchedule();
if (patchSchedule == null) {
return null;
}
return patchSchedule.scheduleEntries();
}
@Override
public String provisioningState() {
return this.inner().provisioningState().toString();
}
@Override
public String hostname() {
return this.inner().hostname();
}
@Override
public int port() {
return Utils.toPrimitiveInt(this.inner().port());
}
@Override
public int sslPort() {
return Utils.toPrimitiveInt(this.inner().sslPort());
}
@Override
public String redisVersion() {
return this.inner().redisVersion();
}
@Override
public Sku sku() {
return this.inner().sku();
}
@Override
public boolean nonSslPort() {
return this.inner().enableNonSslPort();
}
@Override
public int shardCount() {
return Utils.toPrimitiveInt(this.inner().shardCount());
}
@Override
public String subnetId() {
return this.inner().subnetId();
}
@Override
public String staticIp() {
return this.inner().staticIp();
}
@Override
public TlsVersion minimumTlsVersion() {
return this.inner().minimumTlsVersion();
}
@Override
public Map<String, String> redisConfiguration() {
return Collections.unmodifiableMap(this.inner().redisConfiguration());
}
@Override
public RedisCachePremium asPremium() {
if (this.isPremium()) {
return this;
}
return null;
}
@Override
public boolean isPremium() {
return this.sku().name().equals(SkuName.PREMIUM);
}
@Override
public RedisAccessKeys keys() {
if (cachedAccessKeys == null) {
cachedAccessKeys = refreshKeys();
}
return cachedAccessKeys;
}
@Override
public RedisAccessKeys refreshKeys() {
RedisAccessKeysInner response =
this.manager().inner().getRedis().listKeys(this.resourceGroupName(), this.name());
cachedAccessKeys = new RedisAccessKeysImpl(response);
return cachedAccessKeys;
}
@Override
public RedisAccessKeys regenerateKey(RedisKeyType keyType) {
RedisAccessKeysInner response =
this.manager().inner().getRedis().regenerateKey(this.resourceGroupName(), this.name(), keyType);
cachedAccessKeys = new RedisAccessKeysImpl(response);
return cachedAccessKeys;
}
@Override
public void forceReboot(RebootType rebootType) {
RedisRebootParameters parameters = new RedisRebootParameters().withRebootType(rebootType);
this.manager().inner().getRedis().forceReboot(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void forceReboot(RebootType rebootType, int shardId) {
RedisRebootParameters parameters = new RedisRebootParameters().withRebootType(rebootType).withShardId(shardId);
this.manager().inner().getRedis().forceReboot(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void importData(List<String> files) {
ImportRdbParameters parameters = new ImportRdbParameters().withFiles(files);
this.manager().inner().getRedis().importData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void importData(List<String> files, String fileFormat) {
ImportRdbParameters parameters = new ImportRdbParameters().withFiles(files).withFormat(fileFormat);
this.manager().inner().getRedis().importData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void exportData(String containerSASUrl, String prefix) {
ExportRdbParameters parameters = new ExportRdbParameters().withContainer(containerSASUrl).withPrefix(prefix);
this.manager().inner().getRedis().exportData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void exportData(String containerSASUrl, String prefix, String fileFormat) {
ExportRdbParameters parameters =
new ExportRdbParameters().withContainer(containerSASUrl).withPrefix(prefix).withFormat(fileFormat);
this.manager().inner().getRedis().exportData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public RedisCacheImpl withNonSslPort() {
if (isInCreateMode()) {
createParameters.withEnableNonSslPort(true);
} else {
updateParameters.withEnableNonSslPort(true);
}
return this;
}
@Override
public RedisCacheImpl withoutNonSslPort() {
if (!isInCreateMode()) {
updateParameters.withEnableNonSslPort(false);
}
return this;
}
@Override
public RedisCacheImpl withRedisConfiguration(Map<String, String> redisConfiguration) {
if (isInCreateMode()) {
createParameters.withRedisConfiguration(redisConfiguration);
} else {
updateParameters.withRedisConfiguration(redisConfiguration);
}
return this;
}
@Override
public RedisCacheImpl withRedisConfiguration(String key, String value) {
if (isInCreateMode()) {
if (createParameters.redisConfiguration() == null) {
createParameters.withRedisConfiguration(new TreeMap<>());
}
createParameters.redisConfiguration().put(key, value);
} else {
if (updateParameters.redisConfiguration() == null) {
updateParameters.withRedisConfiguration(new TreeMap<>());
}
updateParameters.redisConfiguration().put(key, value);
}
return this;
}
@Override
public RedisCacheImpl withFirewallRule(String name, String lowestIp, String highestIp) {
RedisFirewallRuleImpl rule = this.firewallRules.defineInlineFirewallRule(name);
rule.inner().withStartIp(lowestIp);
rule.inner().withEndIp(highestIp);
return this.withFirewallRule(rule);
}
@Override
public RedisCacheImpl withFirewallRule(RedisFirewallRule rule) {
this.firewallRules.addRule((RedisFirewallRuleImpl) rule);
return this;
}
@Override
public RedisCacheImpl withMinimumTlsVersion(TlsVersion tlsVersion) {
if (isInCreateMode()) {
createParameters.withMinimumTlsVersion(tlsVersion);
} else {
updateParameters.withMinimumTlsVersion(tlsVersion);
}
return this;
}
@Override
public RedisCacheImpl withoutMinimumTlsVersion() {
updateParameters.withMinimumTlsVersion(null);
return this;
}
@Override
public RedisCacheImpl withoutFirewallRule(String name) {
this.firewallRules.removeRule(name);
return this;
}
@Override
public RedisCacheImpl withoutRedisConfiguration() {
if (updateParameters.redisConfiguration() != null) {
updateParameters.redisConfiguration().clear();
}
return this;
}
@Override
public RedisCacheImpl withoutRedisConfiguration(String key) {
if (updateParameters.redisConfiguration() != null) {
updateParameters.redisConfiguration().remove(key);
}
return this;
}
@Override
public RedisCacheImpl withSubnet(HasId networkResource, String subnetName) {
if (networkResource != null) {
String subnetId = networkResource.id() + "/subnets/" + subnetName;
return withSubnet(subnetId);
} else {
createParameters.withSubnetId(null);
}
return this;
}
@Override
public RedisCacheImpl withSubnet(String subnetId) {
if (subnetId != null) {
if (isInCreateMode()) {
createParameters.withSubnetId(subnetId);
} else {
throw logger
.logExceptionAsError(
new UnsupportedOperationException("Subnet cannot be modified during update operation."));
}
}
return this;
}
@Override
public RedisCacheImpl withStaticIp(String staticIp) {
if (isInCreateMode()) {
createParameters.withStaticIp(staticIp);
} else {
throw logger
.logExceptionAsError(
new UnsupportedOperationException("Static IP cannot be modified during update operation."));
}
return this;
}
@Override
public RedisCacheImpl withBasicSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku().withName(SkuName.BASIC).withFamily(SkuFamily.C));
} else {
updateParameters.withSku(new Sku().withName(SkuName.BASIC).withFamily(SkuFamily.C));
}
return this;
}
@Override
public RedisCacheImpl withBasicSku(int capacity) {
if (isInCreateMode()) {
createParameters.withSku(new Sku().withName(SkuName.BASIC).withFamily(SkuFamily.C).withCapacity(capacity));
} else {
updateParameters.withSku(new Sku().withName(SkuName.BASIC).withFamily(SkuFamily.C).withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withStandardSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku().withName(SkuName.STANDARD).withFamily(SkuFamily.C));
} else {
updateParameters.withSku(new Sku().withName(SkuName.STANDARD).withFamily(SkuFamily.C));
}
return this;
}
@Override
public RedisCacheImpl withStandardSku(int capacity) {
if (isInCreateMode()) {
createParameters
.withSku(new Sku().withName(SkuName.STANDARD).withFamily(SkuFamily.C).withCapacity(capacity));
} else {
updateParameters
.withSku(new Sku().withName(SkuName.STANDARD).withFamily(SkuFamily.C).withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withPremiumSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku().withName(SkuName.PREMIUM).withFamily(SkuFamily.P).withCapacity(1));
} else {
updateParameters.withSku(new Sku().withName(SkuName.PREMIUM).withFamily(SkuFamily.P).withCapacity(1));
}
return this;
}
@Override
public RedisCacheImpl withPremiumSku(int capacity) {
if (isInCreateMode()) {
createParameters
.withSku(new Sku().withName(SkuName.PREMIUM).withFamily(SkuFamily.P).withCapacity(capacity));
} else {
updateParameters
.withSku(new Sku().withName(SkuName.PREMIUM).withFamily(SkuFamily.P).withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withShardCount(int shardCount) {
if (isInCreateMode()) {
createParameters.withShardCount(shardCount);
} else {
updateParameters.withShardCount(shardCount);
}
return this;
}
@Override
public RedisCacheImpl withPatchSchedule(DayOfWeek dayOfWeek, int startHourUtc) {
return this.withPatchSchedule(new ScheduleEntry().withDayOfWeek(dayOfWeek).withStartHourUtc(startHourUtc));
}
@Override
public RedisCacheImpl withPatchSchedule(DayOfWeek dayOfWeek, int startHourUtc, Duration maintenanceWindow) {
return this
.withPatchSchedule(
new ScheduleEntry()
.withDayOfWeek(dayOfWeek)
.withStartHourUtc(startHourUtc)
.withMaintenanceWindow(maintenanceWindow));
}
@Override
public RedisCacheImpl withPatchSchedule(List<ScheduleEntry> scheduleEntries) {
this.patchSchedules.clear();
for (ScheduleEntry entry : scheduleEntries) {
this.withPatchSchedule(entry);
}
return this;
}
@Override
public RedisCacheImpl withPatchSchedule(ScheduleEntry scheduleEntry) {
RedisPatchScheduleImpl psch;
if (this.patchSchedules.patchSchedulesAsMap().isEmpty()) {
psch = this.patchSchedules.defineInlinePatchSchedule();
this.patchScheduleAdded = true;
psch.inner().withScheduleEntries(new ArrayList<>());
this.patchSchedules.addPatchSchedule(psch);
} else if (!this.patchScheduleAdded) {
psch = this.patchSchedules.updateInlinePatchSchedule();
} else {
psch = this.patchSchedules.getPatchSchedule();
}
psch.inner().scheduleEntries().add(scheduleEntry);
return this;
}
@Override
public RedisCacheImpl withoutPatchSchedule() {
if (this.patchSchedules.patchSchedulesAsMap().isEmpty()) {
return this;
} else {
this.patchSchedules.deleteInlinePatchSchedule();
}
return this;
}
@Override
public void deletePatchSchedule() {
this.patchSchedules.removePatchSchedule();
this.patchSchedules.refresh();
}
@Override
public Mono<RedisCache> refreshAsync() {
return super
.refreshAsync()
.then(this.firewallRules.refreshAsync())
.then(this.patchSchedules.refreshAsync())
.then(Mono.just(this));
}
@Override
protected Mono<RedisResourceInner> getInnerAsync() {
return this.manager().inner().getRedis().getByResourceGroupAsync(this.resourceGroupName(), this.name());
}
@Override
public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) {
this.firewallRules.clear();
this.patchSchedules.clear();
this.patchScheduleAdded = false;
if (isGroupFaulted) {
return Mono.empty();
} else {
return this.refreshAsync().then();
}
}
@Override
public RedisCacheImpl update() {
this.updateParameters = new RedisUpdateParameters();
this.patchSchedules.enableCommitMode();
this.firewallRules.enableCommitMode();
return super.update();
}
@Override
@Override
public Mono<RedisCache> createResourceAsync() {
createParameters.withLocation(this.regionName());
createParameters.withTags(this.inner().tags());
this.patchScheduleAdded = false;
return this
.manager()
.inner()
.getRedis()
.createAsync(this.resourceGroupName(), this.name(), createParameters)
.map(innerToFluentMap(this));
}
@Override
public String addLinkedServer(String linkedRedisCacheId, String linkedServerLocation, ReplicationRole role) {
String linkedRedisName = ResourceUtils.nameFromResourceId(linkedRedisCacheId);
RedisLinkedServerCreateParameters params =
new RedisLinkedServerCreateParameters()
.withLinkedRedisCacheId(linkedRedisCacheId)
.withLinkedRedisCacheLocation(linkedServerLocation)
.withServerRole(role);
RedisLinkedServerWithPropertiesInner linkedServerInner =
this
.manager()
.inner()
.getLinkedServers()
.create(this.resourceGroupName(), this.name(), linkedRedisName, params);
return linkedServerInner.name();
}
@Override
public void removeLinkedServer(String linkedServerName) {
RedisLinkedServerWithPropertiesInner linkedServer =
this.manager().inner().getLinkedServers().get(this.resourceGroupName(), this.name(), linkedServerName);
this.manager().inner().getLinkedServers().delete(this.resourceGroupName(), this.name(), linkedServerName);
RedisResourceInner innerLinkedResource = null;
RedisResourceInner innerResource = null;
while (innerLinkedResource == null
|| innerLinkedResource.provisioningState() != ProvisioningState.SUCCEEDED
|| innerResource == null
|| innerResource.provisioningState() != ProvisioningState.SUCCEEDED) {
SdkContext.sleep(30 * 1000);
innerLinkedResource =
this
.manager()
.inner()
.getRedis()
.getByResourceGroup(
ResourceUtils.groupFromResourceId(linkedServer.id()),
ResourceUtils.nameFromResourceId(linkedServer.id()));
innerResource = this.manager().inner().getRedis().getByResourceGroup(resourceGroupName(), name());
}
}
@Override
public ReplicationRole getLinkedServerRole(String linkedServerName) {
RedisLinkedServerWithPropertiesInner linkedServer =
this.manager().inner().getLinkedServers().get(this.resourceGroupName(), this.name(), linkedServerName);
if (linkedServer == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"Server returned `null` value for Linked Server '"
+ linkedServerName
+ "' for Redis Cache '"
+ this.name()
+ "' in Resource Group '"
+ this.resourceGroupName()
+ "'."));
}
return linkedServer.serverRole();
}
@Override
public Map<String, ReplicationRole> listLinkedServers() {
Map<String, ReplicationRole> result = new TreeMap<>();
PagedIterable<RedisLinkedServerWithPropertiesInner> paginatedResponse =
this.manager().inner().getLinkedServers().list(this.resourceGroupName(), this.name());
for (RedisLinkedServerWithPropertiesInner linkedServer : paginatedResponse) {
result.put(linkedServer.name(), linkedServer.serverRole());
}
return result;
}
} |
Should we use `delaySubscription` + `repeat`? https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/PollerFlux.java#L214-L238 | public Mono<RedisCache> updateResourceAsync() {
updateParameters.withTags(this.inner().tags());
return this.manager().inner().getRedis().updateAsync(resourceGroupName(), name(), updateParameters)
.map(innerToFluentMap(this))
.filter(redisCache -> !redisCache.provisioningState().equalsIgnoreCase(ProvisioningState.SUCCEEDED.toString()))
.flatMap(redisCache -> {
SdkContext.sleep(30 * 1000);
this.patchScheduleAdded = false;
return this.manager().inner().getRedis().getByResourceGroupAsync(resourceGroupName(), name())
.doOnNext( this::setInner)
.filter(redisResourceInner -> redisResourceInner.provisioningState().toString()
.equalsIgnoreCase(ProvisioningState.SUCCEEDED.toString()))
.repeatWhenEmpty(
longFlux -> longFlux.flatMap(
index -> Mono.delay(SdkContext.getDelayDuration(Duration.ofSeconds(30)))
)
);
}
)
.then(this.patchSchedules.commitAndGetAllAsync())
.then(this.firewallRules.commitAndGetAllAsync())
.then(Mono.just(this));
} | SdkContext.sleep(30 * 1000); | public Mono<RedisCache> updateResourceAsync() {
updateParameters.withTags(this.inner().tags());
this.patchScheduleAdded = false;
return this
.manager()
.inner()
.getRedis()
.updateAsync(resourceGroupName(), name(), updateParameters)
.map(innerToFluentMap(this))
.filter(
redisCache -> !redisCache.provisioningState().equalsIgnoreCase(ProvisioningState.SUCCEEDED.toString()))
.flatMapMany(
redisCache ->
Mono
.delay(SdkContext.getDelayDuration(Duration.ofSeconds(30)))
.flatMap(o -> manager().inner().getRedis().getByResourceGroupAsync(resourceGroupName(), name()))
.doOnNext(this::setInner)
.repeat()
.takeUntil(
redisResourceInner ->
redisResourceInner
.provisioningState()
.toString()
.equalsIgnoreCase(ProvisioningState.SUCCEEDED.toString())))
.then(this.patchSchedules.commitAndGetAllAsync())
.then(this.firewallRules.commitAndGetAllAsync())
.then(Mono.just(this));
} | class RedisCacheImpl
extends GroupableResourceImpl<
RedisCache,
RedisResourceInner,
RedisCacheImpl,
RedisManager>
implements
RedisCache,
RedisCachePremium,
RedisCache.Definition,
RedisCache.Update {
private RedisAccessKeys cachedAccessKeys;
private RedisCreateParameters createParameters;
private RedisUpdateParameters updateParameters;
private RedisPatchSchedulesImpl patchSchedules;
private RedisFirewallRulesImpl firewallRules;
private boolean patchScheduleAdded;
RedisCacheImpl(String name,
RedisResourceInner innerModel,
final RedisManager redisManager) {
super(name, innerModel, redisManager);
this.createParameters = new RedisCreateParameters();
this.patchSchedules = new RedisPatchSchedulesImpl(this);
this.firewallRules = new RedisFirewallRulesImpl(this);
this.patchSchedules.enablePostRunMode();
this.firewallRules.enablePostRunMode();
this.patchScheduleAdded = false;
}
@Override
public Map<String, RedisFirewallRule> firewallRules() {
return this.firewallRules.rulesAsMap();
}
@Override
public List<ScheduleEntry> patchSchedules() {
List<ScheduleEntry> patchSchedules = listPatchSchedules();
if (patchSchedules == null) {
return new ArrayList<>();
}
return patchSchedules;
}
@Override
public List<ScheduleEntry> listPatchSchedules() {
RedisPatchScheduleImpl patchSchedule = this.patchSchedules.getPatchSchedule();
if (patchSchedule == null) {
return null;
}
return patchSchedule.scheduleEntries();
}
@Override
public String provisioningState() {
return this.inner().provisioningState().toString();
}
@Override
public String hostname() {
return this.inner().hostname();
}
@Override
public int port() {
return Utils.toPrimitiveInt(this.inner().port());
}
@Override
public int sslPort() {
return Utils.toPrimitiveInt(this.inner().sslPort());
}
@Override
public String redisVersion() {
return this.inner().redisVersion();
}
@Override
public Sku sku() {
return this.inner().sku();
}
@Override
public boolean nonSslPort() {
return this.inner().enableNonSslPort();
}
@Override
public int shardCount() {
return Utils.toPrimitiveInt(this.inner().shardCount());
}
@Override
public String subnetId() {
return this.inner().subnetId();
}
@Override
public String staticIp() {
return this.inner().staticIp();
}
@Override
public TlsVersion minimumTlsVersion() {
return this.inner().minimumTlsVersion();
}
@Override
public Map<String, String> redisConfiguration() {
return Collections.unmodifiableMap(this.inner().redisConfiguration());
}
@Override
public RedisCachePremium asPremium() {
if (this.isPremium()) {
return this;
}
return null;
}
@Override
public boolean isPremium() {
return this.sku().name().equals(SkuName.PREMIUM);
}
@Override
public RedisAccessKeys keys() {
if (cachedAccessKeys == null) {
cachedAccessKeys = refreshKeys();
}
return cachedAccessKeys;
}
@Override
public RedisAccessKeys refreshKeys() {
RedisAccessKeysInner response =
this.manager().inner().getRedis().listKeys(this.resourceGroupName(), this.name());
cachedAccessKeys = new RedisAccessKeysImpl(response);
return cachedAccessKeys;
}
@Override
public RedisAccessKeys regenerateKey(RedisKeyType keyType) {
RedisAccessKeysInner response =
this.manager().inner().getRedis().regenerateKey(this.resourceGroupName(), this.name(), keyType);
cachedAccessKeys = new RedisAccessKeysImpl(response);
return cachedAccessKeys;
}
@Override
public void forceReboot(RebootType rebootType) {
RedisRebootParameters parameters = new RedisRebootParameters()
.withRebootType(rebootType);
this.manager().inner().getRedis().forceReboot(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void forceReboot(RebootType rebootType, int shardId) {
RedisRebootParameters parameters = new RedisRebootParameters()
.withRebootType(rebootType)
.withShardId(shardId);
this.manager().inner().getRedis().forceReboot(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void importData(List<String> files) {
ImportRdbParameters parameters = new ImportRdbParameters()
.withFiles(files);
this.manager().inner().getRedis().importData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void importData(List<String> files, String fileFormat) {
ImportRdbParameters parameters = new ImportRdbParameters()
.withFiles(files)
.withFormat(fileFormat);
this.manager().inner().getRedis().importData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void exportData(String containerSASUrl, String prefix) {
ExportRdbParameters parameters = new ExportRdbParameters()
.withContainer(containerSASUrl)
.withPrefix(prefix);
this.manager().inner().getRedis().exportData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void exportData(String containerSASUrl, String prefix, String fileFormat) {
ExportRdbParameters parameters = new ExportRdbParameters()
.withContainer(containerSASUrl)
.withPrefix(prefix)
.withFormat(fileFormat);
this.manager().inner().getRedis().exportData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public RedisCacheImpl withNonSslPort() {
if (isInCreateMode()) {
createParameters.withEnableNonSslPort(true);
} else {
updateParameters.withEnableNonSslPort(true);
}
return this;
}
@Override
public RedisCacheImpl withoutNonSslPort() {
if (!isInCreateMode()) {
updateParameters.withEnableNonSslPort(false);
}
return this;
}
@Override
public RedisCacheImpl withRedisConfiguration(Map<String, String> redisConfiguration) {
if (isInCreateMode()) {
createParameters.withRedisConfiguration(redisConfiguration);
} else {
updateParameters.withRedisConfiguration(redisConfiguration);
}
return this;
}
@Override
public RedisCacheImpl withRedisConfiguration(String key, String value) {
if (isInCreateMode()) {
if (createParameters.redisConfiguration() == null) {
createParameters.withRedisConfiguration(new TreeMap<>());
}
createParameters.redisConfiguration().put(key, value);
} else {
if (updateParameters.redisConfiguration() == null) {
updateParameters.withRedisConfiguration(new TreeMap<>());
}
updateParameters.redisConfiguration().put(key, value);
}
return this;
}
@Override
public RedisCacheImpl withFirewallRule(String name, String lowestIp, String highestIp) {
RedisFirewallRuleImpl rule = this.firewallRules.defineInlineFirewallRule(name);
rule.inner().withStartIp(lowestIp);
rule.inner().withEndIp(highestIp);
return this.withFirewallRule(rule);
}
@Override
public RedisCacheImpl withFirewallRule(RedisFirewallRule rule) {
this.firewallRules.addRule((RedisFirewallRuleImpl) rule);
return this;
}
@Override
public RedisCacheImpl withMinimumTlsVersion(TlsVersion tlsVersion) {
if (isInCreateMode()) {
createParameters.withMinimumTlsVersion(tlsVersion);
} else {
updateParameters.withMinimumTlsVersion(tlsVersion);
}
return this;
}
@Override
public RedisCacheImpl withoutMinimumTlsVersion() {
updateParameters.withMinimumTlsVersion(null);
return this;
}
@Override
public RedisCacheImpl withoutFirewallRule(String name) {
this.firewallRules.removeRule(name);
return this;
}
@Override
public RedisCacheImpl withoutRedisConfiguration() {
if (updateParameters.redisConfiguration() != null) {
updateParameters.redisConfiguration().clear();
}
return this;
}
@Override
public RedisCacheImpl withoutRedisConfiguration(String key) {
if (updateParameters.redisConfiguration() != null) {
updateParameters.redisConfiguration().remove(key);
}
return this;
}
@Override
public RedisCacheImpl withSubnet(HasId networkResource, String subnetName) {
if (networkResource != null) {
String subnetId = networkResource.id() + "/subnets/" + subnetName;
return withSubnet(subnetId);
} else {
createParameters.withSubnetId(null);
}
return this;
}
@Override
public RedisCacheImpl withSubnet(String subnetId) {
if (subnetId != null) {
if (isInCreateMode()) {
createParameters.withSubnetId(subnetId);
} else {
throw new UnsupportedOperationException("Subnet cannot be modified during update operation.");
}
}
return this;
}
@Override
public RedisCacheImpl withStaticIp(String staticIp) {
if (isInCreateMode()) {
createParameters.withStaticIp(staticIp);
} else {
throw new UnsupportedOperationException("Static IP cannot be modified during update operation.");
}
return this;
}
@Override
public RedisCacheImpl withBasicSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.BASIC)
.withFamily(SkuFamily.C));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.BASIC)
.withFamily(SkuFamily.C));
}
return this;
}
@Override
public RedisCacheImpl withBasicSku(int capacity) {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.BASIC)
.withFamily(SkuFamily.C)
.withCapacity(capacity));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.BASIC)
.withFamily(SkuFamily.C)
.withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withStandardSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.STANDARD)
.withFamily(SkuFamily.C));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.STANDARD)
.withFamily(SkuFamily.C));
}
return this;
}
@Override
public RedisCacheImpl withStandardSku(int capacity) {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.STANDARD)
.withFamily(SkuFamily.C)
.withCapacity(capacity));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.STANDARD)
.withFamily(SkuFamily.C)
.withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withPremiumSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.PREMIUM)
.withFamily(SkuFamily.P)
.withCapacity(1));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.PREMIUM)
.withFamily(SkuFamily.P)
.withCapacity(1));
}
return this;
}
@Override
public RedisCacheImpl withPremiumSku(int capacity) {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.PREMIUM)
.withFamily(SkuFamily.P)
.withCapacity(capacity));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.PREMIUM)
.withFamily(SkuFamily.P)
.withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withShardCount(int shardCount) {
if (isInCreateMode()) {
createParameters.withShardCount(shardCount);
} else {
updateParameters.withShardCount(shardCount);
}
return this;
}
@Override
public RedisCacheImpl withPatchSchedule(DayOfWeek dayOfWeek, int startHourUtc) {
return this.withPatchSchedule(new ScheduleEntry()
.withDayOfWeek(dayOfWeek)
.withStartHourUtc(startHourUtc));
}
@Override
public RedisCacheImpl withPatchSchedule(DayOfWeek dayOfWeek, int startHourUtc, Duration maintenanceWindow) {
return this.withPatchSchedule(new ScheduleEntry()
.withDayOfWeek(dayOfWeek)
.withStartHourUtc(startHourUtc)
.withMaintenanceWindow(maintenanceWindow));
}
@Override
public RedisCacheImpl withPatchSchedule(List<ScheduleEntry> scheduleEntries) {
this.patchSchedules.clear();
for (ScheduleEntry entry : scheduleEntries) {
this.withPatchSchedule(entry);
}
return this;
}
@Override
public RedisCacheImpl withPatchSchedule(ScheduleEntry scheduleEntry) {
RedisPatchScheduleImpl psch;
if (this.patchSchedules.patchSchedulesAsMap().isEmpty()) {
psch = this.patchSchedules.defineInlinePatchSchedule();
this.patchScheduleAdded = true;
psch.inner().withScheduleEntries(new ArrayList<>());
this.patchSchedules.addPatchSchedule(psch);
} else if (!this.patchScheduleAdded) {
psch = this.patchSchedules.updateInlinePatchSchedule();
} else {
psch = this.patchSchedules.getPatchSchedule();
}
psch.inner().scheduleEntries().add(scheduleEntry);
return this;
}
@Override
public RedisCacheImpl withoutPatchSchedule() {
if (this.patchSchedules.patchSchedulesAsMap().isEmpty()) {
return this;
} else {
this.patchSchedules.deleteInlinePatchSchedule();
}
return this;
}
@Override
public void deletePatchSchedule() {
this.patchSchedules.removePatchSchedule();
this.patchSchedules.refresh();
}
@Override
public Mono<RedisCache> refreshAsync() {
return super.refreshAsync()
.then(this.firewallRules.refreshAsync())
.then(this.patchSchedules.refreshAsync())
.then(Mono.just(this));
}
@Override
protected Mono<RedisResourceInner> getInnerAsync() {
return this.manager().inner().getRedis().getByResourceGroupAsync(this.resourceGroupName(), this.name());
}
@Override
public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) {
this.firewallRules.clear();
this.patchSchedules.clear();
this.patchScheduleAdded = false;
if (isGroupFaulted) {
return Mono.empty();
} else {
return this.refreshAsync().then();
}
}
@Override
public RedisCacheImpl update() {
this.updateParameters = new RedisUpdateParameters();
this.patchSchedules.enableCommitMode();
this.firewallRules.enableCommitMode();
return super.update();
}
@Override
@Override
public Mono<RedisCache> createResourceAsync() {
createParameters.withLocation(this.regionName());
createParameters.withTags(this.inner().tags());
this.patchScheduleAdded = false;
return this.manager().inner().getRedis().createAsync(this.resourceGroupName(), this.name(), createParameters)
.map(innerToFluentMap(this));
}
@Override
public String addLinkedServer(String linkedRedisCacheId, String linkedServerLocation, ReplicationRole role) {
String linkedRedisName = ResourceUtils.nameFromResourceId(linkedRedisCacheId);
RedisLinkedServerCreateParameters params = new RedisLinkedServerCreateParameters()
.withLinkedRedisCacheId(linkedRedisCacheId)
.withLinkedRedisCacheLocation(linkedServerLocation)
.withServerRole(role);
RedisLinkedServerWithPropertiesInner linkedServerInner = this.manager().inner().getLinkedServers().create(
this.resourceGroupName(),
this.name(),
linkedRedisName,
params);
return linkedServerInner.name();
}
@Override
public void removeLinkedServer(String linkedServerName) {
RedisLinkedServerWithPropertiesInner linkedServer = this.manager().inner().getLinkedServers().get(this.resourceGroupName(), this.name(), linkedServerName);
this.manager().inner().getLinkedServers().delete(
this.resourceGroupName(),
this.name(),
linkedServerName);
RedisResourceInner innerLinkedResource = null;
RedisResourceInner innerResource = null;
while (innerLinkedResource == null
|| innerLinkedResource.provisioningState() != ProvisioningState.SUCCEEDED
|| innerResource == null
|| innerResource.provisioningState() != ProvisioningState.SUCCEEDED) {
SdkContext.sleep(30 * 1000);
innerLinkedResource = this.manager().inner().getRedis().getByResourceGroup(
ResourceUtils.groupFromResourceId(linkedServer.id()),
ResourceUtils.nameFromResourceId(linkedServer.id()));
innerResource = this.manager().inner().getRedis().getByResourceGroup(resourceGroupName(), name());
}
}
@Override
public ReplicationRole getLinkedServerRole(String linkedServerName) {
RedisLinkedServerWithPropertiesInner linkedServer = this.manager().inner().getLinkedServers().get(
this.resourceGroupName(),
this.name(),
linkedServerName);
if (linkedServer == null) {
throw new IllegalArgumentException("Server returned `null` value for Linked Server '"
+ linkedServerName + "' for Redis Cache '" + this.name()
+ "' in Resource Group '" + this.resourceGroupName() + "'.");
}
return linkedServer.serverRole();
}
@Override
public Map<String, ReplicationRole> listLinkedServers() {
Map<String, ReplicationRole> result = new TreeMap<>();
PagedIterable<RedisLinkedServerWithPropertiesInner> paginatedResponse = this.manager().inner().getLinkedServers().list(
this.resourceGroupName(),
this.name());
for (RedisLinkedServerWithPropertiesInner linkedServer : paginatedResponse) {
result.put(linkedServer.name(), linkedServer.serverRole());
}
return result;
}
} | class RedisCacheImpl extends GroupableResourceImpl<RedisCache, RedisResourceInner, RedisCacheImpl, RedisManager>
implements RedisCache, RedisCachePremium, RedisCache.Definition, RedisCache.Update {
private final ClientLogger logger = new ClientLogger(getClass());
private RedisAccessKeys cachedAccessKeys;
private RedisCreateParameters createParameters;
private RedisUpdateParameters updateParameters;
private RedisPatchSchedulesImpl patchSchedules;
private RedisFirewallRulesImpl firewallRules;
private boolean patchScheduleAdded;
RedisCacheImpl(String name, RedisResourceInner innerModel, final RedisManager redisManager) {
super(name, innerModel, redisManager);
this.createParameters = new RedisCreateParameters();
this.patchSchedules = new RedisPatchSchedulesImpl(this);
this.firewallRules = new RedisFirewallRulesImpl(this);
this.patchSchedules.enablePostRunMode();
this.firewallRules.enablePostRunMode();
this.patchScheduleAdded = false;
}
@Override
public Map<String, RedisFirewallRule> firewallRules() {
return this.firewallRules.rulesAsMap();
}
@Override
public List<ScheduleEntry> patchSchedules() {
List<ScheduleEntry> patchSchedules = listPatchSchedules();
if (patchSchedules == null) {
return new ArrayList<>();
}
return patchSchedules;
}
@Override
public List<ScheduleEntry> listPatchSchedules() {
RedisPatchScheduleImpl patchSchedule = this.patchSchedules.getPatchSchedule();
if (patchSchedule == null) {
return null;
}
return patchSchedule.scheduleEntries();
}
@Override
public String provisioningState() {
return this.inner().provisioningState().toString();
}
@Override
public String hostname() {
return this.inner().hostname();
}
@Override
public int port() {
return Utils.toPrimitiveInt(this.inner().port());
}
@Override
public int sslPort() {
return Utils.toPrimitiveInt(this.inner().sslPort());
}
@Override
public String redisVersion() {
return this.inner().redisVersion();
}
@Override
public Sku sku() {
return this.inner().sku();
}
@Override
public boolean nonSslPort() {
return this.inner().enableNonSslPort();
}
@Override
public int shardCount() {
return Utils.toPrimitiveInt(this.inner().shardCount());
}
@Override
public String subnetId() {
return this.inner().subnetId();
}
@Override
public String staticIp() {
return this.inner().staticIp();
}
@Override
public TlsVersion minimumTlsVersion() {
return this.inner().minimumTlsVersion();
}
@Override
public Map<String, String> redisConfiguration() {
return Collections.unmodifiableMap(this.inner().redisConfiguration());
}
@Override
public RedisCachePremium asPremium() {
if (this.isPremium()) {
return this;
}
return null;
}
@Override
public boolean isPremium() {
return this.sku().name().equals(SkuName.PREMIUM);
}
@Override
public RedisAccessKeys keys() {
if (cachedAccessKeys == null) {
cachedAccessKeys = refreshKeys();
}
return cachedAccessKeys;
}
@Override
public RedisAccessKeys refreshKeys() {
RedisAccessKeysInner response =
this.manager().inner().getRedis().listKeys(this.resourceGroupName(), this.name());
cachedAccessKeys = new RedisAccessKeysImpl(response);
return cachedAccessKeys;
}
@Override
public RedisAccessKeys regenerateKey(RedisKeyType keyType) {
RedisAccessKeysInner response =
this.manager().inner().getRedis().regenerateKey(this.resourceGroupName(), this.name(), keyType);
cachedAccessKeys = new RedisAccessKeysImpl(response);
return cachedAccessKeys;
}
@Override
public void forceReboot(RebootType rebootType) {
RedisRebootParameters parameters = new RedisRebootParameters().withRebootType(rebootType);
this.manager().inner().getRedis().forceReboot(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void forceReboot(RebootType rebootType, int shardId) {
RedisRebootParameters parameters = new RedisRebootParameters().withRebootType(rebootType).withShardId(shardId);
this.manager().inner().getRedis().forceReboot(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void importData(List<String> files) {
ImportRdbParameters parameters = new ImportRdbParameters().withFiles(files);
this.manager().inner().getRedis().importData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void importData(List<String> files, String fileFormat) {
ImportRdbParameters parameters = new ImportRdbParameters().withFiles(files).withFormat(fileFormat);
this.manager().inner().getRedis().importData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void exportData(String containerSASUrl, String prefix) {
ExportRdbParameters parameters = new ExportRdbParameters().withContainer(containerSASUrl).withPrefix(prefix);
this.manager().inner().getRedis().exportData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void exportData(String containerSASUrl, String prefix, String fileFormat) {
ExportRdbParameters parameters =
new ExportRdbParameters().withContainer(containerSASUrl).withPrefix(prefix).withFormat(fileFormat);
this.manager().inner().getRedis().exportData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public RedisCacheImpl withNonSslPort() {
if (isInCreateMode()) {
createParameters.withEnableNonSslPort(true);
} else {
updateParameters.withEnableNonSslPort(true);
}
return this;
}
@Override
public RedisCacheImpl withoutNonSslPort() {
if (!isInCreateMode()) {
updateParameters.withEnableNonSslPort(false);
}
return this;
}
@Override
public RedisCacheImpl withRedisConfiguration(Map<String, String> redisConfiguration) {
if (isInCreateMode()) {
createParameters.withRedisConfiguration(redisConfiguration);
} else {
updateParameters.withRedisConfiguration(redisConfiguration);
}
return this;
}
@Override
public RedisCacheImpl withRedisConfiguration(String key, String value) {
if (isInCreateMode()) {
if (createParameters.redisConfiguration() == null) {
createParameters.withRedisConfiguration(new TreeMap<>());
}
createParameters.redisConfiguration().put(key, value);
} else {
if (updateParameters.redisConfiguration() == null) {
updateParameters.withRedisConfiguration(new TreeMap<>());
}
updateParameters.redisConfiguration().put(key, value);
}
return this;
}
@Override
public RedisCacheImpl withFirewallRule(String name, String lowestIp, String highestIp) {
RedisFirewallRuleImpl rule = this.firewallRules.defineInlineFirewallRule(name);
rule.inner().withStartIp(lowestIp);
rule.inner().withEndIp(highestIp);
return this.withFirewallRule(rule);
}
@Override
public RedisCacheImpl withFirewallRule(RedisFirewallRule rule) {
this.firewallRules.addRule((RedisFirewallRuleImpl) rule);
return this;
}
@Override
public RedisCacheImpl withMinimumTlsVersion(TlsVersion tlsVersion) {
if (isInCreateMode()) {
createParameters.withMinimumTlsVersion(tlsVersion);
} else {
updateParameters.withMinimumTlsVersion(tlsVersion);
}
return this;
}
@Override
public RedisCacheImpl withoutMinimumTlsVersion() {
updateParameters.withMinimumTlsVersion(null);
return this;
}
@Override
public RedisCacheImpl withoutFirewallRule(String name) {
this.firewallRules.removeRule(name);
return this;
}
@Override
public RedisCacheImpl withoutRedisConfiguration() {
if (updateParameters.redisConfiguration() != null) {
updateParameters.redisConfiguration().clear();
}
return this;
}
@Override
public RedisCacheImpl withoutRedisConfiguration(String key) {
if (updateParameters.redisConfiguration() != null) {
updateParameters.redisConfiguration().remove(key);
}
return this;
}
@Override
public RedisCacheImpl withSubnet(HasId networkResource, String subnetName) {
if (networkResource != null) {
String subnetId = networkResource.id() + "/subnets/" + subnetName;
return withSubnet(subnetId);
} else {
createParameters.withSubnetId(null);
}
return this;
}
@Override
public RedisCacheImpl withSubnet(String subnetId) {
if (subnetId != null) {
if (isInCreateMode()) {
createParameters.withSubnetId(subnetId);
} else {
throw logger
.logExceptionAsError(
new UnsupportedOperationException("Subnet cannot be modified during update operation."));
}
}
return this;
}
@Override
public RedisCacheImpl withStaticIp(String staticIp) {
if (isInCreateMode()) {
createParameters.withStaticIp(staticIp);
} else {
throw logger
.logExceptionAsError(
new UnsupportedOperationException("Static IP cannot be modified during update operation."));
}
return this;
}
@Override
public RedisCacheImpl withBasicSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku().withName(SkuName.BASIC).withFamily(SkuFamily.C));
} else {
updateParameters.withSku(new Sku().withName(SkuName.BASIC).withFamily(SkuFamily.C));
}
return this;
}
@Override
public RedisCacheImpl withBasicSku(int capacity) {
if (isInCreateMode()) {
createParameters.withSku(new Sku().withName(SkuName.BASIC).withFamily(SkuFamily.C).withCapacity(capacity));
} else {
updateParameters.withSku(new Sku().withName(SkuName.BASIC).withFamily(SkuFamily.C).withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withStandardSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku().withName(SkuName.STANDARD).withFamily(SkuFamily.C));
} else {
updateParameters.withSku(new Sku().withName(SkuName.STANDARD).withFamily(SkuFamily.C));
}
return this;
}
@Override
public RedisCacheImpl withStandardSku(int capacity) {
if (isInCreateMode()) {
createParameters
.withSku(new Sku().withName(SkuName.STANDARD).withFamily(SkuFamily.C).withCapacity(capacity));
} else {
updateParameters
.withSku(new Sku().withName(SkuName.STANDARD).withFamily(SkuFamily.C).withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withPremiumSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku().withName(SkuName.PREMIUM).withFamily(SkuFamily.P).withCapacity(1));
} else {
updateParameters.withSku(new Sku().withName(SkuName.PREMIUM).withFamily(SkuFamily.P).withCapacity(1));
}
return this;
}
@Override
public RedisCacheImpl withPremiumSku(int capacity) {
if (isInCreateMode()) {
createParameters
.withSku(new Sku().withName(SkuName.PREMIUM).withFamily(SkuFamily.P).withCapacity(capacity));
} else {
updateParameters
.withSku(new Sku().withName(SkuName.PREMIUM).withFamily(SkuFamily.P).withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withShardCount(int shardCount) {
if (isInCreateMode()) {
createParameters.withShardCount(shardCount);
} else {
updateParameters.withShardCount(shardCount);
}
return this;
}
@Override
public RedisCacheImpl withPatchSchedule(DayOfWeek dayOfWeek, int startHourUtc) {
return this.withPatchSchedule(new ScheduleEntry().withDayOfWeek(dayOfWeek).withStartHourUtc(startHourUtc));
}
@Override
public RedisCacheImpl withPatchSchedule(DayOfWeek dayOfWeek, int startHourUtc, Duration maintenanceWindow) {
return this
.withPatchSchedule(
new ScheduleEntry()
.withDayOfWeek(dayOfWeek)
.withStartHourUtc(startHourUtc)
.withMaintenanceWindow(maintenanceWindow));
}
@Override
public RedisCacheImpl withPatchSchedule(List<ScheduleEntry> scheduleEntries) {
this.patchSchedules.clear();
for (ScheduleEntry entry : scheduleEntries) {
this.withPatchSchedule(entry);
}
return this;
}
@Override
public RedisCacheImpl withPatchSchedule(ScheduleEntry scheduleEntry) {
RedisPatchScheduleImpl psch;
if (this.patchSchedules.patchSchedulesAsMap().isEmpty()) {
psch = this.patchSchedules.defineInlinePatchSchedule();
this.patchScheduleAdded = true;
psch.inner().withScheduleEntries(new ArrayList<>());
this.patchSchedules.addPatchSchedule(psch);
} else if (!this.patchScheduleAdded) {
psch = this.patchSchedules.updateInlinePatchSchedule();
} else {
psch = this.patchSchedules.getPatchSchedule();
}
psch.inner().scheduleEntries().add(scheduleEntry);
return this;
}
@Override
public RedisCacheImpl withoutPatchSchedule() {
if (this.patchSchedules.patchSchedulesAsMap().isEmpty()) {
return this;
} else {
this.patchSchedules.deleteInlinePatchSchedule();
}
return this;
}
@Override
public void deletePatchSchedule() {
this.patchSchedules.removePatchSchedule();
this.patchSchedules.refresh();
}
@Override
public Mono<RedisCache> refreshAsync() {
return super
.refreshAsync()
.then(this.firewallRules.refreshAsync())
.then(this.patchSchedules.refreshAsync())
.then(Mono.just(this));
}
@Override
protected Mono<RedisResourceInner> getInnerAsync() {
return this.manager().inner().getRedis().getByResourceGroupAsync(this.resourceGroupName(), this.name());
}
@Override
public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) {
this.firewallRules.clear();
this.patchSchedules.clear();
this.patchScheduleAdded = false;
if (isGroupFaulted) {
return Mono.empty();
} else {
return this.refreshAsync().then();
}
}
@Override
public RedisCacheImpl update() {
this.updateParameters = new RedisUpdateParameters();
this.patchSchedules.enableCommitMode();
this.firewallRules.enableCommitMode();
return super.update();
}
@Override
@Override
public Mono<RedisCache> createResourceAsync() {
createParameters.withLocation(this.regionName());
createParameters.withTags(this.inner().tags());
this.patchScheduleAdded = false;
return this
.manager()
.inner()
.getRedis()
.createAsync(this.resourceGroupName(), this.name(), createParameters)
.map(innerToFluentMap(this));
}
@Override
public String addLinkedServer(String linkedRedisCacheId, String linkedServerLocation, ReplicationRole role) {
String linkedRedisName = ResourceUtils.nameFromResourceId(linkedRedisCacheId);
RedisLinkedServerCreateParameters params =
new RedisLinkedServerCreateParameters()
.withLinkedRedisCacheId(linkedRedisCacheId)
.withLinkedRedisCacheLocation(linkedServerLocation)
.withServerRole(role);
RedisLinkedServerWithPropertiesInner linkedServerInner =
this
.manager()
.inner()
.getLinkedServers()
.create(this.resourceGroupName(), this.name(), linkedRedisName, params);
return linkedServerInner.name();
}
@Override
public void removeLinkedServer(String linkedServerName) {
RedisLinkedServerWithPropertiesInner linkedServer =
this.manager().inner().getLinkedServers().get(this.resourceGroupName(), this.name(), linkedServerName);
this.manager().inner().getLinkedServers().delete(this.resourceGroupName(), this.name(), linkedServerName);
RedisResourceInner innerLinkedResource = null;
RedisResourceInner innerResource = null;
while (innerLinkedResource == null
|| innerLinkedResource.provisioningState() != ProvisioningState.SUCCEEDED
|| innerResource == null
|| innerResource.provisioningState() != ProvisioningState.SUCCEEDED) {
SdkContext.sleep(30 * 1000);
innerLinkedResource =
this
.manager()
.inner()
.getRedis()
.getByResourceGroup(
ResourceUtils.groupFromResourceId(linkedServer.id()),
ResourceUtils.nameFromResourceId(linkedServer.id()));
innerResource = this.manager().inner().getRedis().getByResourceGroup(resourceGroupName(), name());
}
}
@Override
public ReplicationRole getLinkedServerRole(String linkedServerName) {
RedisLinkedServerWithPropertiesInner linkedServer =
this.manager().inner().getLinkedServers().get(this.resourceGroupName(), this.name(), linkedServerName);
if (linkedServer == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"Server returned `null` value for Linked Server '"
+ linkedServerName
+ "' for Redis Cache '"
+ this.name()
+ "' in Resource Group '"
+ this.resourceGroupName()
+ "'."));
}
return linkedServer.serverRole();
}
@Override
public Map<String, ReplicationRole> listLinkedServers() {
Map<String, ReplicationRole> result = new TreeMap<>();
PagedIterable<RedisLinkedServerWithPropertiesInner> paginatedResponse =
this.manager().inner().getLinkedServers().list(this.resourceGroupName(), this.name());
for (RedisLinkedServerWithPropertiesInner linkedServer : paginatedResponse) {
result.put(linkedServer.name(), linkedServer.serverRole());
}
return result;
}
} |
done | public Mono<RedisCache> updateResourceAsync() {
updateParameters.withTags(this.inner().tags());
return this.manager().inner().getRedis().updateAsync(resourceGroupName(), name(), updateParameters)
.map(innerToFluentMap(this))
.filter(redisCache -> !redisCache.provisioningState().equalsIgnoreCase(ProvisioningState.SUCCEEDED.toString()))
.flatMap(redisCache -> {
SdkContext.sleep(30 * 1000);
this.patchScheduleAdded = false;
return this.manager().inner().getRedis().getByResourceGroupAsync(resourceGroupName(), name())
.doOnNext( this::setInner)
.filter(redisResourceInner -> redisResourceInner.provisioningState().toString()
.equalsIgnoreCase(ProvisioningState.SUCCEEDED.toString()))
.repeatWhenEmpty(
longFlux -> longFlux.flatMap(
index -> Mono.delay(SdkContext.getDelayDuration(Duration.ofSeconds(30)))
)
);
}
)
.then(this.patchSchedules.commitAndGetAllAsync())
.then(this.firewallRules.commitAndGetAllAsync())
.then(Mono.just(this));
} | SdkContext.sleep(30 * 1000); | public Mono<RedisCache> updateResourceAsync() {
updateParameters.withTags(this.inner().tags());
this.patchScheduleAdded = false;
return this
.manager()
.inner()
.getRedis()
.updateAsync(resourceGroupName(), name(), updateParameters)
.map(innerToFluentMap(this))
.filter(
redisCache -> !redisCache.provisioningState().equalsIgnoreCase(ProvisioningState.SUCCEEDED.toString()))
.flatMapMany(
redisCache ->
Mono
.delay(SdkContext.getDelayDuration(Duration.ofSeconds(30)))
.flatMap(o -> manager().inner().getRedis().getByResourceGroupAsync(resourceGroupName(), name()))
.doOnNext(this::setInner)
.repeat()
.takeUntil(
redisResourceInner ->
redisResourceInner
.provisioningState()
.toString()
.equalsIgnoreCase(ProvisioningState.SUCCEEDED.toString())))
.then(this.patchSchedules.commitAndGetAllAsync())
.then(this.firewallRules.commitAndGetAllAsync())
.then(Mono.just(this));
} | class RedisCacheImpl
extends GroupableResourceImpl<
RedisCache,
RedisResourceInner,
RedisCacheImpl,
RedisManager>
implements
RedisCache,
RedisCachePremium,
RedisCache.Definition,
RedisCache.Update {
private RedisAccessKeys cachedAccessKeys;
private RedisCreateParameters createParameters;
private RedisUpdateParameters updateParameters;
private RedisPatchSchedulesImpl patchSchedules;
private RedisFirewallRulesImpl firewallRules;
private boolean patchScheduleAdded;
RedisCacheImpl(String name,
RedisResourceInner innerModel,
final RedisManager redisManager) {
super(name, innerModel, redisManager);
this.createParameters = new RedisCreateParameters();
this.patchSchedules = new RedisPatchSchedulesImpl(this);
this.firewallRules = new RedisFirewallRulesImpl(this);
this.patchSchedules.enablePostRunMode();
this.firewallRules.enablePostRunMode();
this.patchScheduleAdded = false;
}
@Override
public Map<String, RedisFirewallRule> firewallRules() {
return this.firewallRules.rulesAsMap();
}
@Override
public List<ScheduleEntry> patchSchedules() {
List<ScheduleEntry> patchSchedules = listPatchSchedules();
if (patchSchedules == null) {
return new ArrayList<>();
}
return patchSchedules;
}
@Override
public List<ScheduleEntry> listPatchSchedules() {
RedisPatchScheduleImpl patchSchedule = this.patchSchedules.getPatchSchedule();
if (patchSchedule == null) {
return null;
}
return patchSchedule.scheduleEntries();
}
@Override
public String provisioningState() {
return this.inner().provisioningState().toString();
}
@Override
public String hostname() {
return this.inner().hostname();
}
@Override
public int port() {
return Utils.toPrimitiveInt(this.inner().port());
}
@Override
public int sslPort() {
return Utils.toPrimitiveInt(this.inner().sslPort());
}
@Override
public String redisVersion() {
return this.inner().redisVersion();
}
@Override
public Sku sku() {
return this.inner().sku();
}
@Override
public boolean nonSslPort() {
return this.inner().enableNonSslPort();
}
@Override
public int shardCount() {
return Utils.toPrimitiveInt(this.inner().shardCount());
}
@Override
public String subnetId() {
return this.inner().subnetId();
}
@Override
public String staticIp() {
return this.inner().staticIp();
}
@Override
public TlsVersion minimumTlsVersion() {
return this.inner().minimumTlsVersion();
}
@Override
public Map<String, String> redisConfiguration() {
return Collections.unmodifiableMap(this.inner().redisConfiguration());
}
@Override
public RedisCachePremium asPremium() {
if (this.isPremium()) {
return this;
}
return null;
}
@Override
public boolean isPremium() {
return this.sku().name().equals(SkuName.PREMIUM);
}
@Override
public RedisAccessKeys keys() {
if (cachedAccessKeys == null) {
cachedAccessKeys = refreshKeys();
}
return cachedAccessKeys;
}
@Override
public RedisAccessKeys refreshKeys() {
RedisAccessKeysInner response =
this.manager().inner().getRedis().listKeys(this.resourceGroupName(), this.name());
cachedAccessKeys = new RedisAccessKeysImpl(response);
return cachedAccessKeys;
}
@Override
public RedisAccessKeys regenerateKey(RedisKeyType keyType) {
RedisAccessKeysInner response =
this.manager().inner().getRedis().regenerateKey(this.resourceGroupName(), this.name(), keyType);
cachedAccessKeys = new RedisAccessKeysImpl(response);
return cachedAccessKeys;
}
@Override
public void forceReboot(RebootType rebootType) {
RedisRebootParameters parameters = new RedisRebootParameters()
.withRebootType(rebootType);
this.manager().inner().getRedis().forceReboot(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void forceReboot(RebootType rebootType, int shardId) {
RedisRebootParameters parameters = new RedisRebootParameters()
.withRebootType(rebootType)
.withShardId(shardId);
this.manager().inner().getRedis().forceReboot(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void importData(List<String> files) {
ImportRdbParameters parameters = new ImportRdbParameters()
.withFiles(files);
this.manager().inner().getRedis().importData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void importData(List<String> files, String fileFormat) {
ImportRdbParameters parameters = new ImportRdbParameters()
.withFiles(files)
.withFormat(fileFormat);
this.manager().inner().getRedis().importData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void exportData(String containerSASUrl, String prefix) {
ExportRdbParameters parameters = new ExportRdbParameters()
.withContainer(containerSASUrl)
.withPrefix(prefix);
this.manager().inner().getRedis().exportData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void exportData(String containerSASUrl, String prefix, String fileFormat) {
ExportRdbParameters parameters = new ExportRdbParameters()
.withContainer(containerSASUrl)
.withPrefix(prefix)
.withFormat(fileFormat);
this.manager().inner().getRedis().exportData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public RedisCacheImpl withNonSslPort() {
if (isInCreateMode()) {
createParameters.withEnableNonSslPort(true);
} else {
updateParameters.withEnableNonSslPort(true);
}
return this;
}
@Override
public RedisCacheImpl withoutNonSslPort() {
if (!isInCreateMode()) {
updateParameters.withEnableNonSslPort(false);
}
return this;
}
@Override
public RedisCacheImpl withRedisConfiguration(Map<String, String> redisConfiguration) {
if (isInCreateMode()) {
createParameters.withRedisConfiguration(redisConfiguration);
} else {
updateParameters.withRedisConfiguration(redisConfiguration);
}
return this;
}
@Override
public RedisCacheImpl withRedisConfiguration(String key, String value) {
if (isInCreateMode()) {
if (createParameters.redisConfiguration() == null) {
createParameters.withRedisConfiguration(new TreeMap<>());
}
createParameters.redisConfiguration().put(key, value);
} else {
if (updateParameters.redisConfiguration() == null) {
updateParameters.withRedisConfiguration(new TreeMap<>());
}
updateParameters.redisConfiguration().put(key, value);
}
return this;
}
@Override
public RedisCacheImpl withFirewallRule(String name, String lowestIp, String highestIp) {
RedisFirewallRuleImpl rule = this.firewallRules.defineInlineFirewallRule(name);
rule.inner().withStartIp(lowestIp);
rule.inner().withEndIp(highestIp);
return this.withFirewallRule(rule);
}
@Override
public RedisCacheImpl withFirewallRule(RedisFirewallRule rule) {
this.firewallRules.addRule((RedisFirewallRuleImpl) rule);
return this;
}
@Override
public RedisCacheImpl withMinimumTlsVersion(TlsVersion tlsVersion) {
if (isInCreateMode()) {
createParameters.withMinimumTlsVersion(tlsVersion);
} else {
updateParameters.withMinimumTlsVersion(tlsVersion);
}
return this;
}
@Override
public RedisCacheImpl withoutMinimumTlsVersion() {
updateParameters.withMinimumTlsVersion(null);
return this;
}
@Override
public RedisCacheImpl withoutFirewallRule(String name) {
this.firewallRules.removeRule(name);
return this;
}
@Override
public RedisCacheImpl withoutRedisConfiguration() {
if (updateParameters.redisConfiguration() != null) {
updateParameters.redisConfiguration().clear();
}
return this;
}
@Override
public RedisCacheImpl withoutRedisConfiguration(String key) {
if (updateParameters.redisConfiguration() != null) {
updateParameters.redisConfiguration().remove(key);
}
return this;
}
@Override
public RedisCacheImpl withSubnet(HasId networkResource, String subnetName) {
if (networkResource != null) {
String subnetId = networkResource.id() + "/subnets/" + subnetName;
return withSubnet(subnetId);
} else {
createParameters.withSubnetId(null);
}
return this;
}
@Override
public RedisCacheImpl withSubnet(String subnetId) {
if (subnetId != null) {
if (isInCreateMode()) {
createParameters.withSubnetId(subnetId);
} else {
throw new UnsupportedOperationException("Subnet cannot be modified during update operation.");
}
}
return this;
}
@Override
public RedisCacheImpl withStaticIp(String staticIp) {
if (isInCreateMode()) {
createParameters.withStaticIp(staticIp);
} else {
throw new UnsupportedOperationException("Static IP cannot be modified during update operation.");
}
return this;
}
@Override
public RedisCacheImpl withBasicSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.BASIC)
.withFamily(SkuFamily.C));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.BASIC)
.withFamily(SkuFamily.C));
}
return this;
}
@Override
public RedisCacheImpl withBasicSku(int capacity) {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.BASIC)
.withFamily(SkuFamily.C)
.withCapacity(capacity));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.BASIC)
.withFamily(SkuFamily.C)
.withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withStandardSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.STANDARD)
.withFamily(SkuFamily.C));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.STANDARD)
.withFamily(SkuFamily.C));
}
return this;
}
@Override
public RedisCacheImpl withStandardSku(int capacity) {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.STANDARD)
.withFamily(SkuFamily.C)
.withCapacity(capacity));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.STANDARD)
.withFamily(SkuFamily.C)
.withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withPremiumSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.PREMIUM)
.withFamily(SkuFamily.P)
.withCapacity(1));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.PREMIUM)
.withFamily(SkuFamily.P)
.withCapacity(1));
}
return this;
}
@Override
public RedisCacheImpl withPremiumSku(int capacity) {
if (isInCreateMode()) {
createParameters.withSku(new Sku()
.withName(SkuName.PREMIUM)
.withFamily(SkuFamily.P)
.withCapacity(capacity));
} else {
updateParameters.withSku(new Sku()
.withName(SkuName.PREMIUM)
.withFamily(SkuFamily.P)
.withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withShardCount(int shardCount) {
if (isInCreateMode()) {
createParameters.withShardCount(shardCount);
} else {
updateParameters.withShardCount(shardCount);
}
return this;
}
@Override
public RedisCacheImpl withPatchSchedule(DayOfWeek dayOfWeek, int startHourUtc) {
return this.withPatchSchedule(new ScheduleEntry()
.withDayOfWeek(dayOfWeek)
.withStartHourUtc(startHourUtc));
}
@Override
public RedisCacheImpl withPatchSchedule(DayOfWeek dayOfWeek, int startHourUtc, Duration maintenanceWindow) {
return this.withPatchSchedule(new ScheduleEntry()
.withDayOfWeek(dayOfWeek)
.withStartHourUtc(startHourUtc)
.withMaintenanceWindow(maintenanceWindow));
}
@Override
public RedisCacheImpl withPatchSchedule(List<ScheduleEntry> scheduleEntries) {
this.patchSchedules.clear();
for (ScheduleEntry entry : scheduleEntries) {
this.withPatchSchedule(entry);
}
return this;
}
@Override
public RedisCacheImpl withPatchSchedule(ScheduleEntry scheduleEntry) {
RedisPatchScheduleImpl psch;
if (this.patchSchedules.patchSchedulesAsMap().isEmpty()) {
psch = this.patchSchedules.defineInlinePatchSchedule();
this.patchScheduleAdded = true;
psch.inner().withScheduleEntries(new ArrayList<>());
this.patchSchedules.addPatchSchedule(psch);
} else if (!this.patchScheduleAdded) {
psch = this.patchSchedules.updateInlinePatchSchedule();
} else {
psch = this.patchSchedules.getPatchSchedule();
}
psch.inner().scheduleEntries().add(scheduleEntry);
return this;
}
@Override
public RedisCacheImpl withoutPatchSchedule() {
if (this.patchSchedules.patchSchedulesAsMap().isEmpty()) {
return this;
} else {
this.patchSchedules.deleteInlinePatchSchedule();
}
return this;
}
@Override
public void deletePatchSchedule() {
this.patchSchedules.removePatchSchedule();
this.patchSchedules.refresh();
}
@Override
public Mono<RedisCache> refreshAsync() {
return super.refreshAsync()
.then(this.firewallRules.refreshAsync())
.then(this.patchSchedules.refreshAsync())
.then(Mono.just(this));
}
@Override
protected Mono<RedisResourceInner> getInnerAsync() {
return this.manager().inner().getRedis().getByResourceGroupAsync(this.resourceGroupName(), this.name());
}
@Override
public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) {
this.firewallRules.clear();
this.patchSchedules.clear();
this.patchScheduleAdded = false;
if (isGroupFaulted) {
return Mono.empty();
} else {
return this.refreshAsync().then();
}
}
@Override
public RedisCacheImpl update() {
this.updateParameters = new RedisUpdateParameters();
this.patchSchedules.enableCommitMode();
this.firewallRules.enableCommitMode();
return super.update();
}
@Override
@Override
public Mono<RedisCache> createResourceAsync() {
createParameters.withLocation(this.regionName());
createParameters.withTags(this.inner().tags());
this.patchScheduleAdded = false;
return this.manager().inner().getRedis().createAsync(this.resourceGroupName(), this.name(), createParameters)
.map(innerToFluentMap(this));
}
@Override
public String addLinkedServer(String linkedRedisCacheId, String linkedServerLocation, ReplicationRole role) {
String linkedRedisName = ResourceUtils.nameFromResourceId(linkedRedisCacheId);
RedisLinkedServerCreateParameters params = new RedisLinkedServerCreateParameters()
.withLinkedRedisCacheId(linkedRedisCacheId)
.withLinkedRedisCacheLocation(linkedServerLocation)
.withServerRole(role);
RedisLinkedServerWithPropertiesInner linkedServerInner = this.manager().inner().getLinkedServers().create(
this.resourceGroupName(),
this.name(),
linkedRedisName,
params);
return linkedServerInner.name();
}
@Override
public void removeLinkedServer(String linkedServerName) {
RedisLinkedServerWithPropertiesInner linkedServer = this.manager().inner().getLinkedServers().get(this.resourceGroupName(), this.name(), linkedServerName);
this.manager().inner().getLinkedServers().delete(
this.resourceGroupName(),
this.name(),
linkedServerName);
RedisResourceInner innerLinkedResource = null;
RedisResourceInner innerResource = null;
while (innerLinkedResource == null
|| innerLinkedResource.provisioningState() != ProvisioningState.SUCCEEDED
|| innerResource == null
|| innerResource.provisioningState() != ProvisioningState.SUCCEEDED) {
SdkContext.sleep(30 * 1000);
innerLinkedResource = this.manager().inner().getRedis().getByResourceGroup(
ResourceUtils.groupFromResourceId(linkedServer.id()),
ResourceUtils.nameFromResourceId(linkedServer.id()));
innerResource = this.manager().inner().getRedis().getByResourceGroup(resourceGroupName(), name());
}
}
@Override
public ReplicationRole getLinkedServerRole(String linkedServerName) {
RedisLinkedServerWithPropertiesInner linkedServer = this.manager().inner().getLinkedServers().get(
this.resourceGroupName(),
this.name(),
linkedServerName);
if (linkedServer == null) {
throw new IllegalArgumentException("Server returned `null` value for Linked Server '"
+ linkedServerName + "' for Redis Cache '" + this.name()
+ "' in Resource Group '" + this.resourceGroupName() + "'.");
}
return linkedServer.serverRole();
}
@Override
public Map<String, ReplicationRole> listLinkedServers() {
Map<String, ReplicationRole> result = new TreeMap<>();
PagedIterable<RedisLinkedServerWithPropertiesInner> paginatedResponse = this.manager().inner().getLinkedServers().list(
this.resourceGroupName(),
this.name());
for (RedisLinkedServerWithPropertiesInner linkedServer : paginatedResponse) {
result.put(linkedServer.name(), linkedServer.serverRole());
}
return result;
}
} | class RedisCacheImpl extends GroupableResourceImpl<RedisCache, RedisResourceInner, RedisCacheImpl, RedisManager>
implements RedisCache, RedisCachePremium, RedisCache.Definition, RedisCache.Update {
private final ClientLogger logger = new ClientLogger(getClass());
private RedisAccessKeys cachedAccessKeys;
private RedisCreateParameters createParameters;
private RedisUpdateParameters updateParameters;
private RedisPatchSchedulesImpl patchSchedules;
private RedisFirewallRulesImpl firewallRules;
private boolean patchScheduleAdded;
RedisCacheImpl(String name, RedisResourceInner innerModel, final RedisManager redisManager) {
super(name, innerModel, redisManager);
this.createParameters = new RedisCreateParameters();
this.patchSchedules = new RedisPatchSchedulesImpl(this);
this.firewallRules = new RedisFirewallRulesImpl(this);
this.patchSchedules.enablePostRunMode();
this.firewallRules.enablePostRunMode();
this.patchScheduleAdded = false;
}
@Override
public Map<String, RedisFirewallRule> firewallRules() {
return this.firewallRules.rulesAsMap();
}
@Override
public List<ScheduleEntry> patchSchedules() {
List<ScheduleEntry> patchSchedules = listPatchSchedules();
if (patchSchedules == null) {
return new ArrayList<>();
}
return patchSchedules;
}
@Override
public List<ScheduleEntry> listPatchSchedules() {
RedisPatchScheduleImpl patchSchedule = this.patchSchedules.getPatchSchedule();
if (patchSchedule == null) {
return null;
}
return patchSchedule.scheduleEntries();
}
@Override
public String provisioningState() {
return this.inner().provisioningState().toString();
}
@Override
public String hostname() {
return this.inner().hostname();
}
@Override
public int port() {
return Utils.toPrimitiveInt(this.inner().port());
}
@Override
public int sslPort() {
return Utils.toPrimitiveInt(this.inner().sslPort());
}
@Override
public String redisVersion() {
return this.inner().redisVersion();
}
@Override
public Sku sku() {
return this.inner().sku();
}
@Override
public boolean nonSslPort() {
return this.inner().enableNonSslPort();
}
@Override
public int shardCount() {
return Utils.toPrimitiveInt(this.inner().shardCount());
}
@Override
public String subnetId() {
return this.inner().subnetId();
}
@Override
public String staticIp() {
return this.inner().staticIp();
}
@Override
public TlsVersion minimumTlsVersion() {
return this.inner().minimumTlsVersion();
}
@Override
public Map<String, String> redisConfiguration() {
return Collections.unmodifiableMap(this.inner().redisConfiguration());
}
@Override
public RedisCachePremium asPremium() {
if (this.isPremium()) {
return this;
}
return null;
}
@Override
public boolean isPremium() {
return this.sku().name().equals(SkuName.PREMIUM);
}
@Override
public RedisAccessKeys keys() {
if (cachedAccessKeys == null) {
cachedAccessKeys = refreshKeys();
}
return cachedAccessKeys;
}
@Override
public RedisAccessKeys refreshKeys() {
RedisAccessKeysInner response =
this.manager().inner().getRedis().listKeys(this.resourceGroupName(), this.name());
cachedAccessKeys = new RedisAccessKeysImpl(response);
return cachedAccessKeys;
}
@Override
public RedisAccessKeys regenerateKey(RedisKeyType keyType) {
RedisAccessKeysInner response =
this.manager().inner().getRedis().regenerateKey(this.resourceGroupName(), this.name(), keyType);
cachedAccessKeys = new RedisAccessKeysImpl(response);
return cachedAccessKeys;
}
@Override
public void forceReboot(RebootType rebootType) {
RedisRebootParameters parameters = new RedisRebootParameters().withRebootType(rebootType);
this.manager().inner().getRedis().forceReboot(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void forceReboot(RebootType rebootType, int shardId) {
RedisRebootParameters parameters = new RedisRebootParameters().withRebootType(rebootType).withShardId(shardId);
this.manager().inner().getRedis().forceReboot(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void importData(List<String> files) {
ImportRdbParameters parameters = new ImportRdbParameters().withFiles(files);
this.manager().inner().getRedis().importData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void importData(List<String> files, String fileFormat) {
ImportRdbParameters parameters = new ImportRdbParameters().withFiles(files).withFormat(fileFormat);
this.manager().inner().getRedis().importData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void exportData(String containerSASUrl, String prefix) {
ExportRdbParameters parameters = new ExportRdbParameters().withContainer(containerSASUrl).withPrefix(prefix);
this.manager().inner().getRedis().exportData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public void exportData(String containerSASUrl, String prefix, String fileFormat) {
ExportRdbParameters parameters =
new ExportRdbParameters().withContainer(containerSASUrl).withPrefix(prefix).withFormat(fileFormat);
this.manager().inner().getRedis().exportData(this.resourceGroupName(), this.name(), parameters);
}
@Override
public RedisCacheImpl withNonSslPort() {
if (isInCreateMode()) {
createParameters.withEnableNonSslPort(true);
} else {
updateParameters.withEnableNonSslPort(true);
}
return this;
}
@Override
public RedisCacheImpl withoutNonSslPort() {
if (!isInCreateMode()) {
updateParameters.withEnableNonSslPort(false);
}
return this;
}
@Override
public RedisCacheImpl withRedisConfiguration(Map<String, String> redisConfiguration) {
if (isInCreateMode()) {
createParameters.withRedisConfiguration(redisConfiguration);
} else {
updateParameters.withRedisConfiguration(redisConfiguration);
}
return this;
}
@Override
public RedisCacheImpl withRedisConfiguration(String key, String value) {
if (isInCreateMode()) {
if (createParameters.redisConfiguration() == null) {
createParameters.withRedisConfiguration(new TreeMap<>());
}
createParameters.redisConfiguration().put(key, value);
} else {
if (updateParameters.redisConfiguration() == null) {
updateParameters.withRedisConfiguration(new TreeMap<>());
}
updateParameters.redisConfiguration().put(key, value);
}
return this;
}
@Override
public RedisCacheImpl withFirewallRule(String name, String lowestIp, String highestIp) {
RedisFirewallRuleImpl rule = this.firewallRules.defineInlineFirewallRule(name);
rule.inner().withStartIp(lowestIp);
rule.inner().withEndIp(highestIp);
return this.withFirewallRule(rule);
}
@Override
public RedisCacheImpl withFirewallRule(RedisFirewallRule rule) {
this.firewallRules.addRule((RedisFirewallRuleImpl) rule);
return this;
}
@Override
public RedisCacheImpl withMinimumTlsVersion(TlsVersion tlsVersion) {
if (isInCreateMode()) {
createParameters.withMinimumTlsVersion(tlsVersion);
} else {
updateParameters.withMinimumTlsVersion(tlsVersion);
}
return this;
}
@Override
public RedisCacheImpl withoutMinimumTlsVersion() {
updateParameters.withMinimumTlsVersion(null);
return this;
}
@Override
public RedisCacheImpl withoutFirewallRule(String name) {
this.firewallRules.removeRule(name);
return this;
}
@Override
public RedisCacheImpl withoutRedisConfiguration() {
if (updateParameters.redisConfiguration() != null) {
updateParameters.redisConfiguration().clear();
}
return this;
}
@Override
public RedisCacheImpl withoutRedisConfiguration(String key) {
if (updateParameters.redisConfiguration() != null) {
updateParameters.redisConfiguration().remove(key);
}
return this;
}
@Override
public RedisCacheImpl withSubnet(HasId networkResource, String subnetName) {
if (networkResource != null) {
String subnetId = networkResource.id() + "/subnets/" + subnetName;
return withSubnet(subnetId);
} else {
createParameters.withSubnetId(null);
}
return this;
}
@Override
public RedisCacheImpl withSubnet(String subnetId) {
if (subnetId != null) {
if (isInCreateMode()) {
createParameters.withSubnetId(subnetId);
} else {
throw logger
.logExceptionAsError(
new UnsupportedOperationException("Subnet cannot be modified during update operation."));
}
}
return this;
}
@Override
public RedisCacheImpl withStaticIp(String staticIp) {
if (isInCreateMode()) {
createParameters.withStaticIp(staticIp);
} else {
throw logger
.logExceptionAsError(
new UnsupportedOperationException("Static IP cannot be modified during update operation."));
}
return this;
}
@Override
public RedisCacheImpl withBasicSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku().withName(SkuName.BASIC).withFamily(SkuFamily.C));
} else {
updateParameters.withSku(new Sku().withName(SkuName.BASIC).withFamily(SkuFamily.C));
}
return this;
}
@Override
public RedisCacheImpl withBasicSku(int capacity) {
if (isInCreateMode()) {
createParameters.withSku(new Sku().withName(SkuName.BASIC).withFamily(SkuFamily.C).withCapacity(capacity));
} else {
updateParameters.withSku(new Sku().withName(SkuName.BASIC).withFamily(SkuFamily.C).withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withStandardSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku().withName(SkuName.STANDARD).withFamily(SkuFamily.C));
} else {
updateParameters.withSku(new Sku().withName(SkuName.STANDARD).withFamily(SkuFamily.C));
}
return this;
}
@Override
public RedisCacheImpl withStandardSku(int capacity) {
if (isInCreateMode()) {
createParameters
.withSku(new Sku().withName(SkuName.STANDARD).withFamily(SkuFamily.C).withCapacity(capacity));
} else {
updateParameters
.withSku(new Sku().withName(SkuName.STANDARD).withFamily(SkuFamily.C).withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withPremiumSku() {
if (isInCreateMode()) {
createParameters.withSku(new Sku().withName(SkuName.PREMIUM).withFamily(SkuFamily.P).withCapacity(1));
} else {
updateParameters.withSku(new Sku().withName(SkuName.PREMIUM).withFamily(SkuFamily.P).withCapacity(1));
}
return this;
}
@Override
public RedisCacheImpl withPremiumSku(int capacity) {
if (isInCreateMode()) {
createParameters
.withSku(new Sku().withName(SkuName.PREMIUM).withFamily(SkuFamily.P).withCapacity(capacity));
} else {
updateParameters
.withSku(new Sku().withName(SkuName.PREMIUM).withFamily(SkuFamily.P).withCapacity(capacity));
}
return this;
}
@Override
public RedisCacheImpl withShardCount(int shardCount) {
if (isInCreateMode()) {
createParameters.withShardCount(shardCount);
} else {
updateParameters.withShardCount(shardCount);
}
return this;
}
@Override
public RedisCacheImpl withPatchSchedule(DayOfWeek dayOfWeek, int startHourUtc) {
return this.withPatchSchedule(new ScheduleEntry().withDayOfWeek(dayOfWeek).withStartHourUtc(startHourUtc));
}
@Override
public RedisCacheImpl withPatchSchedule(DayOfWeek dayOfWeek, int startHourUtc, Duration maintenanceWindow) {
return this
.withPatchSchedule(
new ScheduleEntry()
.withDayOfWeek(dayOfWeek)
.withStartHourUtc(startHourUtc)
.withMaintenanceWindow(maintenanceWindow));
}
@Override
public RedisCacheImpl withPatchSchedule(List<ScheduleEntry> scheduleEntries) {
this.patchSchedules.clear();
for (ScheduleEntry entry : scheduleEntries) {
this.withPatchSchedule(entry);
}
return this;
}
@Override
public RedisCacheImpl withPatchSchedule(ScheduleEntry scheduleEntry) {
RedisPatchScheduleImpl psch;
if (this.patchSchedules.patchSchedulesAsMap().isEmpty()) {
psch = this.patchSchedules.defineInlinePatchSchedule();
this.patchScheduleAdded = true;
psch.inner().withScheduleEntries(new ArrayList<>());
this.patchSchedules.addPatchSchedule(psch);
} else if (!this.patchScheduleAdded) {
psch = this.patchSchedules.updateInlinePatchSchedule();
} else {
psch = this.patchSchedules.getPatchSchedule();
}
psch.inner().scheduleEntries().add(scheduleEntry);
return this;
}
@Override
public RedisCacheImpl withoutPatchSchedule() {
if (this.patchSchedules.patchSchedulesAsMap().isEmpty()) {
return this;
} else {
this.patchSchedules.deleteInlinePatchSchedule();
}
return this;
}
@Override
public void deletePatchSchedule() {
this.patchSchedules.removePatchSchedule();
this.patchSchedules.refresh();
}
@Override
public Mono<RedisCache> refreshAsync() {
return super
.refreshAsync()
.then(this.firewallRules.refreshAsync())
.then(this.patchSchedules.refreshAsync())
.then(Mono.just(this));
}
@Override
protected Mono<RedisResourceInner> getInnerAsync() {
return this.manager().inner().getRedis().getByResourceGroupAsync(this.resourceGroupName(), this.name());
}
@Override
public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) {
this.firewallRules.clear();
this.patchSchedules.clear();
this.patchScheduleAdded = false;
if (isGroupFaulted) {
return Mono.empty();
} else {
return this.refreshAsync().then();
}
}
@Override
public RedisCacheImpl update() {
this.updateParameters = new RedisUpdateParameters();
this.patchSchedules.enableCommitMode();
this.firewallRules.enableCommitMode();
return super.update();
}
@Override
@Override
public Mono<RedisCache> createResourceAsync() {
createParameters.withLocation(this.regionName());
createParameters.withTags(this.inner().tags());
this.patchScheduleAdded = false;
return this
.manager()
.inner()
.getRedis()
.createAsync(this.resourceGroupName(), this.name(), createParameters)
.map(innerToFluentMap(this));
}
@Override
public String addLinkedServer(String linkedRedisCacheId, String linkedServerLocation, ReplicationRole role) {
String linkedRedisName = ResourceUtils.nameFromResourceId(linkedRedisCacheId);
RedisLinkedServerCreateParameters params =
new RedisLinkedServerCreateParameters()
.withLinkedRedisCacheId(linkedRedisCacheId)
.withLinkedRedisCacheLocation(linkedServerLocation)
.withServerRole(role);
RedisLinkedServerWithPropertiesInner linkedServerInner =
this
.manager()
.inner()
.getLinkedServers()
.create(this.resourceGroupName(), this.name(), linkedRedisName, params);
return linkedServerInner.name();
}
@Override
public void removeLinkedServer(String linkedServerName) {
RedisLinkedServerWithPropertiesInner linkedServer =
this.manager().inner().getLinkedServers().get(this.resourceGroupName(), this.name(), linkedServerName);
this.manager().inner().getLinkedServers().delete(this.resourceGroupName(), this.name(), linkedServerName);
RedisResourceInner innerLinkedResource = null;
RedisResourceInner innerResource = null;
while (innerLinkedResource == null
|| innerLinkedResource.provisioningState() != ProvisioningState.SUCCEEDED
|| innerResource == null
|| innerResource.provisioningState() != ProvisioningState.SUCCEEDED) {
SdkContext.sleep(30 * 1000);
innerLinkedResource =
this
.manager()
.inner()
.getRedis()
.getByResourceGroup(
ResourceUtils.groupFromResourceId(linkedServer.id()),
ResourceUtils.nameFromResourceId(linkedServer.id()));
innerResource = this.manager().inner().getRedis().getByResourceGroup(resourceGroupName(), name());
}
}
@Override
public ReplicationRole getLinkedServerRole(String linkedServerName) {
RedisLinkedServerWithPropertiesInner linkedServer =
this.manager().inner().getLinkedServers().get(this.resourceGroupName(), this.name(), linkedServerName);
if (linkedServer == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"Server returned `null` value for Linked Server '"
+ linkedServerName
+ "' for Redis Cache '"
+ this.name()
+ "' in Resource Group '"
+ this.resourceGroupName()
+ "'."));
}
return linkedServer.serverRole();
}
@Override
public Map<String, ReplicationRole> listLinkedServers() {
Map<String, ReplicationRole> result = new TreeMap<>();
PagedIterable<RedisLinkedServerWithPropertiesInner> paginatedResponse =
this.manager().inner().getLinkedServers().list(this.resourceGroupName(), this.name());
for (RedisLinkedServerWithPropertiesInner linkedServer : paginatedResponse) {
result.put(linkedServer.name(), linkedServer.serverRole());
}
return result;
}
} |
Can we create a constant and name it as `DEFAULT_POLL_DURATION`? | Duration getPollDuration() {
return Duration.ofSeconds(1);
} | return Duration.ofSeconds(1); | Duration getPollDuration() {
return DEFAULT_POLL_DURATION;
} | class CertificateAsyncClient {
private final String apiVersion;
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault";
private final String vaultUrl;
private final CertificateService service;
private final ClientLogger logger = new ClientLogger(CertificateAsyncClient.class);
/**
* Creates a CertificateAsyncClient that uses {@code pipeline} to service requests
*
* @param vaultUrl URL for the Azure KeyVault service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CertificateServiceVersion} of the service to be used when making requests.
*/
CertificateAsyncClient(URL vaultUrl, HttpPipeline pipeline, CertificateServiceVersion version) {
Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED));
this.vaultUrl = vaultUrl.toString();
this.service = RestProxy.create(CertificateService.class, pipeline);
apiVersion = version.getVersion();
}
/**
* Get the vault endpoint url to which service requests are sent to.
* @return the vault endpoint url
*/
public String getVaultUrl() {
return vaultUrl;
}
/**
* Creates a new certificate. If this is the first version, the certificate resource is created. This operation requires
* the certificates/create permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Create certificate is a long running operation. The {@link PollerFlux poller} allows users to automatically poll on the create certificate
* operation status. It is possible to monitor each intermediate poll response during the poll operation.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.beginCreateCertificate
*
* @param certificateName The name of the certificate to be created.
* @param policy The policy of the certificate to be created.
* @param isEnabled The enabled status for the certificate.
* @param tags The application specific metadata to set.
* @throws ResourceModifiedException when invalid certificate policy configuration is provided.
* @return A {@link PollerFlux} polling on the create certificate operation status.
*/
public PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> beginCreateCertificate(String certificateName, CertificatePolicy policy, Boolean isEnabled, Map<String, String> tags) {
return new PollerFlux<>(getPollDuration(),
activationOperation(certificateName, policy, isEnabled, tags),
createPollOperation(certificateName),
cancelOperation(certificateName),
fetchResultOperation(certificateName));
}
private BiFunction<PollingContext<CertificateOperation>,
PollResponse<CertificateOperation>,
Mono<CertificateOperation>> cancelOperation(String certificateName) {
return (pollingContext, firstResponse) -> withContext(context
-> cancelCertificateOperationWithResponse(certificateName, context))
.flatMap(FluxUtil::toMono);
}
private Function<PollingContext<CertificateOperation>, Mono<CertificateOperation>> activationOperation(String certificateName,
CertificatePolicy policy,
boolean enabled,
Map<String, String> tags) {
return (pollingContext) -> withContext(context -> createCertificateWithResponse(certificateName,
policy,
enabled,
tags,
context))
.flatMap(certificateOperationResponse -> Mono.just(certificateOperationResponse.getValue()));
}
private Function<PollingContext<CertificateOperation>,
Mono<KeyVaultCertificateWithPolicy>> fetchResultOperation(String certificateName) {
return (pollingContext) -> withContext(context
-> getCertificateWithResponse(certificateName, "", context))
.flatMap(certificateResponse -> Mono.just(certificateResponse.getValue()));
}
/**
* Creates a new certificate. If this is the first version, the certificate resource is created. This operation requires
* the certificates/create permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Create certificate is a long running operation. The {@link PollerFlux poller} allows users to automatically poll on the create certificate
* operation status. It is possible to monitor each intermediate poll response during the poll operation.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.beginCreateCertificate
*
* @param certificateName The name of the certificate to be created.
* @param policy The policy of the certificate to be created.
* @throws ResourceModifiedException when invalid certificate policy configuration is provided.
* @return A {@link PollerFlux} polling on the create certificate operation status.
*/
public PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> beginCreateCertificate(String certificateName, CertificatePolicy policy) {
return beginCreateCertificate(certificateName, policy, true, null);
}
/*
Polling operation to poll on create certificate operation status.
*/
private Function<PollingContext<CertificateOperation>, Mono<PollResponse<CertificateOperation>>> createPollOperation(String certificateName) {
return (pollingContext) -> {
try {
return withContext(context -> service.getCertificateOperation(vaultUrl, certificateName, apiVersion,
ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)))
.flatMap(this::processCertificateOperationResponse);
} catch (HttpResponseException e) {
logger.logExceptionAsError(e);
return Mono.just(new PollResponse<>(LongRunningOperationStatus.FAILED, null));
}
};
}
private Mono<PollResponse<CertificateOperation>> processCertificateOperationResponse(Response<CertificateOperation> certificateOperationResponse) {
LongRunningOperationStatus status = null;
switch (certificateOperationResponse.getValue().getStatus()) {
case "inProgress":
status = LongRunningOperationStatus.IN_PROGRESS;
break;
case "completed":
status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED;
break;
case "failed":
status = LongRunningOperationStatus.FAILED;
break;
default:
status = LongRunningOperationStatus.fromString(certificateOperationResponse.getValue().getStatus(), true);
break;
}
return Mono.just(new PollResponse<>(status, certificateOperationResponse.getValue()));
}
Mono<Response<CertificateOperation>> createCertificateWithResponse(String certificateName, CertificatePolicy certificatePolicy, boolean enabled, Map<String, String> tags, Context context) {
CertificateRequestParameters certificateRequestParameters = new CertificateRequestParameters()
.certificatePolicy(new CertificatePolicyRequest(certificatePolicy))
.certificateAttributes(new CertificateRequestAttributes().enabled(enabled))
.tags(tags);
return service.createCertificate(vaultUrl, certificateName, apiVersion, ACCEPT_LANGUAGE, certificateRequestParameters, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE));
}
/**
* Gets a pending {@link CertificateOperation} from the key vault. This operation requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Get a pending certificate operation. The {@link PollerFlux poller} allows users to automatically poll on the certificate
* operation status. It is possible to monitor each intermediate poll response during the poll operation.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateOperation
*
* @param certificateName The name of the certificate.
* @throws ResourceNotFoundException when a certificate operation for a certificate with {@code certificateName} doesn't exist.
* @return A {@link PollerFlux} polling on the certificate operation status.
*/
public PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> getCertificateOperation(String certificateName) {
return new PollerFlux<>(getPollDuration(),
(pollingContext) -> Mono.empty(),
createPollOperation(certificateName),
cancelOperation(certificateName),
fetchResultOperation(certificateName));
}
/**
* Gets information about the latest version of the specified certificate. This operation requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the certificate in the key vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificate
*
* @param certificateName The name of the certificate to retrieve, cannot be null
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException if {@code certificateName} is empty string.
* @return A {@link Mono} containing the requested {@link KeyVaultCertificateWithPolicy certificate}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultCertificateWithPolicy> getCertificate(String certificateName) {
try {
return withContext(context -> getCertificateWithResponse(certificateName, "",
context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets information about the latest version of the specified certificate. This operation requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the certificate in the key vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateWithResponse
*
* @param certificateName The name of the certificate to retrieve, cannot be null
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException if {@code certificateName} is empty string.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultCertificateWithPolicy>> getCertificateWithResponse(String certificateName) {
try {
return withContext(context -> getCertificateWithResponse(certificateName, "", context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultCertificateWithPolicy>> getCertificateWithResponse(String certificateName, String version, Context context) {
context = context == null ? Context.NONE : context;
return service.getCertificateWithPolicy(vaultUrl, certificateName, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.info("Retrieving certificate - {}", certificateName))
.doOnSuccess(response -> logger.info("Retrieved the certificate - {}", response.getValue().getProperties().getName()))
.doOnError(error -> logger.warning("Failed to Retrieve the certificate - {}", certificateName, error));
}
Mono<Response<KeyVaultCertificate>> getCertificateVersionWithResponse(String certificateName, String version, Context context) {
context = context == null ? Context.NONE : context;
return service.getCertificate(vaultUrl, certificateName, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Retrieving certificate - {}", certificateName))
.doOnSuccess(response -> logger.info("Retrieved the certificate - {}", response.getValue().getProperties().getName()))
.doOnError(error -> logger.warning("Failed to Retrieve the certificate - {}", certificateName, error));
}
/**
* Gets information about the latest version of the specified certificate. This operation requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the certificate in the key vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateVersionWithResponse
*
* @param certificateName The name of the certificate to retrieve, cannot be null
* @param version The version of the certificate to retrieve. If this is an empty String or null then latest version of the certificate is retrieved.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException if {@code certificateName} is empty string.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultCertificate>> getCertificateVersionWithResponse(String certificateName, String version) {
try {
return withContext(context -> getCertificateVersionWithResponse(certificateName, version == null ? "" : version,
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets information about the specified version of the specified certificate. This operation requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the certificate in the key vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateVersion
*
* @param certificateName The name of the certificate to retrieve, cannot be null
* @param version The version of the certificate to retrieve. If this is an empty String or null then latest version of the certificate is retrieved.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException if {@code certificateName} is empty string.
* @return A {@link Mono} containing the requested {@link KeyVaultCertificate certificate}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultCertificate> getCertificateVersion(String certificateName, String version) {
try {
return withContext(context -> getCertificateVersionWithResponse(certificateName, version == null ? "" : version,
context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates the specified attributes associated with the specified certificate. The update operation changes specified attributes of an existing
* stored certificate and attributes that are not specified in the request are left unchanged. This operation requires the certificates/update permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the certificate, changes its tags and enabled status and then updates it in the Azure Key Vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificateProperties
*
* @param properties The {@link CertificateProperties} object with updated properties.
* @throws NullPointerException if {@code certificate} is {@code null}.
* @throws ResourceNotFoundException when a certificate with {@link CertificateProperties
* @throws HttpResponseException if {@link CertificateProperties
* @return A {@link Mono} containing the {@link CertificateProperties updated certificate}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultCertificate> updateCertificateProperties(CertificateProperties properties) {
try {
return withContext(context -> updateCertificatePropertiesWithResponse(properties, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates the specified attributes associated with the specified certificate. The update operation changes specified attributes of an existing
* stored certificate and attributes that are not specified in the request are left unchanged. This operation requires the certificates/update permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the certificate, changes its enabled status and then updates it in the Azure Key Vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificatePropertiesWithResponse
*
* @param properties The {@link CertificateProperties} object with updated properties.
* @throws NullPointerException if {@code properties} is {@code null}.
* @throws ResourceNotFoundException when a certificate with {@link CertificateProperties
* @throws HttpResponseException if {@link CertificateProperties
* @return A {@link Mono} containing a {@link Response} whose {@link Response
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultCertificate>> updateCertificatePropertiesWithResponse(CertificateProperties properties) {
try {
return withContext(context -> updateCertificatePropertiesWithResponse(properties,
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultCertificate>> updateCertificatePropertiesWithResponse(CertificateProperties properties, Context context) {
context = context == null ? Context.NONE : context;
Objects.requireNonNull(properties, "properties' cannot be null.");
CertificateUpdateParameters parameters = new CertificateUpdateParameters()
.tags(properties.getTags())
.certificateAttributes(new CertificateRequestAttributes(properties));
return service.updateCertificate(vaultUrl, properties.getName(), properties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.info("Updating certificate - {}", properties.getName()))
.doOnSuccess(response -> logger.info("Updated the certificate - {}", properties.getName()))
.doOnError(error -> logger.warning("Failed to update the certificate - {}", properties.getName(), error));
}
/**
* Deletes a certificate from a specified key vault. All the versions of the certificate along with its associated policy
* get deleted. If soft-delete is enabled on the key vault then the certificate is placed in the deleted state and requires to be
* purged for permanent deletion else the certificate is permanently deleted. The delete operation applies to any certificate stored in
* Azure Key Vault but it cannot be applied to an individual version of a certificate. This operation requires the certificates/delete permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Deletes the certificate in the Azure Key Vault. Prints out the deleted certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.beginDeleteCertificate
*
* @param certificateName The name of the certificate to be deleted.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException when a certificate with {@code certificateName} is empty string.
* @return A {@link PollerFlux} to poll on the {@link DeletedCertificate deleted certificate}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public PollerFlux<DeletedCertificate, Void> beginDeleteCertificate(String certificateName) {
return new PollerFlux<>(getPollDuration(),
activationOperation(certificateName),
createDeletePollOperation(certificateName),
(context, firstResponse) -> Mono.empty(),
(context) -> Mono.empty());
}
private Function<PollingContext<DeletedCertificate>, Mono<DeletedCertificate>> activationOperation(String certificateName) {
return (pollingContext) -> withContext(context -> deleteCertificateWithResponse(certificateName,
context))
.flatMap(deletedCertificateResponse -> Mono.just(deletedCertificateResponse.getValue()));
}
/*
Polling operation to poll on create delete certificate operation status.
*/
private Function<PollingContext<DeletedCertificate>, Mono<PollResponse<DeletedCertificate>>> createDeletePollOperation(String keyName) {
return pollingContext ->
withContext(context -> service.getDeletedCertificatePoller(vaultUrl, keyName, apiVersion,
ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)))
.flatMap(deletedCertificateResponse -> {
if (deletedCertificateResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS,
pollingContext.getLatestResponse().getValue())));
}
if (deletedCertificateResponse.getStatusCode() == HttpURLConnection.HTTP_FORBIDDEN) {
return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED,
pollingContext.getLatestResponse().getValue())));
}
return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedCertificateResponse.getValue())));
})
.onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()));
}
Mono<Response<DeletedCertificate>> deleteCertificateWithResponse(String certificateName, Context context) {
return service.deleteCertificate(vaultUrl, certificateName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.info("Deleting certificate - {}", certificateName))
.doOnSuccess(response -> logger.info("Deleted the certificate - {}", response.getValue().getProperties().getName()))
.doOnError(error -> logger.warning("Failed to delete the certificate - {}", certificateName, error));
}
/**
* Retrieves information about the specified deleted certificate. The GetDeletedCertificate operation is applicable for soft-delete
* enabled vaults and additionally retrieves deleted certificate's attributes, such as retention interval, scheduled permanent deletion and the current deletion recovery level. This operation
* requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p> Gets the deleted certificate from the key vault enabled for soft-delete. Prints out the
* deleted certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getDeletedCertificate
*
* @param certificateName The name of the deleted certificate.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException when a certificate with {@code certificateName} is empty string.
* @return A {@link Mono} containing the {@link DeletedCertificate deleted certificate}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeletedCertificate> getDeletedCertificate(String certificateName) {
try {
return withContext(context -> getDeletedCertificateWithResponse(certificateName, context))
.flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Retrieves information about the specified deleted certificate. The GetDeletedCertificate operation is applicable for soft-delete
* enabled vaults and additionally retrieves deleted certificate's attributes, such as retention interval, scheduled permanent deletion and the current deletion recovery level. This operation
* requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p> Gets the deleted certificate from the key vault enabled for soft-delete. Prints out the
* deleted certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getDeletedCertificateWithResponse
*
* @param certificateName The name of the deleted certificate.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException when a certificate with {@code certificateName} is empty string.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeletedCertificate>> getDeletedCertificateWithResponse(String certificateName) {
try {
return withContext(context -> getDeletedCertificateWithResponse(certificateName, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DeletedCertificate>> getDeletedCertificateWithResponse(String certificateName, Context context) {
context = context == null ? Context.NONE : context;
return service.getDeletedCertificate(vaultUrl, certificateName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.info("Retrieving deleted certificate - {}", certificateName))
.doOnSuccess(response -> logger.info("Retrieved the deleted certificate - {}", response.getValue().getProperties().getName()))
.doOnError(error -> logger.warning("Failed to Retrieve the deleted certificate - {}", certificateName, error));
}
/**
* Permanently deletes the specified deleted certificate without possibility for recovery. The Purge Deleted Certificate operation is applicable for
* soft-delete enabled vaults and is not available if the recovery level does not specify 'Purgeable'. This operation requires the certificate/purge permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Purges the deleted certificate from the key vault enabled for soft-delete. Prints out the
* status code from the server response when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.purgeDeletedCertificateWithResponse
*
* @param certificateName The name of the deleted certificate.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException when a certificate with {@code certificateName} is empty string.
* @return An empty {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> purgeDeletedCertificate(String certificateName) {
try {
return purgeDeletedCertificateWithResponse(certificateName).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Permanently deletes the specified deleted certificate without possibility for recovery. The Purge Deleted Certificate operation is applicable for
* soft-delete enabled vaults and is not available if the recovery level does not specify 'Purgeable'. This operation requires the certificate/purge permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Purges the deleted certificate from the key vault enabled for soft-delete. Prints out the
* status code from the server response when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.purgeDeletedCertificateWithResponse
*
* @param certificateName The name of the deleted certificate.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException when a certificate with {@code certificateName} is empty string.
* @return A {@link Mono} containing a Void Response} | class CertificateAsyncClient {
private final String apiVersion;
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault";
private static final Duration DEFAULT_POLL_DURATION = Duration.ofSeconds(1);
private final String vaultUrl;
private final CertificateService service;
private final ClientLogger logger = new ClientLogger(CertificateAsyncClient.class);
/**
* Creates a CertificateAsyncClient that uses {@code pipeline} to service requests
*
* @param vaultUrl URL for the Azure KeyVault service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CertificateServiceVersion} of the service to be used when making requests.
*/
CertificateAsyncClient(URL vaultUrl, HttpPipeline pipeline, CertificateServiceVersion version) {
Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED));
this.vaultUrl = vaultUrl.toString();
this.service = RestProxy.create(CertificateService.class, pipeline);
apiVersion = version.getVersion();
}
/**
* Get the vault endpoint url to which service requests are sent to.
* @return the vault endpoint url
*/
public String getVaultUrl() {
return vaultUrl;
}
/**
* Creates a new certificate. If this is the first version, the certificate resource is created. This operation requires
* the certificates/create permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Create certificate is a long running operation. The {@link PollerFlux poller} allows users to automatically poll on the create certificate
* operation status. It is possible to monitor each intermediate poll response during the poll operation.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.beginCreateCertificate
*
* @param certificateName The name of the certificate to be created.
* @param policy The policy of the certificate to be created.
* @param isEnabled The enabled status for the certificate.
* @param tags The application specific metadata to set.
* @throws ResourceModifiedException when invalid certificate policy configuration is provided.
* @return A {@link PollerFlux} polling on the create certificate operation status.
*/
public PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> beginCreateCertificate(String certificateName, CertificatePolicy policy, Boolean isEnabled, Map<String, String> tags) {
return new PollerFlux<>(getPollDuration(),
activationOperation(certificateName, policy, isEnabled, tags),
createPollOperation(certificateName),
cancelOperation(certificateName),
fetchResultOperation(certificateName));
}
private BiFunction<PollingContext<CertificateOperation>,
PollResponse<CertificateOperation>,
Mono<CertificateOperation>> cancelOperation(String certificateName) {
return (pollingContext, firstResponse) -> withContext(context
-> cancelCertificateOperationWithResponse(certificateName, context))
.flatMap(FluxUtil::toMono);
}
private Function<PollingContext<CertificateOperation>, Mono<CertificateOperation>> activationOperation(String certificateName,
CertificatePolicy policy,
boolean enabled,
Map<String, String> tags) {
return (pollingContext) -> withContext(context -> createCertificateWithResponse(certificateName,
policy,
enabled,
tags,
context))
.flatMap(certificateOperationResponse -> Mono.just(certificateOperationResponse.getValue()));
}
private Function<PollingContext<CertificateOperation>,
Mono<KeyVaultCertificateWithPolicy>> fetchResultOperation(String certificateName) {
return (pollingContext) -> withContext(context
-> getCertificateWithResponse(certificateName, "", context))
.flatMap(certificateResponse -> Mono.just(certificateResponse.getValue()));
}
/**
* Creates a new certificate. If this is the first version, the certificate resource is created. This operation requires
* the certificates/create permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Create certificate is a long running operation. The {@link PollerFlux poller} allows users to automatically poll on the create certificate
* operation status. It is possible to monitor each intermediate poll response during the poll operation.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.beginCreateCertificate
*
* @param certificateName The name of the certificate to be created.
* @param policy The policy of the certificate to be created.
* @throws ResourceModifiedException when invalid certificate policy configuration is provided.
* @return A {@link PollerFlux} polling on the create certificate operation status.
*/
public PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> beginCreateCertificate(String certificateName, CertificatePolicy policy) {
return beginCreateCertificate(certificateName, policy, true, null);
}
/*
Polling operation to poll on create certificate operation status.
*/
private Function<PollingContext<CertificateOperation>, Mono<PollResponse<CertificateOperation>>> createPollOperation(String certificateName) {
return (pollingContext) -> {
try {
return withContext(context -> service.getCertificateOperation(vaultUrl, certificateName, apiVersion,
ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)))
.flatMap(this::processCertificateOperationResponse);
} catch (HttpResponseException e) {
logger.logExceptionAsError(e);
return Mono.just(new PollResponse<>(LongRunningOperationStatus.FAILED, null));
}
};
}
private Mono<PollResponse<CertificateOperation>> processCertificateOperationResponse(Response<CertificateOperation> certificateOperationResponse) {
LongRunningOperationStatus status = null;
switch (certificateOperationResponse.getValue().getStatus()) {
case "inProgress":
status = LongRunningOperationStatus.IN_PROGRESS;
break;
case "completed":
status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED;
break;
case "failed":
status = LongRunningOperationStatus.FAILED;
break;
default:
status = LongRunningOperationStatus.fromString(certificateOperationResponse.getValue().getStatus(), true);
break;
}
return Mono.just(new PollResponse<>(status, certificateOperationResponse.getValue()));
}
Mono<Response<CertificateOperation>> createCertificateWithResponse(String certificateName, CertificatePolicy certificatePolicy, boolean enabled, Map<String, String> tags, Context context) {
CertificateRequestParameters certificateRequestParameters = new CertificateRequestParameters()
.certificatePolicy(new CertificatePolicyRequest(certificatePolicy))
.certificateAttributes(new CertificateRequestAttributes().enabled(enabled))
.tags(tags);
return service.createCertificate(vaultUrl, certificateName, apiVersion, ACCEPT_LANGUAGE, certificateRequestParameters, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE));
}
/**
* Gets a pending {@link CertificateOperation} from the key vault. This operation requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Get a pending certificate operation. The {@link PollerFlux poller} allows users to automatically poll on the certificate
* operation status. It is possible to monitor each intermediate poll response during the poll operation.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateOperation
*
* @param certificateName The name of the certificate.
* @throws ResourceNotFoundException when a certificate operation for a certificate with {@code certificateName} doesn't exist.
* @return A {@link PollerFlux} polling on the certificate operation status.
*/
public PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> getCertificateOperation(String certificateName) {
return new PollerFlux<>(getPollDuration(),
(pollingContext) -> Mono.empty(),
createPollOperation(certificateName),
cancelOperation(certificateName),
fetchResultOperation(certificateName));
}
/**
* Gets information about the latest version of the specified certificate. This operation requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the certificate in the key vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificate
*
* @param certificateName The name of the certificate to retrieve, cannot be null
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException if {@code certificateName} is empty string.
* @return A {@link Mono} containing the requested {@link KeyVaultCertificateWithPolicy certificate}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultCertificateWithPolicy> getCertificate(String certificateName) {
try {
return withContext(context -> getCertificateWithResponse(certificateName, "",
context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets information about the latest version of the specified certificate. This operation requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the certificate in the key vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateWithResponse
*
* @param certificateName The name of the certificate to retrieve, cannot be null
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException if {@code certificateName} is empty string.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultCertificateWithPolicy>> getCertificateWithResponse(String certificateName) {
try {
return withContext(context -> getCertificateWithResponse(certificateName, "", context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultCertificateWithPolicy>> getCertificateWithResponse(String certificateName, String version, Context context) {
context = context == null ? Context.NONE : context;
return service.getCertificateWithPolicy(vaultUrl, certificateName, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.info("Retrieving certificate - {}", certificateName))
.doOnSuccess(response -> logger.info("Retrieved the certificate - {}", response.getValue().getProperties().getName()))
.doOnError(error -> logger.warning("Failed to Retrieve the certificate - {}", certificateName, error));
}
Mono<Response<KeyVaultCertificate>> getCertificateVersionWithResponse(String certificateName, String version, Context context) {
context = context == null ? Context.NONE : context;
return service.getCertificate(vaultUrl, certificateName, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Retrieving certificate - {}", certificateName))
.doOnSuccess(response -> logger.info("Retrieved the certificate - {}", response.getValue().getProperties().getName()))
.doOnError(error -> logger.warning("Failed to Retrieve the certificate - {}", certificateName, error));
}
/**
* Gets information about the latest version of the specified certificate. This operation requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the certificate in the key vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateVersionWithResponse
*
* @param certificateName The name of the certificate to retrieve, cannot be null
* @param version The version of the certificate to retrieve. If this is an empty String or null then latest version of the certificate is retrieved.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException if {@code certificateName} is empty string.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultCertificate>> getCertificateVersionWithResponse(String certificateName, String version) {
try {
return withContext(context -> getCertificateVersionWithResponse(certificateName, version == null ? "" : version,
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets information about the specified version of the specified certificate. This operation requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the certificate in the key vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateVersion
*
* @param certificateName The name of the certificate to retrieve, cannot be null
* @param version The version of the certificate to retrieve. If this is an empty String or null then latest version of the certificate is retrieved.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException if {@code certificateName} is empty string.
* @return A {@link Mono} containing the requested {@link KeyVaultCertificate certificate}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultCertificate> getCertificateVersion(String certificateName, String version) {
try {
return withContext(context -> getCertificateVersionWithResponse(certificateName, version == null ? "" : version,
context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates the specified attributes associated with the specified certificate. The update operation changes specified attributes of an existing
* stored certificate and attributes that are not specified in the request are left unchanged. This operation requires the certificates/update permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the certificate, changes its tags and enabled status and then updates it in the Azure Key Vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificateProperties
*
* @param properties The {@link CertificateProperties} object with updated properties.
* @throws NullPointerException if {@code certificate} is {@code null}.
* @throws ResourceNotFoundException when a certificate with {@link CertificateProperties
* @throws HttpResponseException if {@link CertificateProperties
* @return A {@link Mono} containing the {@link CertificateProperties updated certificate}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultCertificate> updateCertificateProperties(CertificateProperties properties) {
try {
return withContext(context -> updateCertificatePropertiesWithResponse(properties, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates the specified attributes associated with the specified certificate. The update operation changes specified attributes of an existing
* stored certificate and attributes that are not specified in the request are left unchanged. This operation requires the certificates/update permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the certificate, changes its enabled status and then updates it in the Azure Key Vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificatePropertiesWithResponse
*
* @param properties The {@link CertificateProperties} object with updated properties.
* @throws NullPointerException if {@code properties} is {@code null}.
* @throws ResourceNotFoundException when a certificate with {@link CertificateProperties
* @throws HttpResponseException if {@link CertificateProperties
* @return A {@link Mono} containing a {@link Response} whose {@link Response
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultCertificate>> updateCertificatePropertiesWithResponse(CertificateProperties properties) {
try {
return withContext(context -> updateCertificatePropertiesWithResponse(properties,
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultCertificate>> updateCertificatePropertiesWithResponse(CertificateProperties properties, Context context) {
context = context == null ? Context.NONE : context;
Objects.requireNonNull(properties, "properties' cannot be null.");
CertificateUpdateParameters parameters = new CertificateUpdateParameters()
.tags(properties.getTags())
.certificateAttributes(new CertificateRequestAttributes(properties));
return service.updateCertificate(vaultUrl, properties.getName(), properties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.info("Updating certificate - {}", properties.getName()))
.doOnSuccess(response -> logger.info("Updated the certificate - {}", properties.getName()))
.doOnError(error -> logger.warning("Failed to update the certificate - {}", properties.getName(), error));
}
/**
* Deletes a certificate from a specified key vault. All the versions of the certificate along with its associated policy
* get deleted. If soft-delete is enabled on the key vault then the certificate is placed in the deleted state and requires to be
* purged for permanent deletion else the certificate is permanently deleted. The delete operation applies to any certificate stored in
* Azure Key Vault but it cannot be applied to an individual version of a certificate. This operation requires the certificates/delete permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Deletes the certificate in the Azure Key Vault. Prints out the deleted certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.beginDeleteCertificate
*
* @param certificateName The name of the certificate to be deleted.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException when a certificate with {@code certificateName} is empty string.
* @return A {@link PollerFlux} to poll on the {@link DeletedCertificate deleted certificate}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public PollerFlux<DeletedCertificate, Void> beginDeleteCertificate(String certificateName) {
return new PollerFlux<>(getPollDuration(),
activationOperation(certificateName),
createDeletePollOperation(certificateName),
(context, firstResponse) -> Mono.empty(),
(context) -> Mono.empty());
}
private Function<PollingContext<DeletedCertificate>, Mono<DeletedCertificate>> activationOperation(String certificateName) {
return (pollingContext) -> withContext(context -> deleteCertificateWithResponse(certificateName,
context))
.flatMap(deletedCertificateResponse -> Mono.just(deletedCertificateResponse.getValue()));
}
/*
Polling operation to poll on create delete certificate operation status.
*/
private Function<PollingContext<DeletedCertificate>, Mono<PollResponse<DeletedCertificate>>> createDeletePollOperation(String keyName) {
return pollingContext ->
withContext(context -> service.getDeletedCertificatePoller(vaultUrl, keyName, apiVersion,
ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)))
.flatMap(deletedCertificateResponse -> {
if (deletedCertificateResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS,
pollingContext.getLatestResponse().getValue())));
}
if (deletedCertificateResponse.getStatusCode() == HttpURLConnection.HTTP_FORBIDDEN) {
return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED,
pollingContext.getLatestResponse().getValue())));
}
return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedCertificateResponse.getValue())));
})
.onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()));
}
Mono<Response<DeletedCertificate>> deleteCertificateWithResponse(String certificateName, Context context) {
return service.deleteCertificate(vaultUrl, certificateName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.info("Deleting certificate - {}", certificateName))
.doOnSuccess(response -> logger.info("Deleted the certificate - {}", response.getValue().getProperties().getName()))
.doOnError(error -> logger.warning("Failed to delete the certificate - {}", certificateName, error));
}
/**
* Retrieves information about the specified deleted certificate. The GetDeletedCertificate operation is applicable for soft-delete
* enabled vaults and additionally retrieves deleted certificate's attributes, such as retention interval, scheduled permanent deletion and the current deletion recovery level. This operation
* requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p> Gets the deleted certificate from the key vault enabled for soft-delete. Prints out the
* deleted certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getDeletedCertificate
*
* @param certificateName The name of the deleted certificate.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException when a certificate with {@code certificateName} is empty string.
* @return A {@link Mono} containing the {@link DeletedCertificate deleted certificate}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeletedCertificate> getDeletedCertificate(String certificateName) {
try {
return withContext(context -> getDeletedCertificateWithResponse(certificateName, context))
.flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Retrieves information about the specified deleted certificate. The GetDeletedCertificate operation is applicable for soft-delete
* enabled vaults and additionally retrieves deleted certificate's attributes, such as retention interval, scheduled permanent deletion and the current deletion recovery level. This operation
* requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p> Gets the deleted certificate from the key vault enabled for soft-delete. Prints out the
* deleted certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getDeletedCertificateWithResponse
*
* @param certificateName The name of the deleted certificate.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException when a certificate with {@code certificateName} is empty string.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeletedCertificate>> getDeletedCertificateWithResponse(String certificateName) {
try {
return withContext(context -> getDeletedCertificateWithResponse(certificateName, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DeletedCertificate>> getDeletedCertificateWithResponse(String certificateName, Context context) {
context = context == null ? Context.NONE : context;
return service.getDeletedCertificate(vaultUrl, certificateName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.info("Retrieving deleted certificate - {}", certificateName))
.doOnSuccess(response -> logger.info("Retrieved the deleted certificate - {}", response.getValue().getProperties().getName()))
.doOnError(error -> logger.warning("Failed to Retrieve the deleted certificate - {}", certificateName, error));
}
/**
* Permanently deletes the specified deleted certificate without possibility for recovery. The Purge Deleted Certificate operation is applicable for
* soft-delete enabled vaults and is not available if the recovery level does not specify 'Purgeable'. This operation requires the certificate/purge permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Purges the deleted certificate from the key vault enabled for soft-delete. Prints out the
* status code from the server response when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.purgeDeletedCertificateWithResponse
*
* @param certificateName The name of the deleted certificate.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException when a certificate with {@code certificateName} is empty string.
* @return An empty {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> purgeDeletedCertificate(String certificateName) {
try {
return purgeDeletedCertificateWithResponse(certificateName).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Permanently deletes the specified deleted certificate without possibility for recovery. The Purge Deleted Certificate operation is applicable for
* soft-delete enabled vaults and is not available if the recovery level does not specify 'Purgeable'. This operation requires the certificate/purge permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Purges the deleted certificate from the key vault enabled for soft-delete. Prints out the
* status code from the server response when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.purgeDeletedCertificateWithResponse
*
* @param certificateName The name of the deleted certificate.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException when a certificate with {@code certificateName} is empty string.
* @return A {@link Mono} containing a Void Response} |
Done | Duration getPollDuration() {
return Duration.ofSeconds(1);
} | return Duration.ofSeconds(1); | Duration getPollDuration() {
return DEFAULT_POLL_DURATION;
} | class CertificateAsyncClient {
private final String apiVersion;
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault";
private final String vaultUrl;
private final CertificateService service;
private final ClientLogger logger = new ClientLogger(CertificateAsyncClient.class);
/**
* Creates a CertificateAsyncClient that uses {@code pipeline} to service requests
*
* @param vaultUrl URL for the Azure KeyVault service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CertificateServiceVersion} of the service to be used when making requests.
*/
CertificateAsyncClient(URL vaultUrl, HttpPipeline pipeline, CertificateServiceVersion version) {
Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED));
this.vaultUrl = vaultUrl.toString();
this.service = RestProxy.create(CertificateService.class, pipeline);
apiVersion = version.getVersion();
}
/**
* Get the vault endpoint url to which service requests are sent to.
* @return the vault endpoint url
*/
public String getVaultUrl() {
return vaultUrl;
}
/**
* Creates a new certificate. If this is the first version, the certificate resource is created. This operation requires
* the certificates/create permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Create certificate is a long running operation. The {@link PollerFlux poller} allows users to automatically poll on the create certificate
* operation status. It is possible to monitor each intermediate poll response during the poll operation.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.beginCreateCertificate
*
* @param certificateName The name of the certificate to be created.
* @param policy The policy of the certificate to be created.
* @param isEnabled The enabled status for the certificate.
* @param tags The application specific metadata to set.
* @throws ResourceModifiedException when invalid certificate policy configuration is provided.
* @return A {@link PollerFlux} polling on the create certificate operation status.
*/
public PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> beginCreateCertificate(String certificateName, CertificatePolicy policy, Boolean isEnabled, Map<String, String> tags) {
return new PollerFlux<>(getPollDuration(),
activationOperation(certificateName, policy, isEnabled, tags),
createPollOperation(certificateName),
cancelOperation(certificateName),
fetchResultOperation(certificateName));
}
private BiFunction<PollingContext<CertificateOperation>,
PollResponse<CertificateOperation>,
Mono<CertificateOperation>> cancelOperation(String certificateName) {
return (pollingContext, firstResponse) -> withContext(context
-> cancelCertificateOperationWithResponse(certificateName, context))
.flatMap(FluxUtil::toMono);
}
private Function<PollingContext<CertificateOperation>, Mono<CertificateOperation>> activationOperation(String certificateName,
CertificatePolicy policy,
boolean enabled,
Map<String, String> tags) {
return (pollingContext) -> withContext(context -> createCertificateWithResponse(certificateName,
policy,
enabled,
tags,
context))
.flatMap(certificateOperationResponse -> Mono.just(certificateOperationResponse.getValue()));
}
private Function<PollingContext<CertificateOperation>,
Mono<KeyVaultCertificateWithPolicy>> fetchResultOperation(String certificateName) {
return (pollingContext) -> withContext(context
-> getCertificateWithResponse(certificateName, "", context))
.flatMap(certificateResponse -> Mono.just(certificateResponse.getValue()));
}
/**
* Creates a new certificate. If this is the first version, the certificate resource is created. This operation requires
* the certificates/create permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Create certificate is a long running operation. The {@link PollerFlux poller} allows users to automatically poll on the create certificate
* operation status. It is possible to monitor each intermediate poll response during the poll operation.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.beginCreateCertificate
*
* @param certificateName The name of the certificate to be created.
* @param policy The policy of the certificate to be created.
* @throws ResourceModifiedException when invalid certificate policy configuration is provided.
* @return A {@link PollerFlux} polling on the create certificate operation status.
*/
public PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> beginCreateCertificate(String certificateName, CertificatePolicy policy) {
return beginCreateCertificate(certificateName, policy, true, null);
}
/*
Polling operation to poll on create certificate operation status.
*/
private Function<PollingContext<CertificateOperation>, Mono<PollResponse<CertificateOperation>>> createPollOperation(String certificateName) {
return (pollingContext) -> {
try {
return withContext(context -> service.getCertificateOperation(vaultUrl, certificateName, apiVersion,
ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)))
.flatMap(this::processCertificateOperationResponse);
} catch (HttpResponseException e) {
logger.logExceptionAsError(e);
return Mono.just(new PollResponse<>(LongRunningOperationStatus.FAILED, null));
}
};
}
private Mono<PollResponse<CertificateOperation>> processCertificateOperationResponse(Response<CertificateOperation> certificateOperationResponse) {
LongRunningOperationStatus status = null;
switch (certificateOperationResponse.getValue().getStatus()) {
case "inProgress":
status = LongRunningOperationStatus.IN_PROGRESS;
break;
case "completed":
status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED;
break;
case "failed":
status = LongRunningOperationStatus.FAILED;
break;
default:
status = LongRunningOperationStatus.fromString(certificateOperationResponse.getValue().getStatus(), true);
break;
}
return Mono.just(new PollResponse<>(status, certificateOperationResponse.getValue()));
}
Mono<Response<CertificateOperation>> createCertificateWithResponse(String certificateName, CertificatePolicy certificatePolicy, boolean enabled, Map<String, String> tags, Context context) {
CertificateRequestParameters certificateRequestParameters = new CertificateRequestParameters()
.certificatePolicy(new CertificatePolicyRequest(certificatePolicy))
.certificateAttributes(new CertificateRequestAttributes().enabled(enabled))
.tags(tags);
return service.createCertificate(vaultUrl, certificateName, apiVersion, ACCEPT_LANGUAGE, certificateRequestParameters, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE));
}
/**
* Gets a pending {@link CertificateOperation} from the key vault. This operation requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Get a pending certificate operation. The {@link PollerFlux poller} allows users to automatically poll on the certificate
* operation status. It is possible to monitor each intermediate poll response during the poll operation.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateOperation
*
* @param certificateName The name of the certificate.
* @throws ResourceNotFoundException when a certificate operation for a certificate with {@code certificateName} doesn't exist.
* @return A {@link PollerFlux} polling on the certificate operation status.
*/
public PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> getCertificateOperation(String certificateName) {
return new PollerFlux<>(getPollDuration(),
(pollingContext) -> Mono.empty(),
createPollOperation(certificateName),
cancelOperation(certificateName),
fetchResultOperation(certificateName));
}
/**
* Gets information about the latest version of the specified certificate. This operation requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the certificate in the key vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificate
*
* @param certificateName The name of the certificate to retrieve, cannot be null
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException if {@code certificateName} is empty string.
* @return A {@link Mono} containing the requested {@link KeyVaultCertificateWithPolicy certificate}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultCertificateWithPolicy> getCertificate(String certificateName) {
try {
return withContext(context -> getCertificateWithResponse(certificateName, "",
context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets information about the latest version of the specified certificate. This operation requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the certificate in the key vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateWithResponse
*
* @param certificateName The name of the certificate to retrieve, cannot be null
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException if {@code certificateName} is empty string.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultCertificateWithPolicy>> getCertificateWithResponse(String certificateName) {
try {
return withContext(context -> getCertificateWithResponse(certificateName, "", context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultCertificateWithPolicy>> getCertificateWithResponse(String certificateName, String version, Context context) {
context = context == null ? Context.NONE : context;
return service.getCertificateWithPolicy(vaultUrl, certificateName, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.info("Retrieving certificate - {}", certificateName))
.doOnSuccess(response -> logger.info("Retrieved the certificate - {}", response.getValue().getProperties().getName()))
.doOnError(error -> logger.warning("Failed to Retrieve the certificate - {}", certificateName, error));
}
Mono<Response<KeyVaultCertificate>> getCertificateVersionWithResponse(String certificateName, String version, Context context) {
context = context == null ? Context.NONE : context;
return service.getCertificate(vaultUrl, certificateName, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Retrieving certificate - {}", certificateName))
.doOnSuccess(response -> logger.info("Retrieved the certificate - {}", response.getValue().getProperties().getName()))
.doOnError(error -> logger.warning("Failed to Retrieve the certificate - {}", certificateName, error));
}
/**
* Gets information about the latest version of the specified certificate. This operation requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the certificate in the key vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateVersionWithResponse
*
* @param certificateName The name of the certificate to retrieve, cannot be null
* @param version The version of the certificate to retrieve. If this is an empty String or null then latest version of the certificate is retrieved.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException if {@code certificateName} is empty string.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultCertificate>> getCertificateVersionWithResponse(String certificateName, String version) {
try {
return withContext(context -> getCertificateVersionWithResponse(certificateName, version == null ? "" : version,
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets information about the specified version of the specified certificate. This operation requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the certificate in the key vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateVersion
*
* @param certificateName The name of the certificate to retrieve, cannot be null
* @param version The version of the certificate to retrieve. If this is an empty String or null then latest version of the certificate is retrieved.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException if {@code certificateName} is empty string.
* @return A {@link Mono} containing the requested {@link KeyVaultCertificate certificate}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultCertificate> getCertificateVersion(String certificateName, String version) {
try {
return withContext(context -> getCertificateVersionWithResponse(certificateName, version == null ? "" : version,
context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates the specified attributes associated with the specified certificate. The update operation changes specified attributes of an existing
* stored certificate and attributes that are not specified in the request are left unchanged. This operation requires the certificates/update permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the certificate, changes its tags and enabled status and then updates it in the Azure Key Vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificateProperties
*
* @param properties The {@link CertificateProperties} object with updated properties.
* @throws NullPointerException if {@code certificate} is {@code null}.
* @throws ResourceNotFoundException when a certificate with {@link CertificateProperties
* @throws HttpResponseException if {@link CertificateProperties
* @return A {@link Mono} containing the {@link CertificateProperties updated certificate}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultCertificate> updateCertificateProperties(CertificateProperties properties) {
try {
return withContext(context -> updateCertificatePropertiesWithResponse(properties, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates the specified attributes associated with the specified certificate. The update operation changes specified attributes of an existing
* stored certificate and attributes that are not specified in the request are left unchanged. This operation requires the certificates/update permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the certificate, changes its enabled status and then updates it in the Azure Key Vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificatePropertiesWithResponse
*
* @param properties The {@link CertificateProperties} object with updated properties.
* @throws NullPointerException if {@code properties} is {@code null}.
* @throws ResourceNotFoundException when a certificate with {@link CertificateProperties
* @throws HttpResponseException if {@link CertificateProperties
* @return A {@link Mono} containing a {@link Response} whose {@link Response
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultCertificate>> updateCertificatePropertiesWithResponse(CertificateProperties properties) {
try {
return withContext(context -> updateCertificatePropertiesWithResponse(properties,
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultCertificate>> updateCertificatePropertiesWithResponse(CertificateProperties properties, Context context) {
context = context == null ? Context.NONE : context;
Objects.requireNonNull(properties, "properties' cannot be null.");
CertificateUpdateParameters parameters = new CertificateUpdateParameters()
.tags(properties.getTags())
.certificateAttributes(new CertificateRequestAttributes(properties));
return service.updateCertificate(vaultUrl, properties.getName(), properties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.info("Updating certificate - {}", properties.getName()))
.doOnSuccess(response -> logger.info("Updated the certificate - {}", properties.getName()))
.doOnError(error -> logger.warning("Failed to update the certificate - {}", properties.getName(), error));
}
/**
* Deletes a certificate from a specified key vault. All the versions of the certificate along with its associated policy
* get deleted. If soft-delete is enabled on the key vault then the certificate is placed in the deleted state and requires to be
* purged for permanent deletion else the certificate is permanently deleted. The delete operation applies to any certificate stored in
* Azure Key Vault but it cannot be applied to an individual version of a certificate. This operation requires the certificates/delete permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Deletes the certificate in the Azure Key Vault. Prints out the deleted certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.beginDeleteCertificate
*
* @param certificateName The name of the certificate to be deleted.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException when a certificate with {@code certificateName} is empty string.
* @return A {@link PollerFlux} to poll on the {@link DeletedCertificate deleted certificate}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public PollerFlux<DeletedCertificate, Void> beginDeleteCertificate(String certificateName) {
return new PollerFlux<>(getPollDuration(),
activationOperation(certificateName),
createDeletePollOperation(certificateName),
(context, firstResponse) -> Mono.empty(),
(context) -> Mono.empty());
}
private Function<PollingContext<DeletedCertificate>, Mono<DeletedCertificate>> activationOperation(String certificateName) {
return (pollingContext) -> withContext(context -> deleteCertificateWithResponse(certificateName,
context))
.flatMap(deletedCertificateResponse -> Mono.just(deletedCertificateResponse.getValue()));
}
/*
Polling operation to poll on create delete certificate operation status.
*/
private Function<PollingContext<DeletedCertificate>, Mono<PollResponse<DeletedCertificate>>> createDeletePollOperation(String keyName) {
return pollingContext ->
withContext(context -> service.getDeletedCertificatePoller(vaultUrl, keyName, apiVersion,
ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)))
.flatMap(deletedCertificateResponse -> {
if (deletedCertificateResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS,
pollingContext.getLatestResponse().getValue())));
}
if (deletedCertificateResponse.getStatusCode() == HttpURLConnection.HTTP_FORBIDDEN) {
return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED,
pollingContext.getLatestResponse().getValue())));
}
return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedCertificateResponse.getValue())));
})
.onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()));
}
Mono<Response<DeletedCertificate>> deleteCertificateWithResponse(String certificateName, Context context) {
return service.deleteCertificate(vaultUrl, certificateName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.info("Deleting certificate - {}", certificateName))
.doOnSuccess(response -> logger.info("Deleted the certificate - {}", response.getValue().getProperties().getName()))
.doOnError(error -> logger.warning("Failed to delete the certificate - {}", certificateName, error));
}
/**
* Retrieves information about the specified deleted certificate. The GetDeletedCertificate operation is applicable for soft-delete
* enabled vaults and additionally retrieves deleted certificate's attributes, such as retention interval, scheduled permanent deletion and the current deletion recovery level. This operation
* requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p> Gets the deleted certificate from the key vault enabled for soft-delete. Prints out the
* deleted certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getDeletedCertificate
*
* @param certificateName The name of the deleted certificate.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException when a certificate with {@code certificateName} is empty string.
* @return A {@link Mono} containing the {@link DeletedCertificate deleted certificate}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeletedCertificate> getDeletedCertificate(String certificateName) {
try {
return withContext(context -> getDeletedCertificateWithResponse(certificateName, context))
.flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Retrieves information about the specified deleted certificate. The GetDeletedCertificate operation is applicable for soft-delete
* enabled vaults and additionally retrieves deleted certificate's attributes, such as retention interval, scheduled permanent deletion and the current deletion recovery level. This operation
* requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p> Gets the deleted certificate from the key vault enabled for soft-delete. Prints out the
* deleted certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getDeletedCertificateWithResponse
*
* @param certificateName The name of the deleted certificate.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException when a certificate with {@code certificateName} is empty string.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeletedCertificate>> getDeletedCertificateWithResponse(String certificateName) {
try {
return withContext(context -> getDeletedCertificateWithResponse(certificateName, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DeletedCertificate>> getDeletedCertificateWithResponse(String certificateName, Context context) {
context = context == null ? Context.NONE : context;
return service.getDeletedCertificate(vaultUrl, certificateName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.info("Retrieving deleted certificate - {}", certificateName))
.doOnSuccess(response -> logger.info("Retrieved the deleted certificate - {}", response.getValue().getProperties().getName()))
.doOnError(error -> logger.warning("Failed to Retrieve the deleted certificate - {}", certificateName, error));
}
/**
* Permanently deletes the specified deleted certificate without possibility for recovery. The Purge Deleted Certificate operation is applicable for
* soft-delete enabled vaults and is not available if the recovery level does not specify 'Purgeable'. This operation requires the certificate/purge permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Purges the deleted certificate from the key vault enabled for soft-delete. Prints out the
* status code from the server response when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.purgeDeletedCertificateWithResponse
*
* @param certificateName The name of the deleted certificate.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException when a certificate with {@code certificateName} is empty string.
* @return An empty {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> purgeDeletedCertificate(String certificateName) {
try {
return purgeDeletedCertificateWithResponse(certificateName).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Permanently deletes the specified deleted certificate without possibility for recovery. The Purge Deleted Certificate operation is applicable for
* soft-delete enabled vaults and is not available if the recovery level does not specify 'Purgeable'. This operation requires the certificate/purge permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Purges the deleted certificate from the key vault enabled for soft-delete. Prints out the
* status code from the server response when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.purgeDeletedCertificateWithResponse
*
* @param certificateName The name of the deleted certificate.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException when a certificate with {@code certificateName} is empty string.
* @return A {@link Mono} containing a Void Response} | class CertificateAsyncClient {
private final String apiVersion;
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private static final String KEYVAULT_TRACING_NAMESPACE_VALUE = "Microsoft.KeyVault";
private static final Duration DEFAULT_POLL_DURATION = Duration.ofSeconds(1);
private final String vaultUrl;
private final CertificateService service;
private final ClientLogger logger = new ClientLogger(CertificateAsyncClient.class);
/**
* Creates a CertificateAsyncClient that uses {@code pipeline} to service requests
*
* @param vaultUrl URL for the Azure KeyVault service.
* @param pipeline HttpPipeline that the HTTP requests and responses flow through.
* @param version {@link CertificateServiceVersion} of the service to be used when making requests.
*/
CertificateAsyncClient(URL vaultUrl, HttpPipeline pipeline, CertificateServiceVersion version) {
Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED));
this.vaultUrl = vaultUrl.toString();
this.service = RestProxy.create(CertificateService.class, pipeline);
apiVersion = version.getVersion();
}
/**
* Get the vault endpoint url to which service requests are sent to.
* @return the vault endpoint url
*/
public String getVaultUrl() {
return vaultUrl;
}
/**
* Creates a new certificate. If this is the first version, the certificate resource is created. This operation requires
* the certificates/create permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Create certificate is a long running operation. The {@link PollerFlux poller} allows users to automatically poll on the create certificate
* operation status. It is possible to monitor each intermediate poll response during the poll operation.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.beginCreateCertificate
*
* @param certificateName The name of the certificate to be created.
* @param policy The policy of the certificate to be created.
* @param isEnabled The enabled status for the certificate.
* @param tags The application specific metadata to set.
* @throws ResourceModifiedException when invalid certificate policy configuration is provided.
* @return A {@link PollerFlux} polling on the create certificate operation status.
*/
public PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> beginCreateCertificate(String certificateName, CertificatePolicy policy, Boolean isEnabled, Map<String, String> tags) {
return new PollerFlux<>(getPollDuration(),
activationOperation(certificateName, policy, isEnabled, tags),
createPollOperation(certificateName),
cancelOperation(certificateName),
fetchResultOperation(certificateName));
}
private BiFunction<PollingContext<CertificateOperation>,
PollResponse<CertificateOperation>,
Mono<CertificateOperation>> cancelOperation(String certificateName) {
return (pollingContext, firstResponse) -> withContext(context
-> cancelCertificateOperationWithResponse(certificateName, context))
.flatMap(FluxUtil::toMono);
}
private Function<PollingContext<CertificateOperation>, Mono<CertificateOperation>> activationOperation(String certificateName,
CertificatePolicy policy,
boolean enabled,
Map<String, String> tags) {
return (pollingContext) -> withContext(context -> createCertificateWithResponse(certificateName,
policy,
enabled,
tags,
context))
.flatMap(certificateOperationResponse -> Mono.just(certificateOperationResponse.getValue()));
}
private Function<PollingContext<CertificateOperation>,
Mono<KeyVaultCertificateWithPolicy>> fetchResultOperation(String certificateName) {
return (pollingContext) -> withContext(context
-> getCertificateWithResponse(certificateName, "", context))
.flatMap(certificateResponse -> Mono.just(certificateResponse.getValue()));
}
/**
* Creates a new certificate. If this is the first version, the certificate resource is created. This operation requires
* the certificates/create permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Create certificate is a long running operation. The {@link PollerFlux poller} allows users to automatically poll on the create certificate
* operation status. It is possible to monitor each intermediate poll response during the poll operation.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.beginCreateCertificate
*
* @param certificateName The name of the certificate to be created.
* @param policy The policy of the certificate to be created.
* @throws ResourceModifiedException when invalid certificate policy configuration is provided.
* @return A {@link PollerFlux} polling on the create certificate operation status.
*/
public PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> beginCreateCertificate(String certificateName, CertificatePolicy policy) {
return beginCreateCertificate(certificateName, policy, true, null);
}
/*
Polling operation to poll on create certificate operation status.
*/
private Function<PollingContext<CertificateOperation>, Mono<PollResponse<CertificateOperation>>> createPollOperation(String certificateName) {
return (pollingContext) -> {
try {
return withContext(context -> service.getCertificateOperation(vaultUrl, certificateName, apiVersion,
ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)))
.flatMap(this::processCertificateOperationResponse);
} catch (HttpResponseException e) {
logger.logExceptionAsError(e);
return Mono.just(new PollResponse<>(LongRunningOperationStatus.FAILED, null));
}
};
}
private Mono<PollResponse<CertificateOperation>> processCertificateOperationResponse(Response<CertificateOperation> certificateOperationResponse) {
LongRunningOperationStatus status = null;
switch (certificateOperationResponse.getValue().getStatus()) {
case "inProgress":
status = LongRunningOperationStatus.IN_PROGRESS;
break;
case "completed":
status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED;
break;
case "failed":
status = LongRunningOperationStatus.FAILED;
break;
default:
status = LongRunningOperationStatus.fromString(certificateOperationResponse.getValue().getStatus(), true);
break;
}
return Mono.just(new PollResponse<>(status, certificateOperationResponse.getValue()));
}
Mono<Response<CertificateOperation>> createCertificateWithResponse(String certificateName, CertificatePolicy certificatePolicy, boolean enabled, Map<String, String> tags, Context context) {
CertificateRequestParameters certificateRequestParameters = new CertificateRequestParameters()
.certificatePolicy(new CertificatePolicyRequest(certificatePolicy))
.certificateAttributes(new CertificateRequestAttributes().enabled(enabled))
.tags(tags);
return service.createCertificate(vaultUrl, certificateName, apiVersion, ACCEPT_LANGUAGE, certificateRequestParameters, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE));
}
/**
* Gets a pending {@link CertificateOperation} from the key vault. This operation requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Get a pending certificate operation. The {@link PollerFlux poller} allows users to automatically poll on the certificate
* operation status. It is possible to monitor each intermediate poll response during the poll operation.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateOperation
*
* @param certificateName The name of the certificate.
* @throws ResourceNotFoundException when a certificate operation for a certificate with {@code certificateName} doesn't exist.
* @return A {@link PollerFlux} polling on the certificate operation status.
*/
public PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> getCertificateOperation(String certificateName) {
return new PollerFlux<>(getPollDuration(),
(pollingContext) -> Mono.empty(),
createPollOperation(certificateName),
cancelOperation(certificateName),
fetchResultOperation(certificateName));
}
/**
* Gets information about the latest version of the specified certificate. This operation requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the certificate in the key vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificate
*
* @param certificateName The name of the certificate to retrieve, cannot be null
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException if {@code certificateName} is empty string.
* @return A {@link Mono} containing the requested {@link KeyVaultCertificateWithPolicy certificate}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultCertificateWithPolicy> getCertificate(String certificateName) {
try {
return withContext(context -> getCertificateWithResponse(certificateName, "",
context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets information about the latest version of the specified certificate. This operation requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the certificate in the key vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateWithResponse
*
* @param certificateName The name of the certificate to retrieve, cannot be null
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException if {@code certificateName} is empty string.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultCertificateWithPolicy>> getCertificateWithResponse(String certificateName) {
try {
return withContext(context -> getCertificateWithResponse(certificateName, "", context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultCertificateWithPolicy>> getCertificateWithResponse(String certificateName, String version, Context context) {
context = context == null ? Context.NONE : context;
return service.getCertificateWithPolicy(vaultUrl, certificateName, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.info("Retrieving certificate - {}", certificateName))
.doOnSuccess(response -> logger.info("Retrieved the certificate - {}", response.getValue().getProperties().getName()))
.doOnError(error -> logger.warning("Failed to Retrieve the certificate - {}", certificateName, error));
}
Mono<Response<KeyVaultCertificate>> getCertificateVersionWithResponse(String certificateName, String version, Context context) {
context = context == null ? Context.NONE : context;
return service.getCertificate(vaultUrl, certificateName, version, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context)
.doOnRequest(ignored -> logger.info("Retrieving certificate - {}", certificateName))
.doOnSuccess(response -> logger.info("Retrieved the certificate - {}", response.getValue().getProperties().getName()))
.doOnError(error -> logger.warning("Failed to Retrieve the certificate - {}", certificateName, error));
}
/**
* Gets information about the latest version of the specified certificate. This operation requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the certificate in the key vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateVersionWithResponse
*
* @param certificateName The name of the certificate to retrieve, cannot be null
* @param version The version of the certificate to retrieve. If this is an empty String or null then latest version of the certificate is retrieved.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException if {@code certificateName} is empty string.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultCertificate>> getCertificateVersionWithResponse(String certificateName, String version) {
try {
return withContext(context -> getCertificateVersionWithResponse(certificateName, version == null ? "" : version,
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets information about the specified version of the specified certificate. This operation requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets a specific version of the certificate in the key vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateVersion
*
* @param certificateName The name of the certificate to retrieve, cannot be null
* @param version The version of the certificate to retrieve. If this is an empty String or null then latest version of the certificate is retrieved.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException if {@code certificateName} is empty string.
* @return A {@link Mono} containing the requested {@link KeyVaultCertificate certificate}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultCertificate> getCertificateVersion(String certificateName, String version) {
try {
return withContext(context -> getCertificateVersionWithResponse(certificateName, version == null ? "" : version,
context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates the specified attributes associated with the specified certificate. The update operation changes specified attributes of an existing
* stored certificate and attributes that are not specified in the request are left unchanged. This operation requires the certificates/update permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the certificate, changes its tags and enabled status and then updates it in the Azure Key Vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificateProperties
*
* @param properties The {@link CertificateProperties} object with updated properties.
* @throws NullPointerException if {@code certificate} is {@code null}.
* @throws ResourceNotFoundException when a certificate with {@link CertificateProperties
* @throws HttpResponseException if {@link CertificateProperties
* @return A {@link Mono} containing the {@link CertificateProperties updated certificate}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<KeyVaultCertificate> updateCertificateProperties(CertificateProperties properties) {
try {
return withContext(context -> updateCertificatePropertiesWithResponse(properties, context)).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates the specified attributes associated with the specified certificate. The update operation changes specified attributes of an existing
* stored certificate and attributes that are not specified in the request are left unchanged. This operation requires the certificates/update permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Gets latest version of the certificate, changes its enabled status and then updates it in the Azure Key Vault. Prints out the
* returned certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificatePropertiesWithResponse
*
* @param properties The {@link CertificateProperties} object with updated properties.
* @throws NullPointerException if {@code properties} is {@code null}.
* @throws ResourceNotFoundException when a certificate with {@link CertificateProperties
* @throws HttpResponseException if {@link CertificateProperties
* @return A {@link Mono} containing a {@link Response} whose {@link Response
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<KeyVaultCertificate>> updateCertificatePropertiesWithResponse(CertificateProperties properties) {
try {
return withContext(context -> updateCertificatePropertiesWithResponse(properties,
context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<KeyVaultCertificate>> updateCertificatePropertiesWithResponse(CertificateProperties properties, Context context) {
context = context == null ? Context.NONE : context;
Objects.requireNonNull(properties, "properties' cannot be null.");
CertificateUpdateParameters parameters = new CertificateUpdateParameters()
.tags(properties.getTags())
.certificateAttributes(new CertificateRequestAttributes(properties));
return service.updateCertificate(vaultUrl, properties.getName(), properties.getVersion(), apiVersion, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.info("Updating certificate - {}", properties.getName()))
.doOnSuccess(response -> logger.info("Updated the certificate - {}", properties.getName()))
.doOnError(error -> logger.warning("Failed to update the certificate - {}", properties.getName(), error));
}
/**
* Deletes a certificate from a specified key vault. All the versions of the certificate along with its associated policy
* get deleted. If soft-delete is enabled on the key vault then the certificate is placed in the deleted state and requires to be
* purged for permanent deletion else the certificate is permanently deleted. The delete operation applies to any certificate stored in
* Azure Key Vault but it cannot be applied to an individual version of a certificate. This operation requires the certificates/delete permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Deletes the certificate in the Azure Key Vault. Prints out the deleted certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.beginDeleteCertificate
*
* @param certificateName The name of the certificate to be deleted.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException when a certificate with {@code certificateName} is empty string.
* @return A {@link PollerFlux} to poll on the {@link DeletedCertificate deleted certificate}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public PollerFlux<DeletedCertificate, Void> beginDeleteCertificate(String certificateName) {
return new PollerFlux<>(getPollDuration(),
activationOperation(certificateName),
createDeletePollOperation(certificateName),
(context, firstResponse) -> Mono.empty(),
(context) -> Mono.empty());
}
private Function<PollingContext<DeletedCertificate>, Mono<DeletedCertificate>> activationOperation(String certificateName) {
return (pollingContext) -> withContext(context -> deleteCertificateWithResponse(certificateName,
context))
.flatMap(deletedCertificateResponse -> Mono.just(deletedCertificateResponse.getValue()));
}
/*
Polling operation to poll on create delete certificate operation status.
*/
private Function<PollingContext<DeletedCertificate>, Mono<PollResponse<DeletedCertificate>>> createDeletePollOperation(String keyName) {
return pollingContext ->
withContext(context -> service.getDeletedCertificatePoller(vaultUrl, keyName, apiVersion,
ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE)))
.flatMap(deletedCertificateResponse -> {
if (deletedCertificateResponse.getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS,
pollingContext.getLatestResponse().getValue())));
}
if (deletedCertificateResponse.getStatusCode() == HttpURLConnection.HTTP_FORBIDDEN) {
return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED,
pollingContext.getLatestResponse().getValue())));
}
return Mono.defer(() -> Mono.just(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, deletedCertificateResponse.getValue())));
})
.onErrorReturn(new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()));
}
Mono<Response<DeletedCertificate>> deleteCertificateWithResponse(String certificateName, Context context) {
return service.deleteCertificate(vaultUrl, certificateName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.info("Deleting certificate - {}", certificateName))
.doOnSuccess(response -> logger.info("Deleted the certificate - {}", response.getValue().getProperties().getName()))
.doOnError(error -> logger.warning("Failed to delete the certificate - {}", certificateName, error));
}
/**
* Retrieves information about the specified deleted certificate. The GetDeletedCertificate operation is applicable for soft-delete
* enabled vaults and additionally retrieves deleted certificate's attributes, such as retention interval, scheduled permanent deletion and the current deletion recovery level. This operation
* requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p> Gets the deleted certificate from the key vault enabled for soft-delete. Prints out the
* deleted certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getDeletedCertificate
*
* @param certificateName The name of the deleted certificate.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException when a certificate with {@code certificateName} is empty string.
* @return A {@link Mono} containing the {@link DeletedCertificate deleted certificate}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<DeletedCertificate> getDeletedCertificate(String certificateName) {
try {
return withContext(context -> getDeletedCertificateWithResponse(certificateName, context))
.flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Retrieves information about the specified deleted certificate. The GetDeletedCertificate operation is applicable for soft-delete
* enabled vaults and additionally retrieves deleted certificate's attributes, such as retention interval, scheduled permanent deletion and the current deletion recovery level. This operation
* requires the certificates/get permission.
*
* <p><strong>Code Samples</strong></p>
* <p> Gets the deleted certificate from the key vault enabled for soft-delete. Prints out the
* deleted certificate details when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.getDeletedCertificateWithResponse
*
* @param certificateName The name of the deleted certificate.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException when a certificate with {@code certificateName} is empty string.
* @return A {@link Mono} containing a {@link Response} whose {@link Response
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<DeletedCertificate>> getDeletedCertificateWithResponse(String certificateName) {
try {
return withContext(context -> getDeletedCertificateWithResponse(certificateName, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<DeletedCertificate>> getDeletedCertificateWithResponse(String certificateName, Context context) {
context = context == null ? Context.NONE : context;
return service.getDeletedCertificate(vaultUrl, certificateName, apiVersion, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE,
context.addData(AZ_TRACING_NAMESPACE_KEY, KEYVAULT_TRACING_NAMESPACE_VALUE))
.doOnRequest(ignored -> logger.info("Retrieving deleted certificate - {}", certificateName))
.doOnSuccess(response -> logger.info("Retrieved the deleted certificate - {}", response.getValue().getProperties().getName()))
.doOnError(error -> logger.warning("Failed to Retrieve the deleted certificate - {}", certificateName, error));
}
/**
* Permanently deletes the specified deleted certificate without possibility for recovery. The Purge Deleted Certificate operation is applicable for
* soft-delete enabled vaults and is not available if the recovery level does not specify 'Purgeable'. This operation requires the certificate/purge permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Purges the deleted certificate from the key vault enabled for soft-delete. Prints out the
* status code from the server response when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.purgeDeletedCertificateWithResponse
*
* @param certificateName The name of the deleted certificate.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException when a certificate with {@code certificateName} is empty string.
* @return An empty {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> purgeDeletedCertificate(String certificateName) {
try {
return purgeDeletedCertificateWithResponse(certificateName).flatMap(FluxUtil::toMono);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Permanently deletes the specified deleted certificate without possibility for recovery. The Purge Deleted Certificate operation is applicable for
* soft-delete enabled vaults and is not available if the recovery level does not specify 'Purgeable'. This operation requires the certificate/purge permission.
*
* <p><strong>Code Samples</strong></p>
* <p>Purges the deleted certificate from the key vault enabled for soft-delete. Prints out the
* status code from the server response when a response has been received.</p>
*
* {@codesnippet com.azure.security.keyvault.certificates.CertificateAsyncClient.purgeDeletedCertificateWithResponse
*
* @param certificateName The name of the deleted certificate.
* @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault.
* @throws HttpResponseException when a certificate with {@code certificateName} is empty string.
* @return A {@link Mono} containing a Void Response} |
please use the following instead: `ConsistencyLevel.fromServiceSerializedFormat(.)` if the method is not accessible from this package use: `BridgeInternal.fromServiceSerializedFormat()` | public ConsistencyLevel getDefaultConsistencyLevel() {
if (this.cachedConsistencyLevel == null) {
ConsistencyLevel result = ConsistencyPolicy.DEFAULT_DEFAULT_CONSISTENCY_LEVEL;
String consistencyLevelString = super.getString(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL);
try {
result = ConsistencyLevel
.valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, consistencyLevelString));
} catch (IllegalArgumentException e) {
this.getLogger().warn("Unknown consistency level {}, value ignored.", consistencyLevelString);
}
this.cachedConsistencyLevel = result;
}
return cachedConsistencyLevel;
} | .valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, consistencyLevelString)); | public ConsistencyLevel getDefaultConsistencyLevel() {
if (this.consistencyLevel == null) {
ConsistencyLevel result = ConsistencyPolicy.DEFAULT_DEFAULT_CONSISTENCY_LEVEL;
String consistencyLevelString = super.getString(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL);
try {
result = BridgeInternal.fromServiceSerializedFormat(consistencyLevelString);
} catch (IllegalArgumentException e) {
this.getLogger().warn("Unknown consistency level {}, value ignored.", consistencyLevelString);
}
this.consistencyLevel = result;
}
return consistencyLevel;
} | class ConsistencyPolicy extends JsonSerializable {
private static final ConsistencyLevel DEFAULT_DEFAULT_CONSISTENCY_LEVEL =
ConsistencyLevel.SESSION;
private static final int DEFAULT_MAX_STALENESS_INTERVAL = 5;
private static final int DEFAULT_MAX_STALENESS_PREFIX = 100;
/**
* Constructor.
*/
public ConsistencyPolicy() {
}
/**
* Constructor.
*
* @param objectNode the {@link ObjectNode} that represent the
* {@link JsonSerializable}
*/
public ConsistencyPolicy(ObjectNode objectNode) {
super(objectNode);
}
/**
* Constructor.
*
* @param jsonString the json string that represents the consistency policy.
*/
public ConsistencyPolicy(String jsonString) {
super(jsonString);
}
/**
* Get the name of the resource.
*
* @return the default consistency level.
*/
/**
* Set the name of the resource.
*
* @param level the consistency level.
* @return the ConsistencyPolicy.
*/
public ConsistencyPolicy setDefaultConsistencyLevel(ConsistencyLevel level) {
this.cachedConsistencyLevel = level;
super.set(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL, level.toString());
return this;
}
/**
* Gets the bounded staleness consistency, the maximum allowed staleness in terms difference in sequence numbers
* (aka version).
*
* @return the max staleness prefix.
*/
public int getMaxStalenessPrefix() {
Integer value = super.getInt(Constants.Properties.MAX_STALENESS_PREFIX);
if (value == null) {
return ConsistencyPolicy.DEFAULT_MAX_STALENESS_PREFIX;
}
return value;
}
/**
* Sets the bounded staleness consistency, the maximum allowed staleness in terms difference in sequence numbers
* (aka version).
*
* @param maxStalenessPrefix the max staleness prefix.
* @return the ConsistencyPolicy.
*/
public ConsistencyPolicy setMaxStalenessPrefix(int maxStalenessPrefix) {
super.set(Constants.Properties.MAX_STALENESS_PREFIX, maxStalenessPrefix);
return this;
}
/**
* Gets the in bounded staleness consistency, the maximum allowed staleness in terms time interval.
* Resolution is in seconds.
*
* @return the max staleness prefix.
*/
public Duration getMaxStalenessInterval() {
Integer value = super.getInt(Constants.Properties.MAX_STALENESS_INTERVAL_IN_SECONDS);
if (value == null) {
return Duration.ofSeconds(ConsistencyPolicy.DEFAULT_MAX_STALENESS_INTERVAL);
}
return Duration.ofSeconds(value);
}
/**
* Sets the in bounded staleness consistency, the maximum allowed staleness in terms time interval.
* Resolution is in seconds.
*
* @param maxStalenessInterval the max staleness interval.
* @return the ConsistencyPolicy.
*/
public ConsistencyPolicy setMaxStalenessInterval(Duration maxStalenessInterval) {
if (maxStalenessInterval == null) {
throw new IllegalArgumentException("maxStalenessInterval should not be null");
}
super.set(Constants.Properties.MAX_STALENESS_INTERVAL_IN_SECONDS, maxStalenessInterval.getSeconds());
return this;
}
/**
* Assumption: all consistency mutations are through setDefaultConsistencyLevel only.
* NOTE: If the underlying ObjectNode is mutated cache might be stale
*/
private ConsistencyLevel cachedConsistencyLevel = null;
} | class ConsistencyPolicy extends JsonSerializable {
private static final ConsistencyLevel DEFAULT_DEFAULT_CONSISTENCY_LEVEL =
ConsistencyLevel.SESSION;
private static final int DEFAULT_MAX_STALENESS_INTERVAL = 5;
private static final int DEFAULT_MAX_STALENESS_PREFIX = 100;
/**
* Constructor.
*/
public ConsistencyPolicy() {
}
/**
* Constructor.
*
* @param objectNode the {@link ObjectNode} that represent the
* {@link JsonSerializable}
*/
public ConsistencyPolicy(ObjectNode objectNode) {
super(objectNode);
}
/**
* Constructor.
*
* @param jsonString the json string that represents the consistency policy.
*/
public ConsistencyPolicy(String jsonString) {
super(jsonString);
}
/**
* Get the name of the resource.
*
* @return the default consistency level.
*/
/**
* Set the name of the resource.
*
* @param level the consistency level.
* @return the ConsistencyPolicy.
*/
public ConsistencyPolicy setDefaultConsistencyLevel(ConsistencyLevel level) {
this.consistencyLevel = level;
super.set(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL, level.toString());
return this;
}
/**
* Gets the bounded staleness consistency, the maximum allowed staleness in terms difference in sequence numbers
* (aka version).
*
* @return the max staleness prefix.
*/
public int getMaxStalenessPrefix() {
Integer value = super.getInt(Constants.Properties.MAX_STALENESS_PREFIX);
if (value == null) {
return ConsistencyPolicy.DEFAULT_MAX_STALENESS_PREFIX;
}
return value;
}
/**
* Sets the bounded staleness consistency, the maximum allowed staleness in terms difference in sequence numbers
* (aka version).
*
* @param maxStalenessPrefix the max staleness prefix.
* @return the ConsistencyPolicy.
*/
public ConsistencyPolicy setMaxStalenessPrefix(int maxStalenessPrefix) {
super.set(Constants.Properties.MAX_STALENESS_PREFIX, maxStalenessPrefix);
return this;
}
/**
* Gets the in bounded staleness consistency, the maximum allowed staleness in terms time interval.
* Resolution is in seconds.
*
* @return the max staleness prefix.
*/
public Duration getMaxStalenessInterval() {
Integer value = super.getInt(Constants.Properties.MAX_STALENESS_INTERVAL_IN_SECONDS);
if (value == null) {
return Duration.ofSeconds(ConsistencyPolicy.DEFAULT_MAX_STALENESS_INTERVAL);
}
return Duration.ofSeconds(value);
}
/**
* Sets the in bounded staleness consistency, the maximum allowed staleness in terms time interval.
* Resolution is in seconds.
*
* @param maxStalenessInterval the max staleness interval.
* @return the ConsistencyPolicy.
*/
public ConsistencyPolicy setMaxStalenessInterval(Duration maxStalenessInterval) {
if (maxStalenessInterval == null) {
throw new IllegalArgumentException("maxStalenessInterval should not be null");
}
super.set(Constants.Properties.MAX_STALENESS_INTERVAL_IN_SECONDS, maxStalenessInterval.getSeconds());
return this;
}
/**
* Assumption: all consistency mutations are through setDefaultConsistencyLevel only.
* NOTE: If the underlying ObjectNode is mutated cache might be stale
*/
private ConsistencyLevel consistencyLevel = null;
} |
you don't need `ConsistencyLeve.valueOf()` here. | public ConsistencyLevel getDefaultConsistencyLevel() {
if (this.consistencyLevel == null) {
ConsistencyLevel result = ConsistencyPolicy.DEFAULT_DEFAULT_CONSISTENCY_LEVEL;
String consistencyLevelString = super.getString(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL);
try {
result = ConsistencyLevel
.valueOf(BridgeInternal.fromServiceSerializedFormat(consistencyLevelString));
} catch (IllegalArgumentException e) {
this.getLogger().warn("Unknown consistency level {}, value ignored.", consistencyLevelString);
}
this.consistencyLevel = result;
}
return consistencyLevel;
} | .valueOf(BridgeInternal.fromServiceSerializedFormat(consistencyLevelString)); | public ConsistencyLevel getDefaultConsistencyLevel() {
if (this.consistencyLevel == null) {
ConsistencyLevel result = ConsistencyPolicy.DEFAULT_DEFAULT_CONSISTENCY_LEVEL;
String consistencyLevelString = super.getString(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL);
try {
result = BridgeInternal.fromServiceSerializedFormat(consistencyLevelString);
} catch (IllegalArgumentException e) {
this.getLogger().warn("Unknown consistency level {}, value ignored.", consistencyLevelString);
}
this.consistencyLevel = result;
}
return consistencyLevel;
} | class ConsistencyPolicy extends JsonSerializable {
private static final ConsistencyLevel DEFAULT_DEFAULT_CONSISTENCY_LEVEL =
ConsistencyLevel.SESSION;
private static final int DEFAULT_MAX_STALENESS_INTERVAL = 5;
private static final int DEFAULT_MAX_STALENESS_PREFIX = 100;
/**
* Constructor.
*/
public ConsistencyPolicy() {
}
/**
* Constructor.
*
* @param objectNode the {@link ObjectNode} that represent the
* {@link JsonSerializable}
*/
public ConsistencyPolicy(ObjectNode objectNode) {
super(objectNode);
}
/**
* Constructor.
*
* @param jsonString the json string that represents the consistency policy.
*/
public ConsistencyPolicy(String jsonString) {
super(jsonString);
}
/**
* Get the name of the resource.
*
* @return the default consistency level.
*/
/**
* Set the name of the resource.
*
* @param level the consistency level.
* @return the ConsistencyPolicy.
*/
public ConsistencyPolicy setDefaultConsistencyLevel(ConsistencyLevel level) {
this.consistencyLevel = level;
super.set(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL, level.toString());
return this;
}
/**
* Gets the bounded staleness consistency, the maximum allowed staleness in terms difference in sequence numbers
* (aka version).
*
* @return the max staleness prefix.
*/
public int getMaxStalenessPrefix() {
Integer value = super.getInt(Constants.Properties.MAX_STALENESS_PREFIX);
if (value == null) {
return ConsistencyPolicy.DEFAULT_MAX_STALENESS_PREFIX;
}
return value;
}
/**
* Sets the bounded staleness consistency, the maximum allowed staleness in terms difference in sequence numbers
* (aka version).
*
* @param maxStalenessPrefix the max staleness prefix.
* @return the ConsistencyPolicy.
*/
public ConsistencyPolicy setMaxStalenessPrefix(int maxStalenessPrefix) {
super.set(Constants.Properties.MAX_STALENESS_PREFIX, maxStalenessPrefix);
return this;
}
/**
* Gets the in bounded staleness consistency, the maximum allowed staleness in terms time interval.
* Resolution is in seconds.
*
* @return the max staleness prefix.
*/
public Duration getMaxStalenessInterval() {
Integer value = super.getInt(Constants.Properties.MAX_STALENESS_INTERVAL_IN_SECONDS);
if (value == null) {
return Duration.ofSeconds(ConsistencyPolicy.DEFAULT_MAX_STALENESS_INTERVAL);
}
return Duration.ofSeconds(value);
}
/**
* Sets the in bounded staleness consistency, the maximum allowed staleness in terms time interval.
* Resolution is in seconds.
*
* @param maxStalenessInterval the max staleness interval.
* @return the ConsistencyPolicy.
*/
public ConsistencyPolicy setMaxStalenessInterval(Duration maxStalenessInterval) {
if (maxStalenessInterval == null) {
throw new IllegalArgumentException("maxStalenessInterval should not be null");
}
super.set(Constants.Properties.MAX_STALENESS_INTERVAL_IN_SECONDS, maxStalenessInterval.getSeconds());
return this;
}
/**
* Assumption: all consistency mutations are through setDefaultConsistencyLevel only.
* NOTE: If the underlying ObjectNode is mutated cache might be stale
*/
private ConsistencyLevel consistencyLevel = null;
} | class ConsistencyPolicy extends JsonSerializable {
private static final ConsistencyLevel DEFAULT_DEFAULT_CONSISTENCY_LEVEL =
ConsistencyLevel.SESSION;
private static final int DEFAULT_MAX_STALENESS_INTERVAL = 5;
private static final int DEFAULT_MAX_STALENESS_PREFIX = 100;
/**
* Constructor.
*/
public ConsistencyPolicy() {
}
/**
* Constructor.
*
* @param objectNode the {@link ObjectNode} that represent the
* {@link JsonSerializable}
*/
public ConsistencyPolicy(ObjectNode objectNode) {
super(objectNode);
}
/**
* Constructor.
*
* @param jsonString the json string that represents the consistency policy.
*/
public ConsistencyPolicy(String jsonString) {
super(jsonString);
}
/**
* Get the name of the resource.
*
* @return the default consistency level.
*/
/**
* Set the name of the resource.
*
* @param level the consistency level.
* @return the ConsistencyPolicy.
*/
public ConsistencyPolicy setDefaultConsistencyLevel(ConsistencyLevel level) {
this.consistencyLevel = level;
super.set(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL, level.toString());
return this;
}
/**
* Gets the bounded staleness consistency, the maximum allowed staleness in terms difference in sequence numbers
* (aka version).
*
* @return the max staleness prefix.
*/
public int getMaxStalenessPrefix() {
Integer value = super.getInt(Constants.Properties.MAX_STALENESS_PREFIX);
if (value == null) {
return ConsistencyPolicy.DEFAULT_MAX_STALENESS_PREFIX;
}
return value;
}
/**
* Sets the bounded staleness consistency, the maximum allowed staleness in terms difference in sequence numbers
* (aka version).
*
* @param maxStalenessPrefix the max staleness prefix.
* @return the ConsistencyPolicy.
*/
public ConsistencyPolicy setMaxStalenessPrefix(int maxStalenessPrefix) {
super.set(Constants.Properties.MAX_STALENESS_PREFIX, maxStalenessPrefix);
return this;
}
/**
* Gets the in bounded staleness consistency, the maximum allowed staleness in terms time interval.
* Resolution is in seconds.
*
* @return the max staleness prefix.
*/
public Duration getMaxStalenessInterval() {
Integer value = super.getInt(Constants.Properties.MAX_STALENESS_INTERVAL_IN_SECONDS);
if (value == null) {
return Duration.ofSeconds(ConsistencyPolicy.DEFAULT_MAX_STALENESS_INTERVAL);
}
return Duration.ofSeconds(value);
}
/**
* Sets the in bounded staleness consistency, the maximum allowed staleness in terms time interval.
* Resolution is in seconds.
*
* @param maxStalenessInterval the max staleness interval.
* @return the ConsistencyPolicy.
*/
public ConsistencyPolicy setMaxStalenessInterval(Duration maxStalenessInterval) {
if (maxStalenessInterval == null) {
throw new IllegalArgumentException("maxStalenessInterval should not be null");
}
super.set(Constants.Properties.MAX_STALENESS_INTERVAL_IN_SECONDS, maxStalenessInterval.getSeconds());
return this;
}
/**
* Assumption: all consistency mutations are through setDefaultConsistencyLevel only.
* NOTE: If the underlying ObjectNode is mutated cache might be stale
*/
private ConsistencyLevel consistencyLevel = null;
} |
please change to ```java result = BridgeInternal.fromServiceSerializedFormat(consistencyLevelString) ``` | public ConsistencyLevel getDefaultConsistencyLevel() {
if (this.consistencyLevel == null) {
ConsistencyLevel result = ConsistencyPolicy.DEFAULT_DEFAULT_CONSISTENCY_LEVEL;
String consistencyLevelString = super.getString(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL);
try {
result = ConsistencyLevel
.valueOf(BridgeInternal.fromServiceSerializedFormat(consistencyLevelString));
} catch (IllegalArgumentException e) {
this.getLogger().warn("Unknown consistency level {}, value ignored.", consistencyLevelString);
}
this.consistencyLevel = result;
}
return consistencyLevel;
} | .valueOf(BridgeInternal.fromServiceSerializedFormat(consistencyLevelString)); | public ConsistencyLevel getDefaultConsistencyLevel() {
if (this.consistencyLevel == null) {
ConsistencyLevel result = ConsistencyPolicy.DEFAULT_DEFAULT_CONSISTENCY_LEVEL;
String consistencyLevelString = super.getString(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL);
try {
result = BridgeInternal.fromServiceSerializedFormat(consistencyLevelString);
} catch (IllegalArgumentException e) {
this.getLogger().warn("Unknown consistency level {}, value ignored.", consistencyLevelString);
}
this.consistencyLevel = result;
}
return consistencyLevel;
} | class ConsistencyPolicy extends JsonSerializable {
private static final ConsistencyLevel DEFAULT_DEFAULT_CONSISTENCY_LEVEL =
ConsistencyLevel.SESSION;
private static final int DEFAULT_MAX_STALENESS_INTERVAL = 5;
private static final int DEFAULT_MAX_STALENESS_PREFIX = 100;
/**
* Constructor.
*/
public ConsistencyPolicy() {
}
/**
* Constructor.
*
* @param objectNode the {@link ObjectNode} that represent the
* {@link JsonSerializable}
*/
public ConsistencyPolicy(ObjectNode objectNode) {
super(objectNode);
}
/**
* Constructor.
*
* @param jsonString the json string that represents the consistency policy.
*/
public ConsistencyPolicy(String jsonString) {
super(jsonString);
}
/**
* Get the name of the resource.
*
* @return the default consistency level.
*/
/**
* Set the name of the resource.
*
* @param level the consistency level.
* @return the ConsistencyPolicy.
*/
public ConsistencyPolicy setDefaultConsistencyLevel(ConsistencyLevel level) {
this.consistencyLevel = level;
super.set(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL, level.toString());
return this;
}
/**
* Gets the bounded staleness consistency, the maximum allowed staleness in terms difference in sequence numbers
* (aka version).
*
* @return the max staleness prefix.
*/
public int getMaxStalenessPrefix() {
Integer value = super.getInt(Constants.Properties.MAX_STALENESS_PREFIX);
if (value == null) {
return ConsistencyPolicy.DEFAULT_MAX_STALENESS_PREFIX;
}
return value;
}
/**
* Sets the bounded staleness consistency, the maximum allowed staleness in terms difference in sequence numbers
* (aka version).
*
* @param maxStalenessPrefix the max staleness prefix.
* @return the ConsistencyPolicy.
*/
public ConsistencyPolicy setMaxStalenessPrefix(int maxStalenessPrefix) {
super.set(Constants.Properties.MAX_STALENESS_PREFIX, maxStalenessPrefix);
return this;
}
/**
* Gets the in bounded staleness consistency, the maximum allowed staleness in terms time interval.
* Resolution is in seconds.
*
* @return the max staleness prefix.
*/
public Duration getMaxStalenessInterval() {
Integer value = super.getInt(Constants.Properties.MAX_STALENESS_INTERVAL_IN_SECONDS);
if (value == null) {
return Duration.ofSeconds(ConsistencyPolicy.DEFAULT_MAX_STALENESS_INTERVAL);
}
return Duration.ofSeconds(value);
}
/**
* Sets the in bounded staleness consistency, the maximum allowed staleness in terms time interval.
* Resolution is in seconds.
*
* @param maxStalenessInterval the max staleness interval.
* @return the ConsistencyPolicy.
*/
public ConsistencyPolicy setMaxStalenessInterval(Duration maxStalenessInterval) {
if (maxStalenessInterval == null) {
throw new IllegalArgumentException("maxStalenessInterval should not be null");
}
super.set(Constants.Properties.MAX_STALENESS_INTERVAL_IN_SECONDS, maxStalenessInterval.getSeconds());
return this;
}
/**
* Assumption: all consistency mutations are through setDefaultConsistencyLevel only.
* NOTE: If the underlying ObjectNode is mutated cache might be stale
*/
private ConsistencyLevel consistencyLevel = null;
} | class ConsistencyPolicy extends JsonSerializable {
private static final ConsistencyLevel DEFAULT_DEFAULT_CONSISTENCY_LEVEL =
ConsistencyLevel.SESSION;
private static final int DEFAULT_MAX_STALENESS_INTERVAL = 5;
private static final int DEFAULT_MAX_STALENESS_PREFIX = 100;
/**
* Constructor.
*/
public ConsistencyPolicy() {
}
/**
* Constructor.
*
* @param objectNode the {@link ObjectNode} that represent the
* {@link JsonSerializable}
*/
public ConsistencyPolicy(ObjectNode objectNode) {
super(objectNode);
}
/**
* Constructor.
*
* @param jsonString the json string that represents the consistency policy.
*/
public ConsistencyPolicy(String jsonString) {
super(jsonString);
}
/**
* Get the name of the resource.
*
* @return the default consistency level.
*/
/**
* Set the name of the resource.
*
* @param level the consistency level.
* @return the ConsistencyPolicy.
*/
public ConsistencyPolicy setDefaultConsistencyLevel(ConsistencyLevel level) {
this.consistencyLevel = level;
super.set(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL, level.toString());
return this;
}
/**
* Gets the bounded staleness consistency, the maximum allowed staleness in terms difference in sequence numbers
* (aka version).
*
* @return the max staleness prefix.
*/
public int getMaxStalenessPrefix() {
Integer value = super.getInt(Constants.Properties.MAX_STALENESS_PREFIX);
if (value == null) {
return ConsistencyPolicy.DEFAULT_MAX_STALENESS_PREFIX;
}
return value;
}
/**
* Sets the bounded staleness consistency, the maximum allowed staleness in terms difference in sequence numbers
* (aka version).
*
* @param maxStalenessPrefix the max staleness prefix.
* @return the ConsistencyPolicy.
*/
public ConsistencyPolicy setMaxStalenessPrefix(int maxStalenessPrefix) {
super.set(Constants.Properties.MAX_STALENESS_PREFIX, maxStalenessPrefix);
return this;
}
/**
* Gets the in bounded staleness consistency, the maximum allowed staleness in terms time interval.
* Resolution is in seconds.
*
* @return the max staleness prefix.
*/
public Duration getMaxStalenessInterval() {
Integer value = super.getInt(Constants.Properties.MAX_STALENESS_INTERVAL_IN_SECONDS);
if (value == null) {
return Duration.ofSeconds(ConsistencyPolicy.DEFAULT_MAX_STALENESS_INTERVAL);
}
return Duration.ofSeconds(value);
}
/**
* Sets the in bounded staleness consistency, the maximum allowed staleness in terms time interval.
* Resolution is in seconds.
*
* @param maxStalenessInterval the max staleness interval.
* @return the ConsistencyPolicy.
*/
public ConsistencyPolicy setMaxStalenessInterval(Duration maxStalenessInterval) {
if (maxStalenessInterval == null) {
throw new IllegalArgumentException("maxStalenessInterval should not be null");
}
super.set(Constants.Properties.MAX_STALENESS_INTERVAL_IN_SECONDS, maxStalenessInterval.getSeconds());
return this;
}
/**
* Assumption: all consistency mutations are through setDefaultConsistencyLevel only.
* NOTE: If the underlying ObjectNode is mutated cache might be stale
*/
private ConsistencyLevel consistencyLevel = null;
} |
I am concerned about this synchronized code piece, since this will be called on every request. My concern is this will slow down things. Do we need `synchronized` block here even though `credential` is volatile now ? | private Mac getMacInstance() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
synchronized (this.credential) {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.UTF_8);
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256");
try {
Mac macInstance = Mac.getInstance("HMACSHA256");
macInstance.init(signingKey);
this.masterKeyHashCode = masterKeyLatestHashCode;
this.macInstance = macInstance;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
}
}
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
} | synchronized (this.credential) { | private Mac getMacInstance() {
reInitializeIfPossible();
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredential credential) {
this.credential = credential;
}
private static String getResourceSegment(ResourceType resourceType) {
switch (resourceType) {
case Attachment:
return Paths.ATTACHMENTS_PATH_SEGMENT;
case Database:
return Paths.DATABASES_PATH_SEGMENT;
case Conflict:
return Paths.CONFLICTS_PATH_SEGMENT;
case Document:
return Paths.DOCUMENTS_PATH_SEGMENT;
case DocumentCollection:
return Paths.COLLECTIONS_PATH_SEGMENT;
case Offer:
return Paths.OFFERS_PATH_SEGMENT;
case Permission:
return Paths.PERMISSIONS_PATH_SEGMENT;
case StoredProcedure:
return Paths.STORED_PROCEDURES_PATH_SEGMENT;
case Trigger:
return Paths.TRIGGERS_PATH_SEGMENT;
case UserDefinedFunction:
return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT;
case User:
return Paths.USERS_PATH_SEGMENT;
case PartitionKeyRange:
return Paths.PARTITION_KEY_RANGES_PATH_SEGMENT;
case Media:
return Paths.MEDIA_PATH_SEGMENT;
case DatabaseAccount:
return "";
default:
return null;
}
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb.
* @param resourceIdOrFullName the resource id or full name
* @param resourceType the resource type.
* @param headers the request headers.
* @return the key authorization signature.
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
ResourceType resourceType,
Map<String, String> headers) {
return this.generateKeyAuthorizationSignature(verb, resourceIdOrFullName,
BaseAuthorizationTokenProvider.getResourceSegment(resourceType), headers);
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb
* @param resourceIdOrFullName the resource id or full name
* @param resourceSegment the resource segment
* @param headers the request headers
* @return the key authorization signature
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
String resourceSegment,
Map<String, String> headers) {
if (verb == null) {
throw new IllegalArgumentException("verb");
}
if (resourceIdOrFullName == null) {
resourceIdOrFullName = "";
}
if (resourceSegment == null) {
throw new IllegalArgumentException("resourceSegment");
}
if (headers == null) {
throw new IllegalArgumentException("headers");
}
if (StringUtils.isEmpty(this.credential.getKey())) {
throw new IllegalArgumentException("key credentials cannot be empty");
}
if(!PathsHelper.isNameBased(resourceIdOrFullName)) {
resourceIdOrFullName = resourceIdOrFullName.toLowerCase(Locale.ROOT);
}
StringBuilder body = new StringBuilder();
body.append(ModelBridgeInternal.toLower(verb))
.append('\n')
.append(resourceSegment)
.append('\n')
.append(resourceIdOrFullName)
.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.X_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.X_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.HTTP_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.HTTP_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
Mac mac = getMacInstance();
byte[] digest = mac.doFinal(body.toString().getBytes(StandardCharsets.UTF_8));
String auth = Utils.encodeBase64String(digest);
return AUTH_PREFIX + auth;
}
/**
* This API is a helper method to create auth header based on client request using resourceTokens.
*
* @param resourceTokens the resource tokens.
* @param path the path.
* @param resourceId the resource id.
* @return the authorization token.
*/
public String getAuthorizationTokenUsingResourceTokens(Map<String, String> resourceTokens,
String path,
String resourceId) {
if (resourceTokens == null) {
throw new IllegalArgumentException("resourceTokens");
}
String resourceToken = null;
if (resourceTokens.containsKey(resourceId) && resourceTokens.get(resourceId) != null) {
resourceToken = resourceTokens.get(resourceId);
} else if (StringUtils.isEmpty(path) || StringUtils.isEmpty(resourceId)) {
if (resourceTokens.size() > 0) {
resourceToken = resourceTokens.values().iterator().next();
}
} else {
String[] pathParts = StringUtils.split(path, "/");
String[] resourceTypes = {"dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions",
"attachments", "media", "conflicts"};
HashSet<String> resourceTypesSet = new HashSet<String>();
Collections.addAll(resourceTypesSet, resourceTypes);
for (int i = pathParts.length - 1; i >= 0; --i) {
if (!resourceTypesSet.contains(pathParts[i]) && resourceTokens.containsKey(pathParts[i])) {
resourceToken = resourceTokens.get(pathParts[i]);
}
}
}
return resourceToken;
}
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredential credential) {
this.credential = credential;
reInitializeIfPossible();
}
private static String getResourceSegment(ResourceType resourceType) {
switch (resourceType) {
case Attachment:
return Paths.ATTACHMENTS_PATH_SEGMENT;
case Database:
return Paths.DATABASES_PATH_SEGMENT;
case Conflict:
return Paths.CONFLICTS_PATH_SEGMENT;
case Document:
return Paths.DOCUMENTS_PATH_SEGMENT;
case DocumentCollection:
return Paths.COLLECTIONS_PATH_SEGMENT;
case Offer:
return Paths.OFFERS_PATH_SEGMENT;
case Permission:
return Paths.PERMISSIONS_PATH_SEGMENT;
case StoredProcedure:
return Paths.STORED_PROCEDURES_PATH_SEGMENT;
case Trigger:
return Paths.TRIGGERS_PATH_SEGMENT;
case UserDefinedFunction:
return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT;
case User:
return Paths.USERS_PATH_SEGMENT;
case PartitionKeyRange:
return Paths.PARTITION_KEY_RANGES_PATH_SEGMENT;
case Media:
return Paths.MEDIA_PATH_SEGMENT;
case DatabaseAccount:
return "";
default:
return null;
}
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb.
* @param resourceIdOrFullName the resource id or full name
* @param resourceType the resource type.
* @param headers the request headers.
* @return the key authorization signature.
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
ResourceType resourceType,
Map<String, String> headers) {
return this.generateKeyAuthorizationSignature(verb, resourceIdOrFullName,
BaseAuthorizationTokenProvider.getResourceSegment(resourceType), headers);
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb
* @param resourceIdOrFullName the resource id or full name
* @param resourceSegment the resource segment
* @param headers the request headers
* @return the key authorization signature
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
String resourceSegment,
Map<String, String> headers) {
if (verb == null) {
throw new IllegalArgumentException("verb");
}
if (resourceIdOrFullName == null) {
resourceIdOrFullName = "";
}
if (resourceSegment == null) {
throw new IllegalArgumentException("resourceSegment");
}
if (headers == null) {
throw new IllegalArgumentException("headers");
}
if (StringUtils.isEmpty(this.credential.getKey())) {
throw new IllegalArgumentException("key credentials cannot be empty");
}
if(!PathsHelper.isNameBased(resourceIdOrFullName)) {
resourceIdOrFullName = resourceIdOrFullName.toLowerCase(Locale.ROOT);
}
StringBuilder body = new StringBuilder();
body.append(ModelBridgeInternal.toLower(verb))
.append('\n')
.append(resourceSegment)
.append('\n')
.append(resourceIdOrFullName)
.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.X_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.X_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.HTTP_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.HTTP_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
Mac mac = getMacInstance();
byte[] digest = mac.doFinal(body.toString().getBytes(StandardCharsets.UTF_8));
String auth = Utils.encodeBase64String(digest);
return AUTH_PREFIX + auth;
}
/**
* This API is a helper method to create auth header based on client request using resourceTokens.
*
* @param resourceTokens the resource tokens.
* @param path the path.
* @param resourceId the resource id.
* @return the authorization token.
*/
public String getAuthorizationTokenUsingResourceTokens(Map<String, String> resourceTokens,
String path,
String resourceId) {
if (resourceTokens == null) {
throw new IllegalArgumentException("resourceTokens");
}
String resourceToken = null;
if (resourceTokens.containsKey(resourceId) && resourceTokens.get(resourceId) != null) {
resourceToken = resourceTokens.get(resourceId);
} else if (StringUtils.isEmpty(path) || StringUtils.isEmpty(resourceId)) {
if (resourceTokens.size() > 0) {
resourceToken = resourceTokens.values().iterator().next();
}
} else {
String[] pathParts = StringUtils.split(path, "/");
String[] resourceTypes = {"dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions",
"attachments", "media", "conflicts"};
HashSet<String> resourceTypesSet = new HashSet<String>();
Collections.addAll(resourceTypesSet, resourceTypes);
for (int i = pathParts.length - 1; i >= 0; --i) {
if (!resourceTypesSet.contains(pathParts[i]) && resourceTokens.containsKey(pathParts[i])) {
resourceToken = resourceTokens.get(pathParts[i]);
}
}
}
return resourceToken;
}
/*
* Ensures that this.macInstance is initialized
* In-case of credential change, optimistically will try to refresh the macInstance
*
* Implementation is non-blocking, the one which acquire the lock will try to refresh
* with new credentials
*
* NOTE: Calling it CTOR ensured that default is initialized.
*/
private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.UTF_8);
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256");
try {
Mac macInstance = Mac.getInstance("HMACSHA256");
macInstance.init(signingKey);
this.masterKeyHashCode = masterKeyLatestHashCode;
this.macInstance = macInstance;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
} finally {
this.macInstanceLock.unlock();
}
}
}
}
} |
this is very valid point. I also think will have perf impact | private Mac getMacInstance() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
synchronized (this.credential) {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.UTF_8);
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256");
try {
Mac macInstance = Mac.getInstance("HMACSHA256");
macInstance.init(signingKey);
this.masterKeyHashCode = masterKeyLatestHashCode;
this.macInstance = macInstance;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
}
}
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
} | synchronized (this.credential) { | private Mac getMacInstance() {
reInitializeIfPossible();
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredential credential) {
this.credential = credential;
}
private static String getResourceSegment(ResourceType resourceType) {
switch (resourceType) {
case Attachment:
return Paths.ATTACHMENTS_PATH_SEGMENT;
case Database:
return Paths.DATABASES_PATH_SEGMENT;
case Conflict:
return Paths.CONFLICTS_PATH_SEGMENT;
case Document:
return Paths.DOCUMENTS_PATH_SEGMENT;
case DocumentCollection:
return Paths.COLLECTIONS_PATH_SEGMENT;
case Offer:
return Paths.OFFERS_PATH_SEGMENT;
case Permission:
return Paths.PERMISSIONS_PATH_SEGMENT;
case StoredProcedure:
return Paths.STORED_PROCEDURES_PATH_SEGMENT;
case Trigger:
return Paths.TRIGGERS_PATH_SEGMENT;
case UserDefinedFunction:
return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT;
case User:
return Paths.USERS_PATH_SEGMENT;
case PartitionKeyRange:
return Paths.PARTITION_KEY_RANGES_PATH_SEGMENT;
case Media:
return Paths.MEDIA_PATH_SEGMENT;
case DatabaseAccount:
return "";
default:
return null;
}
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb.
* @param resourceIdOrFullName the resource id or full name
* @param resourceType the resource type.
* @param headers the request headers.
* @return the key authorization signature.
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
ResourceType resourceType,
Map<String, String> headers) {
return this.generateKeyAuthorizationSignature(verb, resourceIdOrFullName,
BaseAuthorizationTokenProvider.getResourceSegment(resourceType), headers);
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb
* @param resourceIdOrFullName the resource id or full name
* @param resourceSegment the resource segment
* @param headers the request headers
* @return the key authorization signature
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
String resourceSegment,
Map<String, String> headers) {
if (verb == null) {
throw new IllegalArgumentException("verb");
}
if (resourceIdOrFullName == null) {
resourceIdOrFullName = "";
}
if (resourceSegment == null) {
throw new IllegalArgumentException("resourceSegment");
}
if (headers == null) {
throw new IllegalArgumentException("headers");
}
if (StringUtils.isEmpty(this.credential.getKey())) {
throw new IllegalArgumentException("key credentials cannot be empty");
}
if(!PathsHelper.isNameBased(resourceIdOrFullName)) {
resourceIdOrFullName = resourceIdOrFullName.toLowerCase(Locale.ROOT);
}
StringBuilder body = new StringBuilder();
body.append(ModelBridgeInternal.toLower(verb))
.append('\n')
.append(resourceSegment)
.append('\n')
.append(resourceIdOrFullName)
.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.X_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.X_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.HTTP_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.HTTP_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
Mac mac = getMacInstance();
byte[] digest = mac.doFinal(body.toString().getBytes(StandardCharsets.UTF_8));
String auth = Utils.encodeBase64String(digest);
return AUTH_PREFIX + auth;
}
/**
* This API is a helper method to create auth header based on client request using resourceTokens.
*
* @param resourceTokens the resource tokens.
* @param path the path.
* @param resourceId the resource id.
* @return the authorization token.
*/
public String getAuthorizationTokenUsingResourceTokens(Map<String, String> resourceTokens,
String path,
String resourceId) {
if (resourceTokens == null) {
throw new IllegalArgumentException("resourceTokens");
}
String resourceToken = null;
if (resourceTokens.containsKey(resourceId) && resourceTokens.get(resourceId) != null) {
resourceToken = resourceTokens.get(resourceId);
} else if (StringUtils.isEmpty(path) || StringUtils.isEmpty(resourceId)) {
if (resourceTokens.size() > 0) {
resourceToken = resourceTokens.values().iterator().next();
}
} else {
String[] pathParts = StringUtils.split(path, "/");
String[] resourceTypes = {"dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions",
"attachments", "media", "conflicts"};
HashSet<String> resourceTypesSet = new HashSet<String>();
Collections.addAll(resourceTypesSet, resourceTypes);
for (int i = pathParts.length - 1; i >= 0; --i) {
if (!resourceTypesSet.contains(pathParts[i]) && resourceTokens.containsKey(pathParts[i])) {
resourceToken = resourceTokens.get(pathParts[i]);
}
}
}
return resourceToken;
}
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredential credential) {
this.credential = credential;
reInitializeIfPossible();
}
private static String getResourceSegment(ResourceType resourceType) {
switch (resourceType) {
case Attachment:
return Paths.ATTACHMENTS_PATH_SEGMENT;
case Database:
return Paths.DATABASES_PATH_SEGMENT;
case Conflict:
return Paths.CONFLICTS_PATH_SEGMENT;
case Document:
return Paths.DOCUMENTS_PATH_SEGMENT;
case DocumentCollection:
return Paths.COLLECTIONS_PATH_SEGMENT;
case Offer:
return Paths.OFFERS_PATH_SEGMENT;
case Permission:
return Paths.PERMISSIONS_PATH_SEGMENT;
case StoredProcedure:
return Paths.STORED_PROCEDURES_PATH_SEGMENT;
case Trigger:
return Paths.TRIGGERS_PATH_SEGMENT;
case UserDefinedFunction:
return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT;
case User:
return Paths.USERS_PATH_SEGMENT;
case PartitionKeyRange:
return Paths.PARTITION_KEY_RANGES_PATH_SEGMENT;
case Media:
return Paths.MEDIA_PATH_SEGMENT;
case DatabaseAccount:
return "";
default:
return null;
}
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb.
* @param resourceIdOrFullName the resource id or full name
* @param resourceType the resource type.
* @param headers the request headers.
* @return the key authorization signature.
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
ResourceType resourceType,
Map<String, String> headers) {
return this.generateKeyAuthorizationSignature(verb, resourceIdOrFullName,
BaseAuthorizationTokenProvider.getResourceSegment(resourceType), headers);
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb
* @param resourceIdOrFullName the resource id or full name
* @param resourceSegment the resource segment
* @param headers the request headers
* @return the key authorization signature
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
String resourceSegment,
Map<String, String> headers) {
if (verb == null) {
throw new IllegalArgumentException("verb");
}
if (resourceIdOrFullName == null) {
resourceIdOrFullName = "";
}
if (resourceSegment == null) {
throw new IllegalArgumentException("resourceSegment");
}
if (headers == null) {
throw new IllegalArgumentException("headers");
}
if (StringUtils.isEmpty(this.credential.getKey())) {
throw new IllegalArgumentException("key credentials cannot be empty");
}
if(!PathsHelper.isNameBased(resourceIdOrFullName)) {
resourceIdOrFullName = resourceIdOrFullName.toLowerCase(Locale.ROOT);
}
StringBuilder body = new StringBuilder();
body.append(ModelBridgeInternal.toLower(verb))
.append('\n')
.append(resourceSegment)
.append('\n')
.append(resourceIdOrFullName)
.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.X_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.X_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.HTTP_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.HTTP_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
Mac mac = getMacInstance();
byte[] digest = mac.doFinal(body.toString().getBytes(StandardCharsets.UTF_8));
String auth = Utils.encodeBase64String(digest);
return AUTH_PREFIX + auth;
}
/**
* This API is a helper method to create auth header based on client request using resourceTokens.
*
* @param resourceTokens the resource tokens.
* @param path the path.
* @param resourceId the resource id.
* @return the authorization token.
*/
public String getAuthorizationTokenUsingResourceTokens(Map<String, String> resourceTokens,
String path,
String resourceId) {
if (resourceTokens == null) {
throw new IllegalArgumentException("resourceTokens");
}
String resourceToken = null;
if (resourceTokens.containsKey(resourceId) && resourceTokens.get(resourceId) != null) {
resourceToken = resourceTokens.get(resourceId);
} else if (StringUtils.isEmpty(path) || StringUtils.isEmpty(resourceId)) {
if (resourceTokens.size() > 0) {
resourceToken = resourceTokens.values().iterator().next();
}
} else {
String[] pathParts = StringUtils.split(path, "/");
String[] resourceTypes = {"dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions",
"attachments", "media", "conflicts"};
HashSet<String> resourceTypesSet = new HashSet<String>();
Collections.addAll(resourceTypesSet, resourceTypes);
for (int i = pathParts.length - 1; i >= 0; --i) {
if (!resourceTypesSet.contains(pathParts[i]) && resourceTokens.containsKey(pathParts[i])) {
resourceToken = resourceTokens.get(pathParts[i]);
}
}
}
return resourceToken;
}
/*
* Ensures that this.macInstance is initialized
* In-case of credential change, optimistically will try to refresh the macInstance
*
* Implementation is non-blocking, the one which acquire the lock will try to refresh
* with new credentials
*
* NOTE: Calling it CTOR ensured that default is initialized.
*/
private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.UTF_8);
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256");
try {
Mac macInstance = Mac.getInstance("HMACSHA256");
macInstance.init(signingKey);
this.masterKeyHashCode = masterKeyLatestHashCode;
this.macInstance = macInstance;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
} finally {
this.macInstanceLock.unlock();
}
}
}
}
} |
Only when the hashcode is different is when this code path hits. Few triggering points are - new client creation starting point - key-changed If the assumption is that its a both credentials are valid for a good period of time, the refresh can be asynchronous. Can we make that assumption? | private Mac getMacInstance() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
synchronized (this.credential) {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.UTF_8);
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256");
try {
Mac macInstance = Mac.getInstance("HMACSHA256");
macInstance.init(signingKey);
this.masterKeyHashCode = masterKeyLatestHashCode;
this.macInstance = macInstance;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
}
}
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
} | synchronized (this.credential) { | private Mac getMacInstance() {
reInitializeIfPossible();
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredential credential) {
this.credential = credential;
}
private static String getResourceSegment(ResourceType resourceType) {
switch (resourceType) {
case Attachment:
return Paths.ATTACHMENTS_PATH_SEGMENT;
case Database:
return Paths.DATABASES_PATH_SEGMENT;
case Conflict:
return Paths.CONFLICTS_PATH_SEGMENT;
case Document:
return Paths.DOCUMENTS_PATH_SEGMENT;
case DocumentCollection:
return Paths.COLLECTIONS_PATH_SEGMENT;
case Offer:
return Paths.OFFERS_PATH_SEGMENT;
case Permission:
return Paths.PERMISSIONS_PATH_SEGMENT;
case StoredProcedure:
return Paths.STORED_PROCEDURES_PATH_SEGMENT;
case Trigger:
return Paths.TRIGGERS_PATH_SEGMENT;
case UserDefinedFunction:
return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT;
case User:
return Paths.USERS_PATH_SEGMENT;
case PartitionKeyRange:
return Paths.PARTITION_KEY_RANGES_PATH_SEGMENT;
case Media:
return Paths.MEDIA_PATH_SEGMENT;
case DatabaseAccount:
return "";
default:
return null;
}
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb.
* @param resourceIdOrFullName the resource id or full name
* @param resourceType the resource type.
* @param headers the request headers.
* @return the key authorization signature.
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
ResourceType resourceType,
Map<String, String> headers) {
return this.generateKeyAuthorizationSignature(verb, resourceIdOrFullName,
BaseAuthorizationTokenProvider.getResourceSegment(resourceType), headers);
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb
* @param resourceIdOrFullName the resource id or full name
* @param resourceSegment the resource segment
* @param headers the request headers
* @return the key authorization signature
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
String resourceSegment,
Map<String, String> headers) {
if (verb == null) {
throw new IllegalArgumentException("verb");
}
if (resourceIdOrFullName == null) {
resourceIdOrFullName = "";
}
if (resourceSegment == null) {
throw new IllegalArgumentException("resourceSegment");
}
if (headers == null) {
throw new IllegalArgumentException("headers");
}
if (StringUtils.isEmpty(this.credential.getKey())) {
throw new IllegalArgumentException("key credentials cannot be empty");
}
if(!PathsHelper.isNameBased(resourceIdOrFullName)) {
resourceIdOrFullName = resourceIdOrFullName.toLowerCase(Locale.ROOT);
}
StringBuilder body = new StringBuilder();
body.append(ModelBridgeInternal.toLower(verb))
.append('\n')
.append(resourceSegment)
.append('\n')
.append(resourceIdOrFullName)
.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.X_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.X_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.HTTP_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.HTTP_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
Mac mac = getMacInstance();
byte[] digest = mac.doFinal(body.toString().getBytes(StandardCharsets.UTF_8));
String auth = Utils.encodeBase64String(digest);
return AUTH_PREFIX + auth;
}
/**
* This API is a helper method to create auth header based on client request using resourceTokens.
*
* @param resourceTokens the resource tokens.
* @param path the path.
* @param resourceId the resource id.
* @return the authorization token.
*/
public String getAuthorizationTokenUsingResourceTokens(Map<String, String> resourceTokens,
String path,
String resourceId) {
if (resourceTokens == null) {
throw new IllegalArgumentException("resourceTokens");
}
String resourceToken = null;
if (resourceTokens.containsKey(resourceId) && resourceTokens.get(resourceId) != null) {
resourceToken = resourceTokens.get(resourceId);
} else if (StringUtils.isEmpty(path) || StringUtils.isEmpty(resourceId)) {
if (resourceTokens.size() > 0) {
resourceToken = resourceTokens.values().iterator().next();
}
} else {
String[] pathParts = StringUtils.split(path, "/");
String[] resourceTypes = {"dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions",
"attachments", "media", "conflicts"};
HashSet<String> resourceTypesSet = new HashSet<String>();
Collections.addAll(resourceTypesSet, resourceTypes);
for (int i = pathParts.length - 1; i >= 0; --i) {
if (!resourceTypesSet.contains(pathParts[i]) && resourceTokens.containsKey(pathParts[i])) {
resourceToken = resourceTokens.get(pathParts[i]);
}
}
}
return resourceToken;
}
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredential credential) {
this.credential = credential;
reInitializeIfPossible();
}
private static String getResourceSegment(ResourceType resourceType) {
switch (resourceType) {
case Attachment:
return Paths.ATTACHMENTS_PATH_SEGMENT;
case Database:
return Paths.DATABASES_PATH_SEGMENT;
case Conflict:
return Paths.CONFLICTS_PATH_SEGMENT;
case Document:
return Paths.DOCUMENTS_PATH_SEGMENT;
case DocumentCollection:
return Paths.COLLECTIONS_PATH_SEGMENT;
case Offer:
return Paths.OFFERS_PATH_SEGMENT;
case Permission:
return Paths.PERMISSIONS_PATH_SEGMENT;
case StoredProcedure:
return Paths.STORED_PROCEDURES_PATH_SEGMENT;
case Trigger:
return Paths.TRIGGERS_PATH_SEGMENT;
case UserDefinedFunction:
return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT;
case User:
return Paths.USERS_PATH_SEGMENT;
case PartitionKeyRange:
return Paths.PARTITION_KEY_RANGES_PATH_SEGMENT;
case Media:
return Paths.MEDIA_PATH_SEGMENT;
case DatabaseAccount:
return "";
default:
return null;
}
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb.
* @param resourceIdOrFullName the resource id or full name
* @param resourceType the resource type.
* @param headers the request headers.
* @return the key authorization signature.
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
ResourceType resourceType,
Map<String, String> headers) {
return this.generateKeyAuthorizationSignature(verb, resourceIdOrFullName,
BaseAuthorizationTokenProvider.getResourceSegment(resourceType), headers);
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb
* @param resourceIdOrFullName the resource id or full name
* @param resourceSegment the resource segment
* @param headers the request headers
* @return the key authorization signature
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
String resourceSegment,
Map<String, String> headers) {
if (verb == null) {
throw new IllegalArgumentException("verb");
}
if (resourceIdOrFullName == null) {
resourceIdOrFullName = "";
}
if (resourceSegment == null) {
throw new IllegalArgumentException("resourceSegment");
}
if (headers == null) {
throw new IllegalArgumentException("headers");
}
if (StringUtils.isEmpty(this.credential.getKey())) {
throw new IllegalArgumentException("key credentials cannot be empty");
}
if(!PathsHelper.isNameBased(resourceIdOrFullName)) {
resourceIdOrFullName = resourceIdOrFullName.toLowerCase(Locale.ROOT);
}
StringBuilder body = new StringBuilder();
body.append(ModelBridgeInternal.toLower(verb))
.append('\n')
.append(resourceSegment)
.append('\n')
.append(resourceIdOrFullName)
.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.X_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.X_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.HTTP_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.HTTP_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
Mac mac = getMacInstance();
byte[] digest = mac.doFinal(body.toString().getBytes(StandardCharsets.UTF_8));
String auth = Utils.encodeBase64String(digest);
return AUTH_PREFIX + auth;
}
/**
* This API is a helper method to create auth header based on client request using resourceTokens.
*
* @param resourceTokens the resource tokens.
* @param path the path.
* @param resourceId the resource id.
* @return the authorization token.
*/
public String getAuthorizationTokenUsingResourceTokens(Map<String, String> resourceTokens,
String path,
String resourceId) {
if (resourceTokens == null) {
throw new IllegalArgumentException("resourceTokens");
}
String resourceToken = null;
if (resourceTokens.containsKey(resourceId) && resourceTokens.get(resourceId) != null) {
resourceToken = resourceTokens.get(resourceId);
} else if (StringUtils.isEmpty(path) || StringUtils.isEmpty(resourceId)) {
if (resourceTokens.size() > 0) {
resourceToken = resourceTokens.values().iterator().next();
}
} else {
String[] pathParts = StringUtils.split(path, "/");
String[] resourceTypes = {"dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions",
"attachments", "media", "conflicts"};
HashSet<String> resourceTypesSet = new HashSet<String>();
Collections.addAll(resourceTypesSet, resourceTypes);
for (int i = pathParts.length - 1; i >= 0; --i) {
if (!resourceTypesSet.contains(pathParts[i]) && resourceTokens.containsKey(pathParts[i])) {
resourceToken = resourceTokens.get(pathParts[i]);
}
}
}
return resourceToken;
}
/*
* Ensures that this.macInstance is initialized
* In-case of credential change, optimistically will try to refresh the macInstance
*
* Implementation is non-blocking, the one which acquire the lock will try to refresh
* with new credentials
*
* NOTE: Calling it CTOR ensured that default is initialized.
*/
private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.UTF_8);
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256");
try {
Mac macInstance = Mac.getInstance("HMACSHA256");
macInstance.init(signingKey);
this.masterKeyHashCode = masterKeyLatestHashCode;
this.macInstance = macInstance;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
} finally {
this.macInstanceLock.unlock();
}
}
}
}
} |
Yes, that is correct assumption. We can proceed with this PR. looks good to me. | private Mac getMacInstance() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
synchronized (this.credential) {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.UTF_8);
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256");
try {
Mac macInstance = Mac.getInstance("HMACSHA256");
macInstance.init(signingKey);
this.masterKeyHashCode = masterKeyLatestHashCode;
this.macInstance = macInstance;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
}
}
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
} | synchronized (this.credential) { | private Mac getMacInstance() {
reInitializeIfPossible();
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredential credential) {
this.credential = credential;
}
private static String getResourceSegment(ResourceType resourceType) {
switch (resourceType) {
case Attachment:
return Paths.ATTACHMENTS_PATH_SEGMENT;
case Database:
return Paths.DATABASES_PATH_SEGMENT;
case Conflict:
return Paths.CONFLICTS_PATH_SEGMENT;
case Document:
return Paths.DOCUMENTS_PATH_SEGMENT;
case DocumentCollection:
return Paths.COLLECTIONS_PATH_SEGMENT;
case Offer:
return Paths.OFFERS_PATH_SEGMENT;
case Permission:
return Paths.PERMISSIONS_PATH_SEGMENT;
case StoredProcedure:
return Paths.STORED_PROCEDURES_PATH_SEGMENT;
case Trigger:
return Paths.TRIGGERS_PATH_SEGMENT;
case UserDefinedFunction:
return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT;
case User:
return Paths.USERS_PATH_SEGMENT;
case PartitionKeyRange:
return Paths.PARTITION_KEY_RANGES_PATH_SEGMENT;
case Media:
return Paths.MEDIA_PATH_SEGMENT;
case DatabaseAccount:
return "";
default:
return null;
}
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb.
* @param resourceIdOrFullName the resource id or full name
* @param resourceType the resource type.
* @param headers the request headers.
* @return the key authorization signature.
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
ResourceType resourceType,
Map<String, String> headers) {
return this.generateKeyAuthorizationSignature(verb, resourceIdOrFullName,
BaseAuthorizationTokenProvider.getResourceSegment(resourceType), headers);
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb
* @param resourceIdOrFullName the resource id or full name
* @param resourceSegment the resource segment
* @param headers the request headers
* @return the key authorization signature
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
String resourceSegment,
Map<String, String> headers) {
if (verb == null) {
throw new IllegalArgumentException("verb");
}
if (resourceIdOrFullName == null) {
resourceIdOrFullName = "";
}
if (resourceSegment == null) {
throw new IllegalArgumentException("resourceSegment");
}
if (headers == null) {
throw new IllegalArgumentException("headers");
}
if (StringUtils.isEmpty(this.credential.getKey())) {
throw new IllegalArgumentException("key credentials cannot be empty");
}
if(!PathsHelper.isNameBased(resourceIdOrFullName)) {
resourceIdOrFullName = resourceIdOrFullName.toLowerCase(Locale.ROOT);
}
StringBuilder body = new StringBuilder();
body.append(ModelBridgeInternal.toLower(verb))
.append('\n')
.append(resourceSegment)
.append('\n')
.append(resourceIdOrFullName)
.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.X_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.X_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.HTTP_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.HTTP_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
Mac mac = getMacInstance();
byte[] digest = mac.doFinal(body.toString().getBytes(StandardCharsets.UTF_8));
String auth = Utils.encodeBase64String(digest);
return AUTH_PREFIX + auth;
}
/**
* This API is a helper method to create auth header based on client request using resourceTokens.
*
* @param resourceTokens the resource tokens.
* @param path the path.
* @param resourceId the resource id.
* @return the authorization token.
*/
public String getAuthorizationTokenUsingResourceTokens(Map<String, String> resourceTokens,
String path,
String resourceId) {
if (resourceTokens == null) {
throw new IllegalArgumentException("resourceTokens");
}
String resourceToken = null;
if (resourceTokens.containsKey(resourceId) && resourceTokens.get(resourceId) != null) {
resourceToken = resourceTokens.get(resourceId);
} else if (StringUtils.isEmpty(path) || StringUtils.isEmpty(resourceId)) {
if (resourceTokens.size() > 0) {
resourceToken = resourceTokens.values().iterator().next();
}
} else {
String[] pathParts = StringUtils.split(path, "/");
String[] resourceTypes = {"dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions",
"attachments", "media", "conflicts"};
HashSet<String> resourceTypesSet = new HashSet<String>();
Collections.addAll(resourceTypesSet, resourceTypes);
for (int i = pathParts.length - 1; i >= 0; --i) {
if (!resourceTypesSet.contains(pathParts[i]) && resourceTokens.containsKey(pathParts[i])) {
resourceToken = resourceTokens.get(pathParts[i]);
}
}
}
return resourceToken;
}
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredential credential) {
this.credential = credential;
reInitializeIfPossible();
}
private static String getResourceSegment(ResourceType resourceType) {
switch (resourceType) {
case Attachment:
return Paths.ATTACHMENTS_PATH_SEGMENT;
case Database:
return Paths.DATABASES_PATH_SEGMENT;
case Conflict:
return Paths.CONFLICTS_PATH_SEGMENT;
case Document:
return Paths.DOCUMENTS_PATH_SEGMENT;
case DocumentCollection:
return Paths.COLLECTIONS_PATH_SEGMENT;
case Offer:
return Paths.OFFERS_PATH_SEGMENT;
case Permission:
return Paths.PERMISSIONS_PATH_SEGMENT;
case StoredProcedure:
return Paths.STORED_PROCEDURES_PATH_SEGMENT;
case Trigger:
return Paths.TRIGGERS_PATH_SEGMENT;
case UserDefinedFunction:
return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT;
case User:
return Paths.USERS_PATH_SEGMENT;
case PartitionKeyRange:
return Paths.PARTITION_KEY_RANGES_PATH_SEGMENT;
case Media:
return Paths.MEDIA_PATH_SEGMENT;
case DatabaseAccount:
return "";
default:
return null;
}
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb.
* @param resourceIdOrFullName the resource id or full name
* @param resourceType the resource type.
* @param headers the request headers.
* @return the key authorization signature.
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
ResourceType resourceType,
Map<String, String> headers) {
return this.generateKeyAuthorizationSignature(verb, resourceIdOrFullName,
BaseAuthorizationTokenProvider.getResourceSegment(resourceType), headers);
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb
* @param resourceIdOrFullName the resource id or full name
* @param resourceSegment the resource segment
* @param headers the request headers
* @return the key authorization signature
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
String resourceSegment,
Map<String, String> headers) {
if (verb == null) {
throw new IllegalArgumentException("verb");
}
if (resourceIdOrFullName == null) {
resourceIdOrFullName = "";
}
if (resourceSegment == null) {
throw new IllegalArgumentException("resourceSegment");
}
if (headers == null) {
throw new IllegalArgumentException("headers");
}
if (StringUtils.isEmpty(this.credential.getKey())) {
throw new IllegalArgumentException("key credentials cannot be empty");
}
if(!PathsHelper.isNameBased(resourceIdOrFullName)) {
resourceIdOrFullName = resourceIdOrFullName.toLowerCase(Locale.ROOT);
}
StringBuilder body = new StringBuilder();
body.append(ModelBridgeInternal.toLower(verb))
.append('\n')
.append(resourceSegment)
.append('\n')
.append(resourceIdOrFullName)
.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.X_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.X_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.HTTP_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.HTTP_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
Mac mac = getMacInstance();
byte[] digest = mac.doFinal(body.toString().getBytes(StandardCharsets.UTF_8));
String auth = Utils.encodeBase64String(digest);
return AUTH_PREFIX + auth;
}
/**
* This API is a helper method to create auth header based on client request using resourceTokens.
*
* @param resourceTokens the resource tokens.
* @param path the path.
* @param resourceId the resource id.
* @return the authorization token.
*/
public String getAuthorizationTokenUsingResourceTokens(Map<String, String> resourceTokens,
String path,
String resourceId) {
if (resourceTokens == null) {
throw new IllegalArgumentException("resourceTokens");
}
String resourceToken = null;
if (resourceTokens.containsKey(resourceId) && resourceTokens.get(resourceId) != null) {
resourceToken = resourceTokens.get(resourceId);
} else if (StringUtils.isEmpty(path) || StringUtils.isEmpty(resourceId)) {
if (resourceTokens.size() > 0) {
resourceToken = resourceTokens.values().iterator().next();
}
} else {
String[] pathParts = StringUtils.split(path, "/");
String[] resourceTypes = {"dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions",
"attachments", "media", "conflicts"};
HashSet<String> resourceTypesSet = new HashSet<String>();
Collections.addAll(resourceTypesSet, resourceTypes);
for (int i = pathParts.length - 1; i >= 0; --i) {
if (!resourceTypesSet.contains(pathParts[i]) && resourceTokens.containsKey(pathParts[i])) {
resourceToken = resourceTokens.get(pathParts[i]);
}
}
}
return resourceToken;
}
/*
* Ensures that this.macInstance is initialized
* In-case of credential change, optimistically will try to refresh the macInstance
*
* Implementation is non-blocking, the one which acquire the lock will try to refresh
* with new credentials
*
* NOTE: Calling it CTOR ensured that default is initialized.
*/
private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.UTF_8);
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256");
try {
Mac macInstance = Mac.getInstance("HMACSHA256");
macInstance.init(signingKey);
this.masterKeyHashCode = masterKeyLatestHashCode;
this.macInstance = macInstance;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
} finally {
this.macInstanceLock.unlock();
}
}
}
}
} |
Refreshed the implementation to eventually move to the new key. One thread will try to refresh where as others will move forward with current key. | private Mac getMacInstance() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
synchronized (this.credential) {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.UTF_8);
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256");
try {
Mac macInstance = Mac.getInstance("HMACSHA256");
macInstance.init(signingKey);
this.masterKeyHashCode = masterKeyLatestHashCode;
this.macInstance = macInstance;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
}
}
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
} | synchronized (this.credential) { | private Mac getMacInstance() {
reInitializeIfPossible();
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredential credential) {
this.credential = credential;
}
private static String getResourceSegment(ResourceType resourceType) {
switch (resourceType) {
case Attachment:
return Paths.ATTACHMENTS_PATH_SEGMENT;
case Database:
return Paths.DATABASES_PATH_SEGMENT;
case Conflict:
return Paths.CONFLICTS_PATH_SEGMENT;
case Document:
return Paths.DOCUMENTS_PATH_SEGMENT;
case DocumentCollection:
return Paths.COLLECTIONS_PATH_SEGMENT;
case Offer:
return Paths.OFFERS_PATH_SEGMENT;
case Permission:
return Paths.PERMISSIONS_PATH_SEGMENT;
case StoredProcedure:
return Paths.STORED_PROCEDURES_PATH_SEGMENT;
case Trigger:
return Paths.TRIGGERS_PATH_SEGMENT;
case UserDefinedFunction:
return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT;
case User:
return Paths.USERS_PATH_SEGMENT;
case PartitionKeyRange:
return Paths.PARTITION_KEY_RANGES_PATH_SEGMENT;
case Media:
return Paths.MEDIA_PATH_SEGMENT;
case DatabaseAccount:
return "";
default:
return null;
}
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb.
* @param resourceIdOrFullName the resource id or full name
* @param resourceType the resource type.
* @param headers the request headers.
* @return the key authorization signature.
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
ResourceType resourceType,
Map<String, String> headers) {
return this.generateKeyAuthorizationSignature(verb, resourceIdOrFullName,
BaseAuthorizationTokenProvider.getResourceSegment(resourceType), headers);
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb
* @param resourceIdOrFullName the resource id or full name
* @param resourceSegment the resource segment
* @param headers the request headers
* @return the key authorization signature
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
String resourceSegment,
Map<String, String> headers) {
if (verb == null) {
throw new IllegalArgumentException("verb");
}
if (resourceIdOrFullName == null) {
resourceIdOrFullName = "";
}
if (resourceSegment == null) {
throw new IllegalArgumentException("resourceSegment");
}
if (headers == null) {
throw new IllegalArgumentException("headers");
}
if (StringUtils.isEmpty(this.credential.getKey())) {
throw new IllegalArgumentException("key credentials cannot be empty");
}
if(!PathsHelper.isNameBased(resourceIdOrFullName)) {
resourceIdOrFullName = resourceIdOrFullName.toLowerCase(Locale.ROOT);
}
StringBuilder body = new StringBuilder();
body.append(ModelBridgeInternal.toLower(verb))
.append('\n')
.append(resourceSegment)
.append('\n')
.append(resourceIdOrFullName)
.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.X_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.X_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.HTTP_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.HTTP_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
Mac mac = getMacInstance();
byte[] digest = mac.doFinal(body.toString().getBytes(StandardCharsets.UTF_8));
String auth = Utils.encodeBase64String(digest);
return AUTH_PREFIX + auth;
}
/**
* This API is a helper method to create auth header based on client request using resourceTokens.
*
* @param resourceTokens the resource tokens.
* @param path the path.
* @param resourceId the resource id.
* @return the authorization token.
*/
public String getAuthorizationTokenUsingResourceTokens(Map<String, String> resourceTokens,
String path,
String resourceId) {
if (resourceTokens == null) {
throw new IllegalArgumentException("resourceTokens");
}
String resourceToken = null;
if (resourceTokens.containsKey(resourceId) && resourceTokens.get(resourceId) != null) {
resourceToken = resourceTokens.get(resourceId);
} else if (StringUtils.isEmpty(path) || StringUtils.isEmpty(resourceId)) {
if (resourceTokens.size() > 0) {
resourceToken = resourceTokens.values().iterator().next();
}
} else {
String[] pathParts = StringUtils.split(path, "/");
String[] resourceTypes = {"dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions",
"attachments", "media", "conflicts"};
HashSet<String> resourceTypesSet = new HashSet<String>();
Collections.addAll(resourceTypesSet, resourceTypes);
for (int i = pathParts.length - 1; i >= 0; --i) {
if (!resourceTypesSet.contains(pathParts[i]) && resourceTokens.containsKey(pathParts[i])) {
resourceToken = resourceTokens.get(pathParts[i]);
}
}
}
return resourceToken;
}
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredential credential) {
this.credential = credential;
reInitializeIfPossible();
}
private static String getResourceSegment(ResourceType resourceType) {
switch (resourceType) {
case Attachment:
return Paths.ATTACHMENTS_PATH_SEGMENT;
case Database:
return Paths.DATABASES_PATH_SEGMENT;
case Conflict:
return Paths.CONFLICTS_PATH_SEGMENT;
case Document:
return Paths.DOCUMENTS_PATH_SEGMENT;
case DocumentCollection:
return Paths.COLLECTIONS_PATH_SEGMENT;
case Offer:
return Paths.OFFERS_PATH_SEGMENT;
case Permission:
return Paths.PERMISSIONS_PATH_SEGMENT;
case StoredProcedure:
return Paths.STORED_PROCEDURES_PATH_SEGMENT;
case Trigger:
return Paths.TRIGGERS_PATH_SEGMENT;
case UserDefinedFunction:
return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT;
case User:
return Paths.USERS_PATH_SEGMENT;
case PartitionKeyRange:
return Paths.PARTITION_KEY_RANGES_PATH_SEGMENT;
case Media:
return Paths.MEDIA_PATH_SEGMENT;
case DatabaseAccount:
return "";
default:
return null;
}
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb.
* @param resourceIdOrFullName the resource id or full name
* @param resourceType the resource type.
* @param headers the request headers.
* @return the key authorization signature.
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
ResourceType resourceType,
Map<String, String> headers) {
return this.generateKeyAuthorizationSignature(verb, resourceIdOrFullName,
BaseAuthorizationTokenProvider.getResourceSegment(resourceType), headers);
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb
* @param resourceIdOrFullName the resource id or full name
* @param resourceSegment the resource segment
* @param headers the request headers
* @return the key authorization signature
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
String resourceSegment,
Map<String, String> headers) {
if (verb == null) {
throw new IllegalArgumentException("verb");
}
if (resourceIdOrFullName == null) {
resourceIdOrFullName = "";
}
if (resourceSegment == null) {
throw new IllegalArgumentException("resourceSegment");
}
if (headers == null) {
throw new IllegalArgumentException("headers");
}
if (StringUtils.isEmpty(this.credential.getKey())) {
throw new IllegalArgumentException("key credentials cannot be empty");
}
if(!PathsHelper.isNameBased(resourceIdOrFullName)) {
resourceIdOrFullName = resourceIdOrFullName.toLowerCase(Locale.ROOT);
}
StringBuilder body = new StringBuilder();
body.append(ModelBridgeInternal.toLower(verb))
.append('\n')
.append(resourceSegment)
.append('\n')
.append(resourceIdOrFullName)
.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.X_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.X_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.HTTP_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.HTTP_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
Mac mac = getMacInstance();
byte[] digest = mac.doFinal(body.toString().getBytes(StandardCharsets.UTF_8));
String auth = Utils.encodeBase64String(digest);
return AUTH_PREFIX + auth;
}
/**
* This API is a helper method to create auth header based on client request using resourceTokens.
*
* @param resourceTokens the resource tokens.
* @param path the path.
* @param resourceId the resource id.
* @return the authorization token.
*/
public String getAuthorizationTokenUsingResourceTokens(Map<String, String> resourceTokens,
String path,
String resourceId) {
if (resourceTokens == null) {
throw new IllegalArgumentException("resourceTokens");
}
String resourceToken = null;
if (resourceTokens.containsKey(resourceId) && resourceTokens.get(resourceId) != null) {
resourceToken = resourceTokens.get(resourceId);
} else if (StringUtils.isEmpty(path) || StringUtils.isEmpty(resourceId)) {
if (resourceTokens.size() > 0) {
resourceToken = resourceTokens.values().iterator().next();
}
} else {
String[] pathParts = StringUtils.split(path, "/");
String[] resourceTypes = {"dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions",
"attachments", "media", "conflicts"};
HashSet<String> resourceTypesSet = new HashSet<String>();
Collections.addAll(resourceTypesSet, resourceTypes);
for (int i = pathParts.length - 1; i >= 0; --i) {
if (!resourceTypesSet.contains(pathParts[i]) && resourceTokens.containsKey(pathParts[i])) {
resourceToken = resourceTokens.get(pathParts[i]);
}
}
}
return resourceToken;
}
/*
* Ensures that this.macInstance is initialized
* In-case of credential change, optimistically will try to refresh the macInstance
*
* Implementation is non-blocking, the one which acquire the lock will try to refresh
* with new credentials
*
* NOTE: Calling it CTOR ensured that default is initialized.
*/
private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.UTF_8);
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256");
try {
Mac macInstance = Mac.getInstance("HMACSHA256");
macInstance.init(signingKey);
this.masterKeyHashCode = masterKeyLatestHashCode;
this.macInstance = macInstance;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
} finally {
this.macInstanceLock.unlock();
}
}
}
}
} |
what is the benefit of using ReentrantLock here? key rotation doesn't happen often and this adds a bit to complexity. Why aren't we simply using synchronized? | private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.UTF_8);
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256");
try {
Mac macInstance = Mac.getInstance("HMACSHA256");
macInstance.init(signingKey);
this.masterKeyHashCode = masterKeyLatestHashCode;
this.macInstance = macInstance;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
} finally {
this.macInstanceLock.unlock();
}
}
}
} | boolean lockAcquired = this.macInstanceLock.tryLock(); | private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.UTF_8);
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256");
try {
Mac macInstance = Mac.getInstance("HMACSHA256");
macInstance.init(signingKey);
this.masterKeyHashCode = masterKeyLatestHashCode;
this.macInstance = macInstance;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
} finally {
this.macInstanceLock.unlock();
}
}
}
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredential credential) {
this.credential = credential;
reInitializeIfPossible();
}
private static String getResourceSegment(ResourceType resourceType) {
switch (resourceType) {
case Attachment:
return Paths.ATTACHMENTS_PATH_SEGMENT;
case Database:
return Paths.DATABASES_PATH_SEGMENT;
case Conflict:
return Paths.CONFLICTS_PATH_SEGMENT;
case Document:
return Paths.DOCUMENTS_PATH_SEGMENT;
case DocumentCollection:
return Paths.COLLECTIONS_PATH_SEGMENT;
case Offer:
return Paths.OFFERS_PATH_SEGMENT;
case Permission:
return Paths.PERMISSIONS_PATH_SEGMENT;
case StoredProcedure:
return Paths.STORED_PROCEDURES_PATH_SEGMENT;
case Trigger:
return Paths.TRIGGERS_PATH_SEGMENT;
case UserDefinedFunction:
return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT;
case User:
return Paths.USERS_PATH_SEGMENT;
case PartitionKeyRange:
return Paths.PARTITION_KEY_RANGES_PATH_SEGMENT;
case Media:
return Paths.MEDIA_PATH_SEGMENT;
case DatabaseAccount:
return "";
default:
return null;
}
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb.
* @param resourceIdOrFullName the resource id or full name
* @param resourceType the resource type.
* @param headers the request headers.
* @return the key authorization signature.
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
ResourceType resourceType,
Map<String, String> headers) {
return this.generateKeyAuthorizationSignature(verb, resourceIdOrFullName,
BaseAuthorizationTokenProvider.getResourceSegment(resourceType), headers);
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb
* @param resourceIdOrFullName the resource id or full name
* @param resourceSegment the resource segment
* @param headers the request headers
* @return the key authorization signature
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
String resourceSegment,
Map<String, String> headers) {
if (verb == null) {
throw new IllegalArgumentException("verb");
}
if (resourceIdOrFullName == null) {
resourceIdOrFullName = "";
}
if (resourceSegment == null) {
throw new IllegalArgumentException("resourceSegment");
}
if (headers == null) {
throw new IllegalArgumentException("headers");
}
if (StringUtils.isEmpty(this.credential.getKey())) {
throw new IllegalArgumentException("key credentials cannot be empty");
}
if(!PathsHelper.isNameBased(resourceIdOrFullName)) {
resourceIdOrFullName = resourceIdOrFullName.toLowerCase(Locale.ROOT);
}
StringBuilder body = new StringBuilder();
body.append(ModelBridgeInternal.toLower(verb))
.append('\n')
.append(resourceSegment)
.append('\n')
.append(resourceIdOrFullName)
.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.X_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.X_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.HTTP_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.HTTP_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
Mac mac = getMacInstance();
byte[] digest = mac.doFinal(body.toString().getBytes(StandardCharsets.UTF_8));
String auth = Utils.encodeBase64String(digest);
return AUTH_PREFIX + auth;
}
/**
* This API is a helper method to create auth header based on client request using resourceTokens.
*
* @param resourceTokens the resource tokens.
* @param path the path.
* @param resourceId the resource id.
* @return the authorization token.
*/
public String getAuthorizationTokenUsingResourceTokens(Map<String, String> resourceTokens,
String path,
String resourceId) {
if (resourceTokens == null) {
throw new IllegalArgumentException("resourceTokens");
}
String resourceToken = null;
if (resourceTokens.containsKey(resourceId) && resourceTokens.get(resourceId) != null) {
resourceToken = resourceTokens.get(resourceId);
} else if (StringUtils.isEmpty(path) || StringUtils.isEmpty(resourceId)) {
if (resourceTokens.size() > 0) {
resourceToken = resourceTokens.values().iterator().next();
}
} else {
String[] pathParts = StringUtils.split(path, "/");
String[] resourceTypes = {"dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions",
"attachments", "media", "conflicts"};
HashSet<String> resourceTypesSet = new HashSet<String>();
Collections.addAll(resourceTypesSet, resourceTypes);
for (int i = pathParts.length - 1; i >= 0; --i) {
if (!resourceTypesSet.contains(pathParts[i]) && resourceTokens.containsKey(pathParts[i])) {
resourceToken = resourceTokens.get(pathParts[i]);
}
}
}
return resourceToken;
}
private Mac getMacInstance() {
reInitializeIfPossible();
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
}
/*
* Ensures that this.macInstance is initialized
* In-case of credential change, optimistically will try to refresh the macInstance
*
* Implementation is non-blocking, the one which acquire the lock will try to refresh
* with new credentials
*
* NOTE: Calling it CTOR ensured that default is initialized.
*/
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredential credential) {
this.credential = credential;
reInitializeIfPossible();
}
private static String getResourceSegment(ResourceType resourceType) {
switch (resourceType) {
case Attachment:
return Paths.ATTACHMENTS_PATH_SEGMENT;
case Database:
return Paths.DATABASES_PATH_SEGMENT;
case Conflict:
return Paths.CONFLICTS_PATH_SEGMENT;
case Document:
return Paths.DOCUMENTS_PATH_SEGMENT;
case DocumentCollection:
return Paths.COLLECTIONS_PATH_SEGMENT;
case Offer:
return Paths.OFFERS_PATH_SEGMENT;
case Permission:
return Paths.PERMISSIONS_PATH_SEGMENT;
case StoredProcedure:
return Paths.STORED_PROCEDURES_PATH_SEGMENT;
case Trigger:
return Paths.TRIGGERS_PATH_SEGMENT;
case UserDefinedFunction:
return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT;
case User:
return Paths.USERS_PATH_SEGMENT;
case PartitionKeyRange:
return Paths.PARTITION_KEY_RANGES_PATH_SEGMENT;
case Media:
return Paths.MEDIA_PATH_SEGMENT;
case DatabaseAccount:
return "";
default:
return null;
}
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb.
* @param resourceIdOrFullName the resource id or full name
* @param resourceType the resource type.
* @param headers the request headers.
* @return the key authorization signature.
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
ResourceType resourceType,
Map<String, String> headers) {
return this.generateKeyAuthorizationSignature(verb, resourceIdOrFullName,
BaseAuthorizationTokenProvider.getResourceSegment(resourceType), headers);
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb
* @param resourceIdOrFullName the resource id or full name
* @param resourceSegment the resource segment
* @param headers the request headers
* @return the key authorization signature
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
String resourceSegment,
Map<String, String> headers) {
if (verb == null) {
throw new IllegalArgumentException("verb");
}
if (resourceIdOrFullName == null) {
resourceIdOrFullName = "";
}
if (resourceSegment == null) {
throw new IllegalArgumentException("resourceSegment");
}
if (headers == null) {
throw new IllegalArgumentException("headers");
}
if (StringUtils.isEmpty(this.credential.getKey())) {
throw new IllegalArgumentException("key credentials cannot be empty");
}
if(!PathsHelper.isNameBased(resourceIdOrFullName)) {
resourceIdOrFullName = resourceIdOrFullName.toLowerCase(Locale.ROOT);
}
StringBuilder body = new StringBuilder();
body.append(ModelBridgeInternal.toLower(verb))
.append('\n')
.append(resourceSegment)
.append('\n')
.append(resourceIdOrFullName)
.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.X_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.X_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.HTTP_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.HTTP_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
Mac mac = getMacInstance();
byte[] digest = mac.doFinal(body.toString().getBytes(StandardCharsets.UTF_8));
String auth = Utils.encodeBase64String(digest);
return AUTH_PREFIX + auth;
}
/**
* This API is a helper method to create auth header based on client request using resourceTokens.
*
* @param resourceTokens the resource tokens.
* @param path the path.
* @param resourceId the resource id.
* @return the authorization token.
*/
public String getAuthorizationTokenUsingResourceTokens(Map<String, String> resourceTokens,
String path,
String resourceId) {
if (resourceTokens == null) {
throw new IllegalArgumentException("resourceTokens");
}
String resourceToken = null;
if (resourceTokens.containsKey(resourceId) && resourceTokens.get(resourceId) != null) {
resourceToken = resourceTokens.get(resourceId);
} else if (StringUtils.isEmpty(path) || StringUtils.isEmpty(resourceId)) {
if (resourceTokens.size() > 0) {
resourceToken = resourceTokens.values().iterator().next();
}
} else {
String[] pathParts = StringUtils.split(path, "/");
String[] resourceTypes = {"dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions",
"attachments", "media", "conflicts"};
HashSet<String> resourceTypesSet = new HashSet<String>();
Collections.addAll(resourceTypesSet, resourceTypes);
for (int i = pathParts.length - 1; i >= 0; --i) {
if (!resourceTypesSet.contains(pathParts[i]) && resourceTokens.containsKey(pathParts[i])) {
resourceToken = resourceTokens.get(pathParts[i]);
}
}
}
return resourceToken;
}
private Mac getMacInstance() {
reInitializeIfPossible();
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
}
/*
* Ensures that this.macInstance is initialized
* In-case of credential change, optimistically will try to refresh the macInstance
*
* Implementation is non-blocking, the one which acquire the lock will try to refresh
* with new credentials
*
* NOTE: Calling it CTOR ensured that default is initialized.
*/
} |
reEntrant lock comes into picture only when there is change detected. Otherwise no impact, no? | private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.UTF_8);
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256");
try {
Mac macInstance = Mac.getInstance("HMACSHA256");
macInstance.init(signingKey);
this.masterKeyHashCode = masterKeyLatestHashCode;
this.macInstance = macInstance;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
} finally {
this.macInstanceLock.unlock();
}
}
}
} | boolean lockAcquired = this.macInstanceLock.tryLock(); | private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.UTF_8);
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256");
try {
Mac macInstance = Mac.getInstance("HMACSHA256");
macInstance.init(signingKey);
this.masterKeyHashCode = masterKeyLatestHashCode;
this.macInstance = macInstance;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
} finally {
this.macInstanceLock.unlock();
}
}
}
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredential credential) {
this.credential = credential;
reInitializeIfPossible();
}
private static String getResourceSegment(ResourceType resourceType) {
switch (resourceType) {
case Attachment:
return Paths.ATTACHMENTS_PATH_SEGMENT;
case Database:
return Paths.DATABASES_PATH_SEGMENT;
case Conflict:
return Paths.CONFLICTS_PATH_SEGMENT;
case Document:
return Paths.DOCUMENTS_PATH_SEGMENT;
case DocumentCollection:
return Paths.COLLECTIONS_PATH_SEGMENT;
case Offer:
return Paths.OFFERS_PATH_SEGMENT;
case Permission:
return Paths.PERMISSIONS_PATH_SEGMENT;
case StoredProcedure:
return Paths.STORED_PROCEDURES_PATH_SEGMENT;
case Trigger:
return Paths.TRIGGERS_PATH_SEGMENT;
case UserDefinedFunction:
return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT;
case User:
return Paths.USERS_PATH_SEGMENT;
case PartitionKeyRange:
return Paths.PARTITION_KEY_RANGES_PATH_SEGMENT;
case Media:
return Paths.MEDIA_PATH_SEGMENT;
case DatabaseAccount:
return "";
default:
return null;
}
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb.
* @param resourceIdOrFullName the resource id or full name
* @param resourceType the resource type.
* @param headers the request headers.
* @return the key authorization signature.
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
ResourceType resourceType,
Map<String, String> headers) {
return this.generateKeyAuthorizationSignature(verb, resourceIdOrFullName,
BaseAuthorizationTokenProvider.getResourceSegment(resourceType), headers);
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb
* @param resourceIdOrFullName the resource id or full name
* @param resourceSegment the resource segment
* @param headers the request headers
* @return the key authorization signature
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
String resourceSegment,
Map<String, String> headers) {
if (verb == null) {
throw new IllegalArgumentException("verb");
}
if (resourceIdOrFullName == null) {
resourceIdOrFullName = "";
}
if (resourceSegment == null) {
throw new IllegalArgumentException("resourceSegment");
}
if (headers == null) {
throw new IllegalArgumentException("headers");
}
if (StringUtils.isEmpty(this.credential.getKey())) {
throw new IllegalArgumentException("key credentials cannot be empty");
}
if(!PathsHelper.isNameBased(resourceIdOrFullName)) {
resourceIdOrFullName = resourceIdOrFullName.toLowerCase(Locale.ROOT);
}
StringBuilder body = new StringBuilder();
body.append(ModelBridgeInternal.toLower(verb))
.append('\n')
.append(resourceSegment)
.append('\n')
.append(resourceIdOrFullName)
.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.X_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.X_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.HTTP_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.HTTP_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
Mac mac = getMacInstance();
byte[] digest = mac.doFinal(body.toString().getBytes(StandardCharsets.UTF_8));
String auth = Utils.encodeBase64String(digest);
return AUTH_PREFIX + auth;
}
/**
* This API is a helper method to create auth header based on client request using resourceTokens.
*
* @param resourceTokens the resource tokens.
* @param path the path.
* @param resourceId the resource id.
* @return the authorization token.
*/
public String getAuthorizationTokenUsingResourceTokens(Map<String, String> resourceTokens,
String path,
String resourceId) {
if (resourceTokens == null) {
throw new IllegalArgumentException("resourceTokens");
}
String resourceToken = null;
if (resourceTokens.containsKey(resourceId) && resourceTokens.get(resourceId) != null) {
resourceToken = resourceTokens.get(resourceId);
} else if (StringUtils.isEmpty(path) || StringUtils.isEmpty(resourceId)) {
if (resourceTokens.size() > 0) {
resourceToken = resourceTokens.values().iterator().next();
}
} else {
String[] pathParts = StringUtils.split(path, "/");
String[] resourceTypes = {"dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions",
"attachments", "media", "conflicts"};
HashSet<String> resourceTypesSet = new HashSet<String>();
Collections.addAll(resourceTypesSet, resourceTypes);
for (int i = pathParts.length - 1; i >= 0; --i) {
if (!resourceTypesSet.contains(pathParts[i]) && resourceTokens.containsKey(pathParts[i])) {
resourceToken = resourceTokens.get(pathParts[i]);
}
}
}
return resourceToken;
}
private Mac getMacInstance() {
reInitializeIfPossible();
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
}
/*
* Ensures that this.macInstance is initialized
* In-case of credential change, optimistically will try to refresh the macInstance
*
* Implementation is non-blocking, the one which acquire the lock will try to refresh
* with new credentials
*
* NOTE: Calling it CTOR ensured that default is initialized.
*/
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredential credential) {
this.credential = credential;
reInitializeIfPossible();
}
private static String getResourceSegment(ResourceType resourceType) {
switch (resourceType) {
case Attachment:
return Paths.ATTACHMENTS_PATH_SEGMENT;
case Database:
return Paths.DATABASES_PATH_SEGMENT;
case Conflict:
return Paths.CONFLICTS_PATH_SEGMENT;
case Document:
return Paths.DOCUMENTS_PATH_SEGMENT;
case DocumentCollection:
return Paths.COLLECTIONS_PATH_SEGMENT;
case Offer:
return Paths.OFFERS_PATH_SEGMENT;
case Permission:
return Paths.PERMISSIONS_PATH_SEGMENT;
case StoredProcedure:
return Paths.STORED_PROCEDURES_PATH_SEGMENT;
case Trigger:
return Paths.TRIGGERS_PATH_SEGMENT;
case UserDefinedFunction:
return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT;
case User:
return Paths.USERS_PATH_SEGMENT;
case PartitionKeyRange:
return Paths.PARTITION_KEY_RANGES_PATH_SEGMENT;
case Media:
return Paths.MEDIA_PATH_SEGMENT;
case DatabaseAccount:
return "";
default:
return null;
}
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb.
* @param resourceIdOrFullName the resource id or full name
* @param resourceType the resource type.
* @param headers the request headers.
* @return the key authorization signature.
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
ResourceType resourceType,
Map<String, String> headers) {
return this.generateKeyAuthorizationSignature(verb, resourceIdOrFullName,
BaseAuthorizationTokenProvider.getResourceSegment(resourceType), headers);
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb
* @param resourceIdOrFullName the resource id or full name
* @param resourceSegment the resource segment
* @param headers the request headers
* @return the key authorization signature
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
String resourceSegment,
Map<String, String> headers) {
if (verb == null) {
throw new IllegalArgumentException("verb");
}
if (resourceIdOrFullName == null) {
resourceIdOrFullName = "";
}
if (resourceSegment == null) {
throw new IllegalArgumentException("resourceSegment");
}
if (headers == null) {
throw new IllegalArgumentException("headers");
}
if (StringUtils.isEmpty(this.credential.getKey())) {
throw new IllegalArgumentException("key credentials cannot be empty");
}
if(!PathsHelper.isNameBased(resourceIdOrFullName)) {
resourceIdOrFullName = resourceIdOrFullName.toLowerCase(Locale.ROOT);
}
StringBuilder body = new StringBuilder();
body.append(ModelBridgeInternal.toLower(verb))
.append('\n')
.append(resourceSegment)
.append('\n')
.append(resourceIdOrFullName)
.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.X_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.X_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.HTTP_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.HTTP_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
Mac mac = getMacInstance();
byte[] digest = mac.doFinal(body.toString().getBytes(StandardCharsets.UTF_8));
String auth = Utils.encodeBase64String(digest);
return AUTH_PREFIX + auth;
}
/**
* This API is a helper method to create auth header based on client request using resourceTokens.
*
* @param resourceTokens the resource tokens.
* @param path the path.
* @param resourceId the resource id.
* @return the authorization token.
*/
public String getAuthorizationTokenUsingResourceTokens(Map<String, String> resourceTokens,
String path,
String resourceId) {
if (resourceTokens == null) {
throw new IllegalArgumentException("resourceTokens");
}
String resourceToken = null;
if (resourceTokens.containsKey(resourceId) && resourceTokens.get(resourceId) != null) {
resourceToken = resourceTokens.get(resourceId);
} else if (StringUtils.isEmpty(path) || StringUtils.isEmpty(resourceId)) {
if (resourceTokens.size() > 0) {
resourceToken = resourceTokens.values().iterator().next();
}
} else {
String[] pathParts = StringUtils.split(path, "/");
String[] resourceTypes = {"dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions",
"attachments", "media", "conflicts"};
HashSet<String> resourceTypesSet = new HashSet<String>();
Collections.addAll(resourceTypesSet, resourceTypes);
for (int i = pathParts.length - 1; i >= 0; --i) {
if (!resourceTypesSet.contains(pathParts[i]) && resourceTokens.containsKey(pathParts[i])) {
resourceToken = resourceTokens.get(pathParts[i]);
}
}
}
return resourceToken;
}
private Mac getMacInstance() {
reInitializeIfPossible();
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
}
/*
* Ensures that this.macInstance is initialized
* In-case of credential change, optimistically will try to refresh the macInstance
*
* Implementation is non-blocking, the one which acquire the lock will try to refresh
* with new credentials
*
* NOTE: Calling it CTOR ensured that default is initialized.
*/
} |
that's correct. my question is: isn't `synchronized(.)` easier to use? what's the benefit of reEntrant lock here? I don't think you will get any benefit and its usage is slightly more complicated than using `synchronized(.)` is there any benefit in using reEntrant lock over `synchrnozied()`? | private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.UTF_8);
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256");
try {
Mac macInstance = Mac.getInstance("HMACSHA256");
macInstance.init(signingKey);
this.masterKeyHashCode = masterKeyLatestHashCode;
this.macInstance = macInstance;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
} finally {
this.macInstanceLock.unlock();
}
}
}
} | boolean lockAcquired = this.macInstanceLock.tryLock(); | private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.UTF_8);
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256");
try {
Mac macInstance = Mac.getInstance("HMACSHA256");
macInstance.init(signingKey);
this.masterKeyHashCode = masterKeyLatestHashCode;
this.macInstance = macInstance;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
} finally {
this.macInstanceLock.unlock();
}
}
}
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredential credential) {
this.credential = credential;
reInitializeIfPossible();
}
private static String getResourceSegment(ResourceType resourceType) {
switch (resourceType) {
case Attachment:
return Paths.ATTACHMENTS_PATH_SEGMENT;
case Database:
return Paths.DATABASES_PATH_SEGMENT;
case Conflict:
return Paths.CONFLICTS_PATH_SEGMENT;
case Document:
return Paths.DOCUMENTS_PATH_SEGMENT;
case DocumentCollection:
return Paths.COLLECTIONS_PATH_SEGMENT;
case Offer:
return Paths.OFFERS_PATH_SEGMENT;
case Permission:
return Paths.PERMISSIONS_PATH_SEGMENT;
case StoredProcedure:
return Paths.STORED_PROCEDURES_PATH_SEGMENT;
case Trigger:
return Paths.TRIGGERS_PATH_SEGMENT;
case UserDefinedFunction:
return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT;
case User:
return Paths.USERS_PATH_SEGMENT;
case PartitionKeyRange:
return Paths.PARTITION_KEY_RANGES_PATH_SEGMENT;
case Media:
return Paths.MEDIA_PATH_SEGMENT;
case DatabaseAccount:
return "";
default:
return null;
}
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb.
* @param resourceIdOrFullName the resource id or full name
* @param resourceType the resource type.
* @param headers the request headers.
* @return the key authorization signature.
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
ResourceType resourceType,
Map<String, String> headers) {
return this.generateKeyAuthorizationSignature(verb, resourceIdOrFullName,
BaseAuthorizationTokenProvider.getResourceSegment(resourceType), headers);
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb
* @param resourceIdOrFullName the resource id or full name
* @param resourceSegment the resource segment
* @param headers the request headers
* @return the key authorization signature
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
String resourceSegment,
Map<String, String> headers) {
if (verb == null) {
throw new IllegalArgumentException("verb");
}
if (resourceIdOrFullName == null) {
resourceIdOrFullName = "";
}
if (resourceSegment == null) {
throw new IllegalArgumentException("resourceSegment");
}
if (headers == null) {
throw new IllegalArgumentException("headers");
}
if (StringUtils.isEmpty(this.credential.getKey())) {
throw new IllegalArgumentException("key credentials cannot be empty");
}
if(!PathsHelper.isNameBased(resourceIdOrFullName)) {
resourceIdOrFullName = resourceIdOrFullName.toLowerCase(Locale.ROOT);
}
StringBuilder body = new StringBuilder();
body.append(ModelBridgeInternal.toLower(verb))
.append('\n')
.append(resourceSegment)
.append('\n')
.append(resourceIdOrFullName)
.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.X_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.X_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.HTTP_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.HTTP_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
Mac mac = getMacInstance();
byte[] digest = mac.doFinal(body.toString().getBytes(StandardCharsets.UTF_8));
String auth = Utils.encodeBase64String(digest);
return AUTH_PREFIX + auth;
}
/**
* This API is a helper method to create auth header based on client request using resourceTokens.
*
* @param resourceTokens the resource tokens.
* @param path the path.
* @param resourceId the resource id.
* @return the authorization token.
*/
public String getAuthorizationTokenUsingResourceTokens(Map<String, String> resourceTokens,
String path,
String resourceId) {
if (resourceTokens == null) {
throw new IllegalArgumentException("resourceTokens");
}
String resourceToken = null;
if (resourceTokens.containsKey(resourceId) && resourceTokens.get(resourceId) != null) {
resourceToken = resourceTokens.get(resourceId);
} else if (StringUtils.isEmpty(path) || StringUtils.isEmpty(resourceId)) {
if (resourceTokens.size() > 0) {
resourceToken = resourceTokens.values().iterator().next();
}
} else {
String[] pathParts = StringUtils.split(path, "/");
String[] resourceTypes = {"dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions",
"attachments", "media", "conflicts"};
HashSet<String> resourceTypesSet = new HashSet<String>();
Collections.addAll(resourceTypesSet, resourceTypes);
for (int i = pathParts.length - 1; i >= 0; --i) {
if (!resourceTypesSet.contains(pathParts[i]) && resourceTokens.containsKey(pathParts[i])) {
resourceToken = resourceTokens.get(pathParts[i]);
}
}
}
return resourceToken;
}
private Mac getMacInstance() {
reInitializeIfPossible();
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
}
/*
* Ensures that this.macInstance is initialized
* In-case of credential change, optimistically will try to refresh the macInstance
*
* Implementation is non-blocking, the one which acquire the lock will try to refresh
* with new credentials
*
* NOTE: Calling it CTOR ensured that default is initialized.
*/
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredential credential) {
this.credential = credential;
reInitializeIfPossible();
}
private static String getResourceSegment(ResourceType resourceType) {
switch (resourceType) {
case Attachment:
return Paths.ATTACHMENTS_PATH_SEGMENT;
case Database:
return Paths.DATABASES_PATH_SEGMENT;
case Conflict:
return Paths.CONFLICTS_PATH_SEGMENT;
case Document:
return Paths.DOCUMENTS_PATH_SEGMENT;
case DocumentCollection:
return Paths.COLLECTIONS_PATH_SEGMENT;
case Offer:
return Paths.OFFERS_PATH_SEGMENT;
case Permission:
return Paths.PERMISSIONS_PATH_SEGMENT;
case StoredProcedure:
return Paths.STORED_PROCEDURES_PATH_SEGMENT;
case Trigger:
return Paths.TRIGGERS_PATH_SEGMENT;
case UserDefinedFunction:
return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT;
case User:
return Paths.USERS_PATH_SEGMENT;
case PartitionKeyRange:
return Paths.PARTITION_KEY_RANGES_PATH_SEGMENT;
case Media:
return Paths.MEDIA_PATH_SEGMENT;
case DatabaseAccount:
return "";
default:
return null;
}
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb.
* @param resourceIdOrFullName the resource id or full name
* @param resourceType the resource type.
* @param headers the request headers.
* @return the key authorization signature.
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
ResourceType resourceType,
Map<String, String> headers) {
return this.generateKeyAuthorizationSignature(verb, resourceIdOrFullName,
BaseAuthorizationTokenProvider.getResourceSegment(resourceType), headers);
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb
* @param resourceIdOrFullName the resource id or full name
* @param resourceSegment the resource segment
* @param headers the request headers
* @return the key authorization signature
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
String resourceSegment,
Map<String, String> headers) {
if (verb == null) {
throw new IllegalArgumentException("verb");
}
if (resourceIdOrFullName == null) {
resourceIdOrFullName = "";
}
if (resourceSegment == null) {
throw new IllegalArgumentException("resourceSegment");
}
if (headers == null) {
throw new IllegalArgumentException("headers");
}
if (StringUtils.isEmpty(this.credential.getKey())) {
throw new IllegalArgumentException("key credentials cannot be empty");
}
if(!PathsHelper.isNameBased(resourceIdOrFullName)) {
resourceIdOrFullName = resourceIdOrFullName.toLowerCase(Locale.ROOT);
}
StringBuilder body = new StringBuilder();
body.append(ModelBridgeInternal.toLower(verb))
.append('\n')
.append(resourceSegment)
.append('\n')
.append(resourceIdOrFullName)
.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.X_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.X_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.HTTP_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.HTTP_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
Mac mac = getMacInstance();
byte[] digest = mac.doFinal(body.toString().getBytes(StandardCharsets.UTF_8));
String auth = Utils.encodeBase64String(digest);
return AUTH_PREFIX + auth;
}
/**
* This API is a helper method to create auth header based on client request using resourceTokens.
*
* @param resourceTokens the resource tokens.
* @param path the path.
* @param resourceId the resource id.
* @return the authorization token.
*/
public String getAuthorizationTokenUsingResourceTokens(Map<String, String> resourceTokens,
String path,
String resourceId) {
if (resourceTokens == null) {
throw new IllegalArgumentException("resourceTokens");
}
String resourceToken = null;
if (resourceTokens.containsKey(resourceId) && resourceTokens.get(resourceId) != null) {
resourceToken = resourceTokens.get(resourceId);
} else if (StringUtils.isEmpty(path) || StringUtils.isEmpty(resourceId)) {
if (resourceTokens.size() > 0) {
resourceToken = resourceTokens.values().iterator().next();
}
} else {
String[] pathParts = StringUtils.split(path, "/");
String[] resourceTypes = {"dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions",
"attachments", "media", "conflicts"};
HashSet<String> resourceTypesSet = new HashSet<String>();
Collections.addAll(resourceTypesSet, resourceTypes);
for (int i = pathParts.length - 1; i >= 0; --i) {
if (!resourceTypesSet.contains(pathParts[i]) && resourceTokens.containsKey(pathParts[i])) {
resourceToken = resourceTokens.get(pathParts[i]);
}
}
}
return resourceToken;
}
private Mac getMacInstance() {
reInitializeIfPossible();
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
}
/*
* Ensures that this.macInstance is initialized
* In-case of credential change, optimistically will try to refresh the macInstance
*
* Implementation is non-blocking, the one which acquire the lock will try to refresh
* with new credentials
*
* NOTE: Calling it CTOR ensured that default is initialized.
*/
} |
synchronized is blocking, where as reEntry.TryLock is enabling non-blocking. So only one thread will go into re-initialization. | private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.UTF_8);
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256");
try {
Mac macInstance = Mac.getInstance("HMACSHA256");
macInstance.init(signingKey);
this.masterKeyHashCode = masterKeyLatestHashCode;
this.macInstance = macInstance;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
} finally {
this.macInstanceLock.unlock();
}
}
}
} | boolean lockAcquired = this.macInstanceLock.tryLock(); | private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.UTF_8);
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256");
try {
Mac macInstance = Mac.getInstance("HMACSHA256");
macInstance.init(signingKey);
this.masterKeyHashCode = masterKeyLatestHashCode;
this.macInstance = macInstance;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
} finally {
this.macInstanceLock.unlock();
}
}
}
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredential credential) {
this.credential = credential;
reInitializeIfPossible();
}
private static String getResourceSegment(ResourceType resourceType) {
switch (resourceType) {
case Attachment:
return Paths.ATTACHMENTS_PATH_SEGMENT;
case Database:
return Paths.DATABASES_PATH_SEGMENT;
case Conflict:
return Paths.CONFLICTS_PATH_SEGMENT;
case Document:
return Paths.DOCUMENTS_PATH_SEGMENT;
case DocumentCollection:
return Paths.COLLECTIONS_PATH_SEGMENT;
case Offer:
return Paths.OFFERS_PATH_SEGMENT;
case Permission:
return Paths.PERMISSIONS_PATH_SEGMENT;
case StoredProcedure:
return Paths.STORED_PROCEDURES_PATH_SEGMENT;
case Trigger:
return Paths.TRIGGERS_PATH_SEGMENT;
case UserDefinedFunction:
return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT;
case User:
return Paths.USERS_PATH_SEGMENT;
case PartitionKeyRange:
return Paths.PARTITION_KEY_RANGES_PATH_SEGMENT;
case Media:
return Paths.MEDIA_PATH_SEGMENT;
case DatabaseAccount:
return "";
default:
return null;
}
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb.
* @param resourceIdOrFullName the resource id or full name
* @param resourceType the resource type.
* @param headers the request headers.
* @return the key authorization signature.
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
ResourceType resourceType,
Map<String, String> headers) {
return this.generateKeyAuthorizationSignature(verb, resourceIdOrFullName,
BaseAuthorizationTokenProvider.getResourceSegment(resourceType), headers);
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb
* @param resourceIdOrFullName the resource id or full name
* @param resourceSegment the resource segment
* @param headers the request headers
* @return the key authorization signature
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
String resourceSegment,
Map<String, String> headers) {
if (verb == null) {
throw new IllegalArgumentException("verb");
}
if (resourceIdOrFullName == null) {
resourceIdOrFullName = "";
}
if (resourceSegment == null) {
throw new IllegalArgumentException("resourceSegment");
}
if (headers == null) {
throw new IllegalArgumentException("headers");
}
if (StringUtils.isEmpty(this.credential.getKey())) {
throw new IllegalArgumentException("key credentials cannot be empty");
}
if(!PathsHelper.isNameBased(resourceIdOrFullName)) {
resourceIdOrFullName = resourceIdOrFullName.toLowerCase(Locale.ROOT);
}
StringBuilder body = new StringBuilder();
body.append(ModelBridgeInternal.toLower(verb))
.append('\n')
.append(resourceSegment)
.append('\n')
.append(resourceIdOrFullName)
.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.X_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.X_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.HTTP_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.HTTP_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
Mac mac = getMacInstance();
byte[] digest = mac.doFinal(body.toString().getBytes(StandardCharsets.UTF_8));
String auth = Utils.encodeBase64String(digest);
return AUTH_PREFIX + auth;
}
/**
* This API is a helper method to create auth header based on client request using resourceTokens.
*
* @param resourceTokens the resource tokens.
* @param path the path.
* @param resourceId the resource id.
* @return the authorization token.
*/
public String getAuthorizationTokenUsingResourceTokens(Map<String, String> resourceTokens,
String path,
String resourceId) {
if (resourceTokens == null) {
throw new IllegalArgumentException("resourceTokens");
}
String resourceToken = null;
if (resourceTokens.containsKey(resourceId) && resourceTokens.get(resourceId) != null) {
resourceToken = resourceTokens.get(resourceId);
} else if (StringUtils.isEmpty(path) || StringUtils.isEmpty(resourceId)) {
if (resourceTokens.size() > 0) {
resourceToken = resourceTokens.values().iterator().next();
}
} else {
String[] pathParts = StringUtils.split(path, "/");
String[] resourceTypes = {"dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions",
"attachments", "media", "conflicts"};
HashSet<String> resourceTypesSet = new HashSet<String>();
Collections.addAll(resourceTypesSet, resourceTypes);
for (int i = pathParts.length - 1; i >= 0; --i) {
if (!resourceTypesSet.contains(pathParts[i]) && resourceTokens.containsKey(pathParts[i])) {
resourceToken = resourceTokens.get(pathParts[i]);
}
}
}
return resourceToken;
}
private Mac getMacInstance() {
reInitializeIfPossible();
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
}
/*
* Ensures that this.macInstance is initialized
* In-case of credential change, optimistically will try to refresh the macInstance
*
* Implementation is non-blocking, the one which acquire the lock will try to refresh
* with new credentials
*
* NOTE: Calling it CTOR ensured that default is initialized.
*/
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredential credential) {
this.credential = credential;
reInitializeIfPossible();
}
private static String getResourceSegment(ResourceType resourceType) {
switch (resourceType) {
case Attachment:
return Paths.ATTACHMENTS_PATH_SEGMENT;
case Database:
return Paths.DATABASES_PATH_SEGMENT;
case Conflict:
return Paths.CONFLICTS_PATH_SEGMENT;
case Document:
return Paths.DOCUMENTS_PATH_SEGMENT;
case DocumentCollection:
return Paths.COLLECTIONS_PATH_SEGMENT;
case Offer:
return Paths.OFFERS_PATH_SEGMENT;
case Permission:
return Paths.PERMISSIONS_PATH_SEGMENT;
case StoredProcedure:
return Paths.STORED_PROCEDURES_PATH_SEGMENT;
case Trigger:
return Paths.TRIGGERS_PATH_SEGMENT;
case UserDefinedFunction:
return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT;
case User:
return Paths.USERS_PATH_SEGMENT;
case PartitionKeyRange:
return Paths.PARTITION_KEY_RANGES_PATH_SEGMENT;
case Media:
return Paths.MEDIA_PATH_SEGMENT;
case DatabaseAccount:
return "";
default:
return null;
}
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb.
* @param resourceIdOrFullName the resource id or full name
* @param resourceType the resource type.
* @param headers the request headers.
* @return the key authorization signature.
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
ResourceType resourceType,
Map<String, String> headers) {
return this.generateKeyAuthorizationSignature(verb, resourceIdOrFullName,
BaseAuthorizationTokenProvider.getResourceSegment(resourceType), headers);
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb
* @param resourceIdOrFullName the resource id or full name
* @param resourceSegment the resource segment
* @param headers the request headers
* @return the key authorization signature
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
String resourceSegment,
Map<String, String> headers) {
if (verb == null) {
throw new IllegalArgumentException("verb");
}
if (resourceIdOrFullName == null) {
resourceIdOrFullName = "";
}
if (resourceSegment == null) {
throw new IllegalArgumentException("resourceSegment");
}
if (headers == null) {
throw new IllegalArgumentException("headers");
}
if (StringUtils.isEmpty(this.credential.getKey())) {
throw new IllegalArgumentException("key credentials cannot be empty");
}
if(!PathsHelper.isNameBased(resourceIdOrFullName)) {
resourceIdOrFullName = resourceIdOrFullName.toLowerCase(Locale.ROOT);
}
StringBuilder body = new StringBuilder();
body.append(ModelBridgeInternal.toLower(verb))
.append('\n')
.append(resourceSegment)
.append('\n')
.append(resourceIdOrFullName)
.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.X_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.X_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.HTTP_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.HTTP_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
Mac mac = getMacInstance();
byte[] digest = mac.doFinal(body.toString().getBytes(StandardCharsets.UTF_8));
String auth = Utils.encodeBase64String(digest);
return AUTH_PREFIX + auth;
}
/**
* This API is a helper method to create auth header based on client request using resourceTokens.
*
* @param resourceTokens the resource tokens.
* @param path the path.
* @param resourceId the resource id.
* @return the authorization token.
*/
public String getAuthorizationTokenUsingResourceTokens(Map<String, String> resourceTokens,
String path,
String resourceId) {
if (resourceTokens == null) {
throw new IllegalArgumentException("resourceTokens");
}
String resourceToken = null;
if (resourceTokens.containsKey(resourceId) && resourceTokens.get(resourceId) != null) {
resourceToken = resourceTokens.get(resourceId);
} else if (StringUtils.isEmpty(path) || StringUtils.isEmpty(resourceId)) {
if (resourceTokens.size() > 0) {
resourceToken = resourceTokens.values().iterator().next();
}
} else {
String[] pathParts = StringUtils.split(path, "/");
String[] resourceTypes = {"dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions",
"attachments", "media", "conflicts"};
HashSet<String> resourceTypesSet = new HashSet<String>();
Collections.addAll(resourceTypesSet, resourceTypes);
for (int i = pathParts.length - 1; i >= 0; --i) {
if (!resourceTypesSet.contains(pathParts[i]) && resourceTokens.containsKey(pathParts[i])) {
resourceToken = resourceTokens.get(pathParts[i]);
}
}
}
return resourceToken;
}
private Mac getMacInstance() {
reInitializeIfPossible();
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
}
/*
* Ensures that this.macInstance is initialized
* In-case of credential change, optimistically will try to refresh the macInstance
*
* Implementation is non-blocking, the one which acquire the lock will try to refresh
* with new credentials
*
* NOTE: Calling it CTOR ensured that default is initialized.
*/
} |
if the key is rotated, then shouldn't the threads attempting to get a new macInstance wait and block till a new macInstance generated? Is the old macInstance value returned to the threads which don't get the lock a valid macInstance in the key-rotation scenario? | private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.UTF_8);
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256");
try {
Mac macInstance = Mac.getInstance("HMACSHA256");
macInstance.init(signingKey);
this.masterKeyHashCode = masterKeyLatestHashCode;
this.macInstance = macInstance;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
} finally {
this.macInstanceLock.unlock();
}
}
}
} | boolean lockAcquired = this.macInstanceLock.tryLock(); | private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.UTF_8);
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256");
try {
Mac macInstance = Mac.getInstance("HMACSHA256");
macInstance.init(signingKey);
this.masterKeyHashCode = masterKeyLatestHashCode;
this.macInstance = macInstance;
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
} finally {
this.macInstanceLock.unlock();
}
}
}
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredential credential) {
this.credential = credential;
reInitializeIfPossible();
}
private static String getResourceSegment(ResourceType resourceType) {
switch (resourceType) {
case Attachment:
return Paths.ATTACHMENTS_PATH_SEGMENT;
case Database:
return Paths.DATABASES_PATH_SEGMENT;
case Conflict:
return Paths.CONFLICTS_PATH_SEGMENT;
case Document:
return Paths.DOCUMENTS_PATH_SEGMENT;
case DocumentCollection:
return Paths.COLLECTIONS_PATH_SEGMENT;
case Offer:
return Paths.OFFERS_PATH_SEGMENT;
case Permission:
return Paths.PERMISSIONS_PATH_SEGMENT;
case StoredProcedure:
return Paths.STORED_PROCEDURES_PATH_SEGMENT;
case Trigger:
return Paths.TRIGGERS_PATH_SEGMENT;
case UserDefinedFunction:
return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT;
case User:
return Paths.USERS_PATH_SEGMENT;
case PartitionKeyRange:
return Paths.PARTITION_KEY_RANGES_PATH_SEGMENT;
case Media:
return Paths.MEDIA_PATH_SEGMENT;
case DatabaseAccount:
return "";
default:
return null;
}
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb.
* @param resourceIdOrFullName the resource id or full name
* @param resourceType the resource type.
* @param headers the request headers.
* @return the key authorization signature.
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
ResourceType resourceType,
Map<String, String> headers) {
return this.generateKeyAuthorizationSignature(verb, resourceIdOrFullName,
BaseAuthorizationTokenProvider.getResourceSegment(resourceType), headers);
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb
* @param resourceIdOrFullName the resource id or full name
* @param resourceSegment the resource segment
* @param headers the request headers
* @return the key authorization signature
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
String resourceSegment,
Map<String, String> headers) {
if (verb == null) {
throw new IllegalArgumentException("verb");
}
if (resourceIdOrFullName == null) {
resourceIdOrFullName = "";
}
if (resourceSegment == null) {
throw new IllegalArgumentException("resourceSegment");
}
if (headers == null) {
throw new IllegalArgumentException("headers");
}
if (StringUtils.isEmpty(this.credential.getKey())) {
throw new IllegalArgumentException("key credentials cannot be empty");
}
if(!PathsHelper.isNameBased(resourceIdOrFullName)) {
resourceIdOrFullName = resourceIdOrFullName.toLowerCase(Locale.ROOT);
}
StringBuilder body = new StringBuilder();
body.append(ModelBridgeInternal.toLower(verb))
.append('\n')
.append(resourceSegment)
.append('\n')
.append(resourceIdOrFullName)
.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.X_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.X_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.HTTP_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.HTTP_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
Mac mac = getMacInstance();
byte[] digest = mac.doFinal(body.toString().getBytes(StandardCharsets.UTF_8));
String auth = Utils.encodeBase64String(digest);
return AUTH_PREFIX + auth;
}
/**
* This API is a helper method to create auth header based on client request using resourceTokens.
*
* @param resourceTokens the resource tokens.
* @param path the path.
* @param resourceId the resource id.
* @return the authorization token.
*/
public String getAuthorizationTokenUsingResourceTokens(Map<String, String> resourceTokens,
String path,
String resourceId) {
if (resourceTokens == null) {
throw new IllegalArgumentException("resourceTokens");
}
String resourceToken = null;
if (resourceTokens.containsKey(resourceId) && resourceTokens.get(resourceId) != null) {
resourceToken = resourceTokens.get(resourceId);
} else if (StringUtils.isEmpty(path) || StringUtils.isEmpty(resourceId)) {
if (resourceTokens.size() > 0) {
resourceToken = resourceTokens.values().iterator().next();
}
} else {
String[] pathParts = StringUtils.split(path, "/");
String[] resourceTypes = {"dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions",
"attachments", "media", "conflicts"};
HashSet<String> resourceTypesSet = new HashSet<String>();
Collections.addAll(resourceTypesSet, resourceTypes);
for (int i = pathParts.length - 1; i >= 0; --i) {
if (!resourceTypesSet.contains(pathParts[i]) && resourceTokens.containsKey(pathParts[i])) {
resourceToken = resourceTokens.get(pathParts[i]);
}
}
}
return resourceToken;
}
private Mac getMacInstance() {
reInitializeIfPossible();
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
}
/*
* Ensures that this.macInstance is initialized
* In-case of credential change, optimistically will try to refresh the macInstance
*
* Implementation is non-blocking, the one which acquire the lock will try to refresh
* with new credentials
*
* NOTE: Calling it CTOR ensured that default is initialized.
*/
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredential credential) {
this.credential = credential;
reInitializeIfPossible();
}
private static String getResourceSegment(ResourceType resourceType) {
switch (resourceType) {
case Attachment:
return Paths.ATTACHMENTS_PATH_SEGMENT;
case Database:
return Paths.DATABASES_PATH_SEGMENT;
case Conflict:
return Paths.CONFLICTS_PATH_SEGMENT;
case Document:
return Paths.DOCUMENTS_PATH_SEGMENT;
case DocumentCollection:
return Paths.COLLECTIONS_PATH_SEGMENT;
case Offer:
return Paths.OFFERS_PATH_SEGMENT;
case Permission:
return Paths.PERMISSIONS_PATH_SEGMENT;
case StoredProcedure:
return Paths.STORED_PROCEDURES_PATH_SEGMENT;
case Trigger:
return Paths.TRIGGERS_PATH_SEGMENT;
case UserDefinedFunction:
return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT;
case User:
return Paths.USERS_PATH_SEGMENT;
case PartitionKeyRange:
return Paths.PARTITION_KEY_RANGES_PATH_SEGMENT;
case Media:
return Paths.MEDIA_PATH_SEGMENT;
case DatabaseAccount:
return "";
default:
return null;
}
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb.
* @param resourceIdOrFullName the resource id or full name
* @param resourceType the resource type.
* @param headers the request headers.
* @return the key authorization signature.
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
ResourceType resourceType,
Map<String, String> headers) {
return this.generateKeyAuthorizationSignature(verb, resourceIdOrFullName,
BaseAuthorizationTokenProvider.getResourceSegment(resourceType), headers);
}
/**
* This API is a helper method to create auth header based on client request using masterkey.
*
* @param verb the verb
* @param resourceIdOrFullName the resource id or full name
* @param resourceSegment the resource segment
* @param headers the request headers
* @return the key authorization signature
*/
public String generateKeyAuthorizationSignature(RequestVerb verb,
String resourceIdOrFullName,
String resourceSegment,
Map<String, String> headers) {
if (verb == null) {
throw new IllegalArgumentException("verb");
}
if (resourceIdOrFullName == null) {
resourceIdOrFullName = "";
}
if (resourceSegment == null) {
throw new IllegalArgumentException("resourceSegment");
}
if (headers == null) {
throw new IllegalArgumentException("headers");
}
if (StringUtils.isEmpty(this.credential.getKey())) {
throw new IllegalArgumentException("key credentials cannot be empty");
}
if(!PathsHelper.isNameBased(resourceIdOrFullName)) {
resourceIdOrFullName = resourceIdOrFullName.toLowerCase(Locale.ROOT);
}
StringBuilder body = new StringBuilder();
body.append(ModelBridgeInternal.toLower(verb))
.append('\n')
.append(resourceSegment)
.append('\n')
.append(resourceIdOrFullName)
.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.X_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.X_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
if (headers.containsKey(HttpConstants.HttpHeaders.HTTP_DATE)) {
body.append(headers.get(HttpConstants.HttpHeaders.HTTP_DATE).toLowerCase(Locale.ROOT));
}
body.append('\n');
Mac mac = getMacInstance();
byte[] digest = mac.doFinal(body.toString().getBytes(StandardCharsets.UTF_8));
String auth = Utils.encodeBase64String(digest);
return AUTH_PREFIX + auth;
}
/**
* This API is a helper method to create auth header based on client request using resourceTokens.
*
* @param resourceTokens the resource tokens.
* @param path the path.
* @param resourceId the resource id.
* @return the authorization token.
*/
public String getAuthorizationTokenUsingResourceTokens(Map<String, String> resourceTokens,
String path,
String resourceId) {
if (resourceTokens == null) {
throw new IllegalArgumentException("resourceTokens");
}
String resourceToken = null;
if (resourceTokens.containsKey(resourceId) && resourceTokens.get(resourceId) != null) {
resourceToken = resourceTokens.get(resourceId);
} else if (StringUtils.isEmpty(path) || StringUtils.isEmpty(resourceId)) {
if (resourceTokens.size() > 0) {
resourceToken = resourceTokens.values().iterator().next();
}
} else {
String[] pathParts = StringUtils.split(path, "/");
String[] resourceTypes = {"dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions",
"attachments", "media", "conflicts"};
HashSet<String> resourceTypesSet = new HashSet<String>();
Collections.addAll(resourceTypesSet, resourceTypes);
for (int i = pathParts.length - 1; i >= 0; --i) {
if (!resourceTypesSet.contains(pathParts[i]) && resourceTokens.containsKey(pathParts[i])) {
resourceToken = resourceTokens.get(pathParts[i]);
}
}
}
return resourceToken;
}
private Mac getMacInstance() {
reInitializeIfPossible();
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
}
/*
* Ensures that this.macInstance is initialized
* In-case of credential change, optimistically will try to refresh the macInstance
*
* Implementation is non-blocking, the one which acquire the lock will try to refresh
* with new credentials
*
* NOTE: Calling it CTOR ensured that default is initialized.
*/
} |
made the change in cc20c0521dbed11c5ffc661c23de8ed1ff65e9b4 | private List<UserGroup> loadUserGroups(String graphApiToken) throws IOException {
String responseInJson = getUserMemberships(graphApiToken, Optional.empty());
final List<UserGroup> lUserGroups = new ArrayList<>();
final ObjectMapper objectMapper = JacksonObjectMapperFactory.getInstance();
objectMapper.registerModule(new Jdk8Module());
UserGroups groupsFromJson = objectMapper.readValue(responseInJson, UserGroups.class);
if (groupsFromJson.getValue() != null) {
lUserGroups.addAll(groupsFromJson.getValue().stream().filter(this::isMatchingUserGroupKey)
.collect(Collectors.toList()));
}
while (groupsFromJson.getOdataNextLink().isPresent()) {
responseInJson = getUserMemberships(graphApiToken, groupsFromJson.getOdataNextLink());
groupsFromJson = objectMapper.readValue(responseInJson, UserGroups.class);
lUserGroups.addAll(groupsFromJson.getValue().stream().filter(this::isMatchingUserGroupKey)
.collect(Collectors.toList()));
}
return lUserGroups;
} | objectMapper.registerModule(new Jdk8Module()); | private List<UserGroup> loadUserGroups(String graphApiToken) throws IOException {
String responseInJson = getUserMemberships(graphApiToken, null);
final List<UserGroup> lUserGroups = new ArrayList<>();
final ObjectMapper objectMapper = JacksonObjectMapperFactory.getInstance();
UserGroups groupsFromJson = objectMapper.readValue(responseInJson, UserGroups.class);
if (groupsFromJson.getValue() != null) {
lUserGroups.addAll(groupsFromJson.getValue().stream().filter(this::isMatchingUserGroupKey)
.collect(Collectors.toList()));
}
while (groupsFromJson.getOdataNextLink() != null) {
responseInJson = getUserMemberships(graphApiToken, groupsFromJson.getOdataNextLink());
groupsFromJson = objectMapper.readValue(responseInJson, UserGroups.class);
lUserGroups.addAll(groupsFromJson.getValue().stream().filter(this::isMatchingUserGroupKey)
.collect(Collectors.toList()));
}
return lUserGroups;
} | class AzureADGraphClient {
private static final Logger LOGGER = LoggerFactory.getLogger(AzureADGraphClient.class);
private static final SimpleGrantedAuthority DEFAULT_AUTHORITY = new SimpleGrantedAuthority("ROLE_USER");
private static final String DEFAULT_ROLE_PREFIX = "ROLE_";
private static final String MICROSOFT_GRAPH_SCOPE = "https:
private static final String AAD_GRAPH_API_SCOPE = "https:
private static final String REQUEST_ID_SUFFIX = "aadfeed6";
private final String clientId;
private final String clientSecret;
private final ServiceEndpoints serviceEndpoints;
private final AADAuthenticationProperties aadAuthenticationProperties;
private static final String V2_VERSION_ENV_FLAG = "v2-graph";
private boolean aadMicrosoftGraphApiBool;
public AzureADGraphClient(String clientId, String clientSecret, AADAuthenticationProperties aadAuthProps,
ServiceEndpointsProperties serviceEndpointsProps) {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.aadAuthenticationProperties = aadAuthProps;
this.serviceEndpoints = serviceEndpointsProps.getServiceEndpoints(aadAuthProps.getEnvironment());
this.initAADMicrosoftGraphApiBool(aadAuthProps.getEnvironment());
}
private void initAADMicrosoftGraphApiBool(String endpointEnv) {
this.aadMicrosoftGraphApiBool = endpointEnv.contains(V2_VERSION_ENV_FLAG);
}
private String getUserMemberships(String accessToken, Optional<String> odataNextLink) throws IOException {
final URL url = new URL(serviceEndpoints.getAadMembershipRestUri());
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (this.aadMicrosoftGraphApiBool) {
conn.setRequestMethod(HttpMethod.GET.toString());
conn.setRequestProperty(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", accessToken));
conn.setRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
} else {
conn.setRequestMethod(HttpMethod.GET.toString());
conn.setRequestProperty("api-version", "1.6");
conn.setRequestProperty(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", accessToken));
conn.setRequestProperty(HttpHeaders.ACCEPT, "application/json;odata=minimalmetadata");
}
final String responseInJson = getResponseStringFromConn(conn);
final int responseCode = conn.getResponseCode();
if (responseCode == HTTPResponse.SC_OK) {
return responseInJson;
} else {
throw new IllegalStateException("Response is not "
+ HTTPResponse.SC_OK + ", response json: " + responseInJson);
}
}
private static String getResponseStringFromConn(HttpURLConnection conn) throws IOException {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
final StringBuilder stringBuffer = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuffer.append(line);
}
return stringBuffer.toString();
}
}
public List<UserGroup> getGroups(String graphApiToken) throws IOException {
return loadUserGroups(graphApiToken);
}
/**
* Checks that the JSON Node is a valid User Group to extract User Groups from
*
* @param node - json node to look for a key/value to equate against the
* {@link AADAuthenticationProperties.UserGroupProperties}
* @return true if the json node contains the correct key, and expected value to identify a user group.
*/
private boolean isMatchingUserGroupKey(final UserGroup group) {
return group.getObjectType().equals(aadAuthenticationProperties.getUserGroup().getValue());
}
public Set<GrantedAuthority> getGrantedAuthorities(String graphApiToken) throws IOException {
final List<UserGroup> groups = getGroups(graphApiToken);
return convertGroupsToGrantedAuthorities(groups);
}
/**
* Converts UserGroup list to Set of GrantedAuthorities
*
* @param groups user groups
* @return granted authorities
*/
public Set<GrantedAuthority> convertGroupsToGrantedAuthorities(final List<UserGroup> groups) {
final Set<GrantedAuthority> mappedAuthorities = groups.stream().filter(this::isValidUserGroupToGrantAuthority)
.map(userGroup -> new SimpleGrantedAuthority(DEFAULT_ROLE_PREFIX + userGroup.getDisplayName()))
.collect(Collectors.toCollection(LinkedHashSet::new));
if (mappedAuthorities.isEmpty()) {
mappedAuthorities.add(DEFAULT_AUTHORITY);
}
return mappedAuthorities;
}
/**
* Determines if this is a valid {@link UserGroup} to build to a GrantedAuthority.
* <p>
* If the {@link AADAuthenticationProperties.UserGroupProperties
* contains the {@link UserGroup
* true.
*
* @param group - User Group to check if valid to grant an authority to.
* @return true if allowed-groups contains the UserGroup display name
*/
private boolean isValidUserGroupToGrantAuthority(final UserGroup group) {
return aadAuthenticationProperties.getUserGroup().getAllowedGroups().contains(group.getDisplayName());
}
public IAuthenticationResult acquireTokenForGraphApi(String idToken, String tenantId)
throws ServiceUnavailableException {
final IClientCredential clientCredential = ClientCredentialFactory.createFromSecret(clientSecret);
final UserAssertion assertion = new UserAssertion(idToken);
IAuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
final ConfidentialClientApplication application = ConfidentialClientApplication
.builder(clientId, clientCredential)
.authority(serviceEndpoints.getAadSigninUri() + tenantId + "/")
.correlationId(getCorrelationId())
.build();
final Set<String> scopes = new HashSet<>();
scopes.add(aadMicrosoftGraphApiBool ? MICROSOFT_GRAPH_SCOPE : AAD_GRAPH_API_SCOPE);
final OnBehalfOfParameters onBehalfOfParameters = OnBehalfOfParameters
.builder(scopes, assertion)
.build();
final CompletableFuture<IAuthenticationResult> future = application.acquireToken(onBehalfOfParameters);
result = future.get();
} catch (ExecutionException | InterruptedException | MalformedURLException e) {
final Throwable cause = e.getCause();
if (cause instanceof MsalServiceException) {
final MsalServiceException exception = (MsalServiceException) cause;
if (exception.claims() != null && !exception.claims().isEmpty()) {
throw exception;
}
}
LOGGER.error("acquire on behalf of token for graph api error", e);
} finally {
if (service != null) {
service.shutdown();
}
}
if (result == null) {
throw new ServiceUnavailableException("unable to acquire on-behalf-of token for client " + clientId);
}
return result;
}
private static String getCorrelationId() {
final String uuid = UUID.randomUUID().toString();
return uuid.substring(0, uuid.length() - REQUEST_ID_SUFFIX.length()) + REQUEST_ID_SUFFIX;
}
} | class AzureADGraphClient {
private static final Logger LOGGER = LoggerFactory.getLogger(AzureADGraphClient.class);
private static final SimpleGrantedAuthority DEFAULT_AUTHORITY = new SimpleGrantedAuthority("ROLE_USER");
private static final String DEFAULT_ROLE_PREFIX = "ROLE_";
private static final String MICROSOFT_GRAPH_SCOPE = "https:
private static final String AAD_GRAPH_API_SCOPE = "https:
private static final String REQUEST_ID_SUFFIX = "aadfeed6";
private final String clientId;
private final String clientSecret;
private final ServiceEndpoints serviceEndpoints;
private final AADAuthenticationProperties aadAuthenticationProperties;
private static final String V2_VERSION_ENV_FLAG = "v2-graph";
private boolean aadMicrosoftGraphApiBool;
public AzureADGraphClient(String clientId, String clientSecret, AADAuthenticationProperties aadAuthProps,
ServiceEndpointsProperties serviceEndpointsProps) {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.aadAuthenticationProperties = aadAuthProps;
this.serviceEndpoints = serviceEndpointsProps.getServiceEndpoints(aadAuthProps.getEnvironment());
this.initAADMicrosoftGraphApiBool(aadAuthProps.getEnvironment());
}
private void initAADMicrosoftGraphApiBool(String endpointEnv) {
this.aadMicrosoftGraphApiBool = endpointEnv.contains(V2_VERSION_ENV_FLAG);
}
private String getUserMemberships(String accessToken, String odataNextLink) throws IOException {
final URL url = buildUrl(odataNextLink);
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (this.aadMicrosoftGraphApiBool) {
conn.setRequestMethod(HttpMethod.GET.toString());
conn.setRequestProperty(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", accessToken));
conn.setRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
} else {
conn.setRequestMethod(HttpMethod.GET.toString());
conn.setRequestProperty("api-version", "1.6");
conn.setRequestProperty(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", accessToken));
conn.setRequestProperty(HttpHeaders.ACCEPT, "application/json;odata=minimalmetadata");
}
final String responseInJson = getResponseStringFromConn(conn);
final int responseCode = conn.getResponseCode();
if (responseCode == HTTPResponse.SC_OK) {
return responseInJson;
} else {
throw new IllegalStateException("Response is not "
+ HTTPResponse.SC_OK + ", response json: " + responseInJson);
}
}
private String getSkipTokenFromLink(String odataNextLink) {
String[] parts = odataNextLink.split("/memberOf\\?");
return parts[1];
}
private URL buildUrl(String odataNextLink) throws MalformedURLException {
URL url;
if (odataNextLink != null) {
if (this.aadMicrosoftGraphApiBool) {
url = new URL(odataNextLink);
} else {
String skipToken = getSkipTokenFromLink(odataNextLink);
url = new URL(serviceEndpoints.getAadMembershipRestUri() + "&" + skipToken);
}
} else {
url = new URL(serviceEndpoints.getAadMembershipRestUri());
}
return url;
}
private static String getResponseStringFromConn(HttpURLConnection conn) throws IOException {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
final StringBuilder stringBuffer = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuffer.append(line);
}
return stringBuffer.toString();
}
}
public List<UserGroup> getGroups(String graphApiToken) throws IOException {
return loadUserGroups(graphApiToken);
}
/**
* Checks that the UserGroup has a Group object type.
*
* @param node - json node to look for a key/value to equate against the
* {@link AADAuthenticationProperties.UserGroupProperties}
* @return true if the json node contains the correct key, and expected value to identify a user group.
*/
private boolean isMatchingUserGroupKey(final UserGroup group) {
return group.getObjectType().equals(aadAuthenticationProperties.getUserGroup().getValue());
}
public Set<GrantedAuthority> getGrantedAuthorities(String graphApiToken) throws IOException {
final List<UserGroup> groups = getGroups(graphApiToken);
return convertGroupsToGrantedAuthorities(groups);
}
/**
* Converts UserGroup list to Set of GrantedAuthorities
*
* @param groups user groups
* @return granted authorities
*/
public Set<GrantedAuthority> convertGroupsToGrantedAuthorities(final List<UserGroup> groups) {
final Set<GrantedAuthority> mappedAuthorities = groups.stream().filter(this::isValidUserGroupToGrantAuthority)
.map(userGroup -> new SimpleGrantedAuthority(DEFAULT_ROLE_PREFIX + userGroup.getDisplayName()))
.collect(Collectors.toCollection(LinkedHashSet::new));
if (mappedAuthorities.isEmpty()) {
mappedAuthorities.add(DEFAULT_AUTHORITY);
}
return mappedAuthorities;
}
/**
* Determines if this is a valid {@link UserGroup} to build to a GrantedAuthority.
* <p>
* If the {@link AADAuthenticationProperties.UserGroupProperties
* contains the {@link UserGroup
* true.
*
* @param group - User Group to check if valid to grant an authority to.
* @return true if allowed-groups contains the UserGroup display name
*/
private boolean isValidUserGroupToGrantAuthority(final UserGroup group) {
return aadAuthenticationProperties.getUserGroup().getAllowedGroups().contains(group.getDisplayName());
}
public IAuthenticationResult acquireTokenForGraphApi(String idToken, String tenantId)
throws ServiceUnavailableException {
final IClientCredential clientCredential = ClientCredentialFactory.createFromSecret(clientSecret);
final UserAssertion assertion = new UserAssertion(idToken);
IAuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
final ConfidentialClientApplication application = ConfidentialClientApplication
.builder(clientId, clientCredential)
.authority(serviceEndpoints.getAadSigninUri() + tenantId + "/")
.correlationId(getCorrelationId())
.build();
final Set<String> scopes = new HashSet<>();
scopes.add(aadMicrosoftGraphApiBool ? MICROSOFT_GRAPH_SCOPE : AAD_GRAPH_API_SCOPE);
final OnBehalfOfParameters onBehalfOfParameters = OnBehalfOfParameters
.builder(scopes, assertion)
.build();
final CompletableFuture<IAuthenticationResult> future = application.acquireToken(onBehalfOfParameters);
result = future.get();
} catch (ExecutionException | InterruptedException | MalformedURLException e) {
final Throwable cause = e.getCause();
if (cause instanceof MsalServiceException) {
final MsalServiceException exception = (MsalServiceException) cause;
if (exception.claims() != null && !exception.claims().isEmpty()) {
throw exception;
}
}
LOGGER.error("acquire on behalf of token for graph api error", e);
} finally {
if (service != null) {
service.shutdown();
}
}
if (result == null) {
throw new ServiceUnavailableException("unable to acquire on-behalf-of token for client " + clientId);
}
return result;
}
private static String getCorrelationId() {
final String uuid = UUID.randomUUID().toString();
return uuid.substring(0, uuid.length() - REQUEST_ID_SUFFIX.length()) + REQUEST_ID_SUFFIX;
}
} |
If it is not used, just delete the code. | private ResourceManager(HttpPipeline httpPipeline, AzureProfile profile, SdkContext sdkContext) {
super(null, profile, sdkContext);
super.withResourceManager(this);
this.resourceManagementClient = new ResourceManagementClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.subscriptionId(profile.subscriptionId())
.buildClient();
this.featureClient = new FeatureClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.subscriptionId(profile.subscriptionId())
.buildClient();
this.subscriptionClient = new SubscriptionClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.buildClient();
this.policyClient = new PolicyClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.subscriptionId(profile.subscriptionId())
.buildClient();
} | .endpoint(profile.environment().getResourceManagerEndpoint()) | private ResourceManager(HttpPipeline httpPipeline, AzureProfile profile, SdkContext sdkContext) {
super(null, profile, sdkContext);
super.withResourceManager(this);
this.resourceManagementClient = new ResourceManagementClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.subscriptionId(profile.subscriptionId())
.buildClient();
this.featureClient = new FeatureClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.subscriptionId(profile.subscriptionId())
.buildClient();
this.subscriptionClient = new SubscriptionClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.buildClient();
this.policyClient = new PolicyClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.subscriptionId(profile.subscriptionId())
.buildClient();
} | class AuthenticatedImpl implements Authenticated {
private final HttpPipeline httpPipeline;
private AzureProfile profile;
private SdkContext sdkContext;
private final SubscriptionClient subscriptionClient;
private Subscriptions subscriptions;
private Tenants tenants;
AuthenticatedImpl(HttpPipeline httpPipeline, AzureProfile profile) {
this.httpPipeline = httpPipeline;
this.profile = profile;
this.sdkContext = new SdkContext();
this.subscriptionClient = new SubscriptionClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.buildClient();
}
public Subscriptions subscriptions() {
if (subscriptions == null) {
subscriptions = new SubscriptionsImpl(subscriptionClient.getSubscriptions());
}
return subscriptions;
}
public Tenants tenants() {
if (tenants == null) {
tenants = new TenantsImpl(subscriptionClient.getTenants());
}
return tenants;
}
@Override
public AuthenticatedImpl withSdkContext(SdkContext sdkContext) {
this.sdkContext = sdkContext;
return this;
}
@Override
public ResourceManager withSubscription(String subscriptionId) {
Objects.requireNonNull(subscriptionId);
profile = new AzureProfile(profile.tenantId(), subscriptionId, profile.environment());
return new ResourceManager(httpPipeline, profile, sdkContext);
}
@Override
public ResourceManager withDefaultSubscription() {
if (profile.subscriptionId() == null) {
String subscriptionId = Utils.defaultSubscription(this.subscriptions().list());
profile = new AzureProfile(profile.tenantId(), subscriptionId, profile.environment());
}
return new ResourceManager(httpPipeline, profile, sdkContext);
}
} | class AuthenticatedImpl implements Authenticated {
private final HttpPipeline httpPipeline;
private AzureProfile profile;
private SdkContext sdkContext;
private final SubscriptionClient subscriptionClient;
private Subscriptions subscriptions;
private Tenants tenants;
AuthenticatedImpl(HttpPipeline httpPipeline, AzureProfile profile) {
this.httpPipeline = httpPipeline;
this.profile = profile;
this.sdkContext = new SdkContext();
this.subscriptionClient = new SubscriptionClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.buildClient();
}
public Subscriptions subscriptions() {
if (subscriptions == null) {
subscriptions = new SubscriptionsImpl(subscriptionClient.getSubscriptions());
}
return subscriptions;
}
public Tenants tenants() {
if (tenants == null) {
tenants = new TenantsImpl(subscriptionClient.getTenants());
}
return tenants;
}
@Override
public AuthenticatedImpl withSdkContext(SdkContext sdkContext) {
this.sdkContext = sdkContext;
return this;
}
@Override
public ResourceManager withSubscription(String subscriptionId) {
Objects.requireNonNull(subscriptionId);
profile = new AzureProfile(profile.tenantId(), subscriptionId, profile.environment());
return new ResourceManager(httpPipeline, profile, sdkContext);
}
@Override
public ResourceManager withDefaultSubscription() {
if (profile.subscriptionId() == null) {
String subscriptionId = Utils.defaultSubscription(this.subscriptions().list());
profile = new AzureProfile(profile.tenantId(), subscriptionId, profile.environment());
}
return new ResourceManager(httpPipeline, profile, sdkContext);
}
} |
it is used in this code. | private ResourceManager(HttpPipeline httpPipeline, AzureProfile profile, SdkContext sdkContext) {
super(null, profile, sdkContext);
super.withResourceManager(this);
this.resourceManagementClient = new ResourceManagementClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.subscriptionId(profile.subscriptionId())
.buildClient();
this.featureClient = new FeatureClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.subscriptionId(profile.subscriptionId())
.buildClient();
this.subscriptionClient = new SubscriptionClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.buildClient();
this.policyClient = new PolicyClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.subscriptionId(profile.subscriptionId())
.buildClient();
} | .endpoint(profile.environment().getResourceManagerEndpoint()) | private ResourceManager(HttpPipeline httpPipeline, AzureProfile profile, SdkContext sdkContext) {
super(null, profile, sdkContext);
super.withResourceManager(this);
this.resourceManagementClient = new ResourceManagementClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.subscriptionId(profile.subscriptionId())
.buildClient();
this.featureClient = new FeatureClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.subscriptionId(profile.subscriptionId())
.buildClient();
this.subscriptionClient = new SubscriptionClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.buildClient();
this.policyClient = new PolicyClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.subscriptionId(profile.subscriptionId())
.buildClient();
} | class AuthenticatedImpl implements Authenticated {
private final HttpPipeline httpPipeline;
private AzureProfile profile;
private SdkContext sdkContext;
private final SubscriptionClient subscriptionClient;
private Subscriptions subscriptions;
private Tenants tenants;
AuthenticatedImpl(HttpPipeline httpPipeline, AzureProfile profile) {
this.httpPipeline = httpPipeline;
this.profile = profile;
this.sdkContext = new SdkContext();
this.subscriptionClient = new SubscriptionClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.buildClient();
}
public Subscriptions subscriptions() {
if (subscriptions == null) {
subscriptions = new SubscriptionsImpl(subscriptionClient.getSubscriptions());
}
return subscriptions;
}
public Tenants tenants() {
if (tenants == null) {
tenants = new TenantsImpl(subscriptionClient.getTenants());
}
return tenants;
}
@Override
public AuthenticatedImpl withSdkContext(SdkContext sdkContext) {
this.sdkContext = sdkContext;
return this;
}
@Override
public ResourceManager withSubscription(String subscriptionId) {
Objects.requireNonNull(subscriptionId);
profile = new AzureProfile(profile.tenantId(), subscriptionId, profile.environment());
return new ResourceManager(httpPipeline, profile, sdkContext);
}
@Override
public ResourceManager withDefaultSubscription() {
if (profile.subscriptionId() == null) {
String subscriptionId = Utils.defaultSubscription(this.subscriptions().list());
profile = new AzureProfile(profile.tenantId(), subscriptionId, profile.environment());
}
return new ResourceManager(httpPipeline, profile, sdkContext);
}
} | class AuthenticatedImpl implements Authenticated {
private final HttpPipeline httpPipeline;
private AzureProfile profile;
private SdkContext sdkContext;
private final SubscriptionClient subscriptionClient;
private Subscriptions subscriptions;
private Tenants tenants;
AuthenticatedImpl(HttpPipeline httpPipeline, AzureProfile profile) {
this.httpPipeline = httpPipeline;
this.profile = profile;
this.sdkContext = new SdkContext();
this.subscriptionClient = new SubscriptionClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.buildClient();
}
public Subscriptions subscriptions() {
if (subscriptions == null) {
subscriptions = new SubscriptionsImpl(subscriptionClient.getSubscriptions());
}
return subscriptions;
}
public Tenants tenants() {
if (tenants == null) {
tenants = new TenantsImpl(subscriptionClient.getTenants());
}
return tenants;
}
@Override
public AuthenticatedImpl withSdkContext(SdkContext sdkContext) {
this.sdkContext = sdkContext;
return this;
}
@Override
public ResourceManager withSubscription(String subscriptionId) {
Objects.requireNonNull(subscriptionId);
profile = new AzureProfile(profile.tenantId(), subscriptionId, profile.environment());
return new ResourceManager(httpPipeline, profile, sdkContext);
}
@Override
public ResourceManager withDefaultSubscription() {
if (profile.subscriptionId() == null) {
String subscriptionId = Utils.defaultSubscription(this.subscriptions().list());
profile = new AzureProfile(profile.tenantId(), subscriptionId, profile.environment());
}
return new ResourceManager(httpPipeline, profile, sdkContext);
}
} |
I mean the codes that you've commented out. | private ResourceManager(HttpPipeline httpPipeline, AzureProfile profile, SdkContext sdkContext) {
super(null, profile, sdkContext);
super.withResourceManager(this);
this.resourceManagementClient = new ResourceManagementClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.subscriptionId(profile.subscriptionId())
.buildClient();
this.featureClient = new FeatureClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.subscriptionId(profile.subscriptionId())
.buildClient();
this.subscriptionClient = new SubscriptionClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.buildClient();
this.policyClient = new PolicyClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.subscriptionId(profile.subscriptionId())
.buildClient();
} | .endpoint(profile.environment().getResourceManagerEndpoint()) | private ResourceManager(HttpPipeline httpPipeline, AzureProfile profile, SdkContext sdkContext) {
super(null, profile, sdkContext);
super.withResourceManager(this);
this.resourceManagementClient = new ResourceManagementClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.subscriptionId(profile.subscriptionId())
.buildClient();
this.featureClient = new FeatureClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.subscriptionId(profile.subscriptionId())
.buildClient();
this.subscriptionClient = new SubscriptionClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.buildClient();
this.policyClient = new PolicyClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.subscriptionId(profile.subscriptionId())
.buildClient();
} | class AuthenticatedImpl implements Authenticated {
private final HttpPipeline httpPipeline;
private AzureProfile profile;
private SdkContext sdkContext;
private final SubscriptionClient subscriptionClient;
private Subscriptions subscriptions;
private Tenants tenants;
AuthenticatedImpl(HttpPipeline httpPipeline, AzureProfile profile) {
this.httpPipeline = httpPipeline;
this.profile = profile;
this.sdkContext = new SdkContext();
this.subscriptionClient = new SubscriptionClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.buildClient();
}
public Subscriptions subscriptions() {
if (subscriptions == null) {
subscriptions = new SubscriptionsImpl(subscriptionClient.getSubscriptions());
}
return subscriptions;
}
public Tenants tenants() {
if (tenants == null) {
tenants = new TenantsImpl(subscriptionClient.getTenants());
}
return tenants;
}
@Override
public AuthenticatedImpl withSdkContext(SdkContext sdkContext) {
this.sdkContext = sdkContext;
return this;
}
@Override
public ResourceManager withSubscription(String subscriptionId) {
Objects.requireNonNull(subscriptionId);
profile = new AzureProfile(profile.tenantId(), subscriptionId, profile.environment());
return new ResourceManager(httpPipeline, profile, sdkContext);
}
@Override
public ResourceManager withDefaultSubscription() {
if (profile.subscriptionId() == null) {
String subscriptionId = Utils.defaultSubscription(this.subscriptions().list());
profile = new AzureProfile(profile.tenantId(), subscriptionId, profile.environment());
}
return new ResourceManager(httpPipeline, profile, sdkContext);
}
} | class AuthenticatedImpl implements Authenticated {
private final HttpPipeline httpPipeline;
private AzureProfile profile;
private SdkContext sdkContext;
private final SubscriptionClient subscriptionClient;
private Subscriptions subscriptions;
private Tenants tenants;
AuthenticatedImpl(HttpPipeline httpPipeline, AzureProfile profile) {
this.httpPipeline = httpPipeline;
this.profile = profile;
this.sdkContext = new SdkContext();
this.subscriptionClient = new SubscriptionClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())
.buildClient();
}
public Subscriptions subscriptions() {
if (subscriptions == null) {
subscriptions = new SubscriptionsImpl(subscriptionClient.getSubscriptions());
}
return subscriptions;
}
public Tenants tenants() {
if (tenants == null) {
tenants = new TenantsImpl(subscriptionClient.getTenants());
}
return tenants;
}
@Override
public AuthenticatedImpl withSdkContext(SdkContext sdkContext) {
this.sdkContext = sdkContext;
return this;
}
@Override
public ResourceManager withSubscription(String subscriptionId) {
Objects.requireNonNull(subscriptionId);
profile = new AzureProfile(profile.tenantId(), subscriptionId, profile.environment());
return new ResourceManager(httpPipeline, profile, sdkContext);
}
@Override
public ResourceManager withDefaultSubscription() {
if (profile.subscriptionId() == null) {
String subscriptionId = Utils.defaultSubscription(this.subscriptions().list());
profile = new AzureProfile(profile.tenantId(), subscriptionId, profile.environment());
}
return new ResourceManager(httpPipeline, profile, sdkContext);
}
} |
Consider putting this in a constant | public void deleteModelValidModelIdWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel createdModel = syncPoller.getFinalResult();
StepVerifier.create(client.deleteModelWithResponse(createdModel.getModelId()))
.assertNext(response -> assertEquals(response.getStatusCode(), HttpResponseStatus.NO_CONTENT.code()))
.verifyComplete();
StepVerifier.create(client.getCustomModelWithResponse(createdModel.getModelId()))
.verifyErrorSatisfies(throwable -> {
assertEquals(HttpResponseException.class, throwable.getClass());
final FormRecognizerErrorInformation errorInformation = (FormRecognizerErrorInformation)
((HttpResponseException) throwable).getValue();
assertEquals("1022", errorInformation.getErrorCode());
});
});
} | assertEquals("1022", errorInformation.getErrorCode()); | public void deleteModelValidModelIdWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel createdModel = syncPoller.getFinalResult();
StepVerifier.create(client.deleteModelWithResponse(createdModel.getModelId()))
.assertNext(response -> assertEquals(response.getStatusCode(), HttpResponseStatus.NO_CONTENT.code()))
.verifyComplete();
StepVerifier.create(client.getCustomModelWithResponse(createdModel.getModelId()))
.verifyErrorSatisfies(throwable -> {
assertEquals(HttpResponseException.class, throwable.getClass());
final FormRecognizerErrorInformation errorInformation = (FormRecognizerErrorInformation)
((HttpResponseException) throwable).getValue();
assertEquals(EXPECTED_MODEL_ID_NOT_FOUND_ERROR_CODE, errorInformation.getErrorCode());
});
});
} | class FormTrainingAsyncClientTest extends FormTrainingClientTestBase {
static final String EXPECTED_COPY_REQUEST_INVALID_TARGET_RESOURCE_REGION = "Status code 400, \"{\"error\":{\"code\":\"1002\",\"message\":\"Copy request is invalid. Field 'TargetResourceRegion' must be a valid Azure region name.\"}}\"";
private FormTrainingAsyncClient client;
@BeforeAll
static void beforeAll() {
StepVerifier.setDefaultTimeout(Duration.ofSeconds(30));
}
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
private FormTrainingAsyncClient getFormTrainingAsyncClient(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
return getFormTrainingClientBuilder(httpClient, serviceVersion).buildAsyncClient();
}
/**
* Verifies the form recognizer async client is valid.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
void getFormRecognizerClientAndValidate(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
FormRecognizerAsyncClient formRecognizerClient = getFormTrainingAsyncClient(httpClient, serviceVersion)
.getFormRecognizerAsyncClient();
blankPdfDataRunner(data -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
formRecognizerClient.beginRecognizeReceipts(toFluxByteBuffer(data), BLANK_FORM_FILE_LENGTH,
new RecognizeReceiptsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateBlankPdfResultData(syncPoller.getFinalResult());
});
}
/**
* Verifies that an exception is thrown for null model Id parameter.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void getCustomModelNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.getCustomModel(null)).verifyError();
}
/**
* Verifies that an exception is thrown for invalid model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void getCustomModelInvalidModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
getCustomModelInvalidModelIdRunner(invalidModelId -> StepVerifier.create(client.getCustomModel(invalidModelId))
.expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException
&& throwable.getMessage().equals(INVALID_MODEL_ID_ERROR)).verify());
}
/**
* Verifies custom model info returned with response for a valid model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void getCustomModelWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel trainedModel = syncPoller.getFinalResult();
StepVerifier.create(client.getCustomModelWithResponse(trainedModel.getModelId())).assertNext(customFormModelResponse -> {
assertEquals(customFormModelResponse.getStatusCode(), HttpResponseStatus.OK.code());
validateCustomModelData(syncPoller.getFinalResult(), false);
});
});
}
/**
* Verifies unlabeled custom model info returned with response for a valid model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void getCustomModelUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = client.beginTraining(
trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel trainedUnlabeledModel = syncPoller.getFinalResult();
StepVerifier.create(client.getCustomModel(trainedUnlabeledModel.getModelId()))
.assertNext(customFormModel -> validateCustomModelData(syncPoller.getFinalResult(),
false));
});
}
/**
* Verifies labeled custom model info returned with response for a valid model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void getCustomModelLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel trainedLabeledModel = syncPoller.getFinalResult();
StepVerifier.create(client.getCustomModel(trainedLabeledModel.getModelId()))
.assertNext(customFormModel -> validateCustomModelData(syncPoller.getFinalResult(),
true));
});
}
/**
* Verifies account properties returned for a subscription account.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void validGetAccountProperties(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.getAccountProperties())
.assertNext(accountProperties -> validateAccountProperties(accountProperties))
.verifyComplete();
}
/**
* Verifies account properties returned with an Http Response for a subscription account.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void validGetAccountPropertiesWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.getAccountProperties())
.assertNext(accountProperties -> validateAccountProperties(accountProperties))
.verifyComplete();
}
/**
* Verifies that an exception is thrown for invalid status model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void deleteModelInvalidModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.deleteModel(INVALID_MODEL_ID))
.expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException
&& throwable.getMessage().equals(INVALID_MODEL_ID_ERROR))
.verify();
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void deleteModelValidModelIdWithResponseWithoutTrainingLabels(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingUnlabeledRunner((trainingFilesUrl, notUseTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl,
notUseTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel createdModel = syncPoller.getFinalResult();
StepVerifier.create(client.deleteModelWithResponse(createdModel.getModelId()))
.assertNext(response -> assertEquals(response.getStatusCode(), HttpResponseStatus.NO_CONTENT.code()))
.verifyComplete();
StepVerifier.create(client.getCustomModelWithResponse(createdModel.getModelId()))
.verifyErrorSatisfies(throwable -> {
assertEquals(HttpResponseException.class, throwable.getClass());
final FormRecognizerErrorInformation errorInformation = (FormRecognizerErrorInformation)
((HttpResponseException) throwable).getValue();
assertEquals("1022", errorInformation.getErrorCode());
});
});
}
/**
* Test for listing all models information.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void listCustomModels(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.listCustomModels())
.thenConsumeWhile(customFormModelInfo ->
customFormModelInfo.getModelId() != null && customFormModelInfo.getTrainingStartedOn() != null
&& customFormModelInfo.getTrainingCompletedOn() != null && customFormModelInfo.getStatus() != null)
.verifyComplete();
}
/**
* Verifies that an exception is thrown for null source url input.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginTrainingNullInput(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
NullPointerException thrown = assertThrows(
NullPointerException.class,
() -> client.beginTraining(null, false,
new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
assertTrue(thrown.getMessage().equals(NULL_SOURCE_URL_ERROR));
}
/**
* Verifies the result of the copy operation for valid parameters.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginCopy(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller =
client.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel actualModel = syncPoller.getFinalResult();
beginCopyRunner((resourceId, resourceRegion) -> {
Mono<CopyAuthorization> targetMono = client.getCopyAuthorization(resourceId, resourceRegion);
CopyAuthorization target = targetMono.block();
if (actualModel == null) {
assertTrue(false);
return;
}
PollerFlux<FormRecognizerOperationResult, CustomFormModelInfo> copyPoller =
client.beginCopyModel(actualModel.getModelId(), target);
CustomFormModelInfo copyModel = copyPoller.getSyncPoller().getFinalResult();
assertNotNull(target.getModelId(), copyModel.getModelId());
assertNotNull(actualModel.getTrainingStartedOn());
assertNotNull(actualModel.getTrainingCompletedOn());
assertEquals(CustomFormModelStatus.READY, copyModel.getStatus());
});
});
}
/**
* Verifies the Invalid region ErrorResponseException is thrown for invalid region input to copy operation.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginCopyInvalidRegion(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller =
client.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions()
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel actualModel = syncPoller.getFinalResult();
beginCopyInvalidRegionRunner((resourceId, resourceRegion) -> {
Mono<CopyAuthorization> targetMono = client.getCopyAuthorization(resourceId, resourceRegion);
CopyAuthorization target = targetMono.block();
if (actualModel == null) {
assertTrue(false);
return;
}
PollerFlux<FormRecognizerOperationResult, CustomFormModelInfo> copyPoller = client.beginCopyModel(
actualModel.getModelId(), target);
Exception thrown = assertThrows(HttpResponseException.class,
() -> copyPoller.getSyncPoller().getFinalResult());
assertEquals(EXPECTED_COPY_REQUEST_INVALID_TARGET_RESOURCE_REGION, thrown.getMessage());
});
});
}
/**
* Verifies {@link FormRecognizerException} is thrown for invalid region input to copy operation.
*/
@SuppressWarnings("unchecked")
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginCopyIncorrectRegion(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller =
client.beginTraining(trainingFilesUrl, useTrainingLabels,
new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel actualModel = syncPoller.getFinalResult();
beginCopyIncorrectRegionRunner((resourceId, resourceRegion) -> {
Mono<CopyAuthorization> targetMono = client.getCopyAuthorization(resourceId, resourceRegion);
CopyAuthorization target = targetMono.block();
if (actualModel == null) {
assertTrue(false);
return;
}
FormRecognizerException formRecognizerException = assertThrows(FormRecognizerException.class,
() -> client.beginCopyModel(actualModel.getModelId(), target)
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation = formRecognizerException.getErrorInformation().get(0);
});
});
}
/**
* Verifies the result of the copy authorization for valid parameters.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void copyAuthorization(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginCopyRunner((resourceId, resourceRegion) ->
StepVerifier.create(client.getCopyAuthorization(resourceId, resourceRegion))
.assertNext(copyAuthorization ->
validateCopyAuthorizationResult(resourceId, resourceRegion, copyAuthorization))
.verifyComplete()
);
}
/**
* Verifies the training operation throws FormRecognizerException when an invalid status model is returned.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginTrainingInvalidModelStatus(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingInvalidModelStatusRunner((invalidTrainingFilesUrl, useTrainingLabels) -> {
FormRecognizerException formRecognizerException = assertThrows(FormRecognizerException.class,
() -> client.beginTraining(invalidTrainingFilesUrl, useTrainingLabels).getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation = formRecognizerException.getErrorInformation().get(0);
assertEquals(EXPECTED_INVALID_MODEL_STATUS_ERROR_CODE, errorInformation.getErrorCode());
assertTrue(formRecognizerException.getMessage().contains(EXPECTED_INVALID_MODEL_STATUS_MESSAGE));
assertEquals(EXPECTED_INVALID_MODEL_ERROR, errorInformation.getMessage());
assertTrue(formRecognizerException.getMessage().contains(EXPECTED_INVALID_STATUS_EXCEPTION_MESSAGE));
});
}
/**
* Verifies the result of the training operation for a valid labeled model Id and JPG training set Url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginTrainingWithTrainingLabelsForJPGTrainingSet(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
client.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
validateCustomModelData(trainingPoller.getFinalResult(), true);
});
}
/**
* Verifies the result of the training operation for a valid unlabeled model Id and JPG training set Url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginTrainingWithoutTrainingLabelsForJPGTrainingSet(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = client.beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
validateCustomModelData(trainingPoller.getFinalResult(), false);
});
}
/**
* Verifies the result of the training operation for a valid labeled model Id and multi-page PDF training set Url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginTrainingWithTrainingLabelsForMultiPagePDFTrainingSet(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingMultipageRunner(trainingFilesUrl -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = client.beginTraining(trainingFilesUrl,
true, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
validateCustomModelData(trainingPoller.getFinalResult(), true);
});
}
/**
* Verifies the result of the training operation for a valid unlabeled model Id and multi-page PDF training set Url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginTrainingWithoutTrainingLabelsForMultiPagePDFTrainingSet(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingMultipageRunner(trainingFilesUrl -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = client.beginTraining(trainingFilesUrl,
false, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
validateCustomModelData(trainingPoller.getFinalResult(), false);
});
}
/**
* Verifies the result of the training operation for a valid labeled model Id and include subfolder training set
* Url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginTrainingWithoutTrainingLabelsIncludeSubfolderWithPrefixName(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = client.beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions()
.setPollInterval(durationTestMode)
.setTrainingFileFilter(new TrainingFileFilter().setSubfoldersIncluded(true)
.setPrefix(PREFIX_SUBFOLDER))).getSyncPoller();
trainingPoller.waitForCompletion();
validateCustomModelData(trainingPoller.getFinalResult(), false);
});
}
/**
* Verifies the result of the training operation for a valid unlabeled model ID and exclude subfolder training set
* URL with existing prefix name.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginTrainingWithoutTrainingLabelsExcludeSubfolderWithPrefixName(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = client.beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions()
.setTrainingFileFilter(new TrainingFileFilter().setPrefix(PREFIX_SUBFOLDER))
.setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
validateCustomModelData(trainingPoller.getFinalResult(), false);
});
}
/**
* Verifies the result of the training operation for a valid unlabeled model Id and include subfolder training set
* Url with non-existing prefix name.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginTrainingWithoutTrainingLabelsIncludeSubfolderWithNonExistPrefixName(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingMultipageRunner(trainingFilesUrl -> {
FormRecognizerException thrown = assertThrows(FormRecognizerException.class, () ->
client.beginTraining(trainingFilesUrl, false, new TrainingOptions()
.setTrainingFileFilter(new TrainingFileFilter().setSubfoldersIncluded(true)
.setPrefix(INVALID_PREFIX_FILE_NAME))
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
assertEquals(NO_VALID_BLOB_FOUND, thrown.getErrorInformation().get(0).getMessage());
});
}
/**
* Verifies the result of the training operation for a valid unlabeled model Id and exclude subfolder training set
* Url with non-existing prefix name.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginTrainingWithoutTrainingLabelsExcludeSubfolderWithNonExistPrefixName(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingMultipageRunner(trainingFilesUrl -> {
FormRecognizerException thrown = assertThrows(FormRecognizerException.class, () ->
client.beginTraining(trainingFilesUrl, false,
new TrainingOptions()
.setTrainingFileFilter(new TrainingFileFilter().setPrefix(INVALID_PREFIX_FILE_NAME))
.setPollInterval(durationTestMode)).getSyncPoller()
.getFinalResult());
assertEquals(NO_VALID_BLOB_FOUND, thrown.getErrorInformation().get(0).getMessage());
});
}
} | class FormTrainingAsyncClientTest extends FormTrainingClientTestBase {
static final String EXPECTED_COPY_REQUEST_INVALID_TARGET_RESOURCE_REGION = "Status code 400, \"{\"error\":{\"code\":\"1002\",\"message\":\"Copy request is invalid. Field 'TargetResourceRegion' must be a valid Azure region name.\"}}\"";
private FormTrainingAsyncClient client;
@BeforeAll
static void beforeAll() {
StepVerifier.setDefaultTimeout(Duration.ofSeconds(30));
}
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
private FormTrainingAsyncClient getFormTrainingAsyncClient(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
return getFormTrainingClientBuilder(httpClient, serviceVersion).buildAsyncClient();
}
/**
* Verifies the form recognizer async client is valid.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
void getFormRecognizerClientAndValidate(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
FormRecognizerAsyncClient formRecognizerClient = getFormTrainingAsyncClient(httpClient, serviceVersion)
.getFormRecognizerAsyncClient();
blankPdfDataRunner(data -> {
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> syncPoller =
formRecognizerClient.beginRecognizeReceipts(toFluxByteBuffer(data), BLANK_FORM_FILE_LENGTH,
new RecognizeReceiptsOptions()
.setContentType(FormContentType.APPLICATION_PDF)
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
validateBlankPdfResultData(syncPoller.getFinalResult());
});
}
/**
* Verifies that an exception is thrown for null model Id parameter.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void getCustomModelNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.getCustomModel(null)).verifyError();
}
/**
* Verifies that an exception is thrown for invalid model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void getCustomModelInvalidModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
getCustomModelInvalidModelIdRunner(invalidModelId -> StepVerifier.create(client.getCustomModel(invalidModelId))
.expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException
&& throwable.getMessage().equals(INVALID_MODEL_ID_ERROR)).verify());
}
/**
* Verifies custom model info returned with response for a valid model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void getCustomModelWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel trainedModel = syncPoller.getFinalResult();
StepVerifier.create(client.getCustomModelWithResponse(trainedModel.getModelId())).assertNext(customFormModelResponse -> {
assertEquals(customFormModelResponse.getStatusCode(), HttpResponseStatus.OK.code());
validateCustomModelData(syncPoller.getFinalResult(), false);
});
});
}
/**
* Verifies unlabeled custom model info returned with response for a valid model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void getCustomModelUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = client.beginTraining(
trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel trainedUnlabeledModel = syncPoller.getFinalResult();
StepVerifier.create(client.getCustomModel(trainedUnlabeledModel.getModelId()))
.assertNext(customFormModel -> validateCustomModelData(syncPoller.getFinalResult(),
false));
});
}
/**
* Verifies labeled custom model info returned with response for a valid model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void getCustomModelLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel trainedLabeledModel = syncPoller.getFinalResult();
StepVerifier.create(client.getCustomModel(trainedLabeledModel.getModelId()))
.assertNext(customFormModel -> validateCustomModelData(syncPoller.getFinalResult(),
true));
});
}
/**
* Verifies account properties returned for a subscription account.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void validGetAccountProperties(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.getAccountProperties())
.assertNext(accountProperties -> validateAccountProperties(accountProperties))
.verifyComplete();
}
/**
* Verifies account properties returned with an Http Response for a subscription account.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void validGetAccountPropertiesWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.getAccountProperties())
.assertNext(accountProperties -> validateAccountProperties(accountProperties))
.verifyComplete();
}
/**
* Verifies that an exception is thrown for invalid status model Id.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void deleteModelInvalidModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.deleteModel(INVALID_MODEL_ID))
.expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException
&& throwable.getMessage().equals(INVALID_MODEL_ID_ERROR))
.verify();
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void deleteModelValidModelIdWithResponseWithoutTrainingLabels(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingUnlabeledRunner((trainingFilesUrl, notUseTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl,
notUseTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel createdModel = syncPoller.getFinalResult();
StepVerifier.create(client.deleteModelWithResponse(createdModel.getModelId()))
.assertNext(response -> assertEquals(response.getStatusCode(), HttpResponseStatus.NO_CONTENT.code()))
.verifyComplete();
StepVerifier.create(client.getCustomModelWithResponse(createdModel.getModelId()))
.verifyErrorSatisfies(throwable -> {
assertEquals(HttpResponseException.class, throwable.getClass());
final FormRecognizerErrorInformation errorInformation = (FormRecognizerErrorInformation)
((HttpResponseException) throwable).getValue();
assertEquals(EXPECTED_MODEL_ID_NOT_FOUND_ERROR_CODE, errorInformation.getErrorCode());
});
});
}
/**
* Test for listing all models information.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void listCustomModels(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
StepVerifier.create(client.listCustomModels())
.thenConsumeWhile(customFormModelInfo ->
customFormModelInfo.getModelId() != null && customFormModelInfo.getTrainingStartedOn() != null
&& customFormModelInfo.getTrainingCompletedOn() != null && customFormModelInfo.getStatus() != null)
.verifyComplete();
}
/**
* Verifies that an exception is thrown for null source url input.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginTrainingNullInput(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
NullPointerException thrown = assertThrows(
NullPointerException.class,
() -> client.beginTraining(null, false,
new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
assertTrue(thrown.getMessage().equals(NULL_SOURCE_URL_ERROR));
}
/**
* Verifies the result of the copy operation for valid parameters.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginCopy(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller =
client.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel actualModel = syncPoller.getFinalResult();
beginCopyRunner((resourceId, resourceRegion) -> {
Mono<CopyAuthorization> targetMono = client.getCopyAuthorization(resourceId, resourceRegion);
CopyAuthorization target = targetMono.block();
if (actualModel == null) {
assertTrue(false);
return;
}
PollerFlux<FormRecognizerOperationResult, CustomFormModelInfo> copyPoller =
client.beginCopyModel(actualModel.getModelId(), target);
CustomFormModelInfo copyModel = copyPoller.getSyncPoller().getFinalResult();
assertNotNull(target.getModelId(), copyModel.getModelId());
assertNotNull(actualModel.getTrainingStartedOn());
assertNotNull(actualModel.getTrainingCompletedOn());
assertEquals(CustomFormModelStatus.READY, copyModel.getStatus());
});
});
}
/**
* Verifies the Invalid region ErrorResponseException is thrown for invalid region input to copy operation.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginCopyInvalidRegion(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller =
client.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions()
.setPollInterval(durationTestMode))
.getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel actualModel = syncPoller.getFinalResult();
beginCopyInvalidRegionRunner((resourceId, resourceRegion) -> {
Mono<CopyAuthorization> targetMono = client.getCopyAuthorization(resourceId, resourceRegion);
CopyAuthorization target = targetMono.block();
if (actualModel == null) {
assertTrue(false);
return;
}
PollerFlux<FormRecognizerOperationResult, CustomFormModelInfo> copyPoller = client.beginCopyModel(
actualModel.getModelId(), target);
Exception thrown = assertThrows(HttpResponseException.class,
() -> copyPoller.getSyncPoller().getFinalResult());
assertEquals(EXPECTED_COPY_REQUEST_INVALID_TARGET_RESOURCE_REGION, thrown.getMessage());
});
});
}
/**
* Verifies {@link FormRecognizerException} is thrown for invalid region input to copy operation.
*/
@SuppressWarnings("unchecked")
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginCopyIncorrectRegion(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller =
client.beginTraining(trainingFilesUrl, useTrainingLabels,
new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
syncPoller.waitForCompletion();
CustomFormModel actualModel = syncPoller.getFinalResult();
beginCopyIncorrectRegionRunner((resourceId, resourceRegion) -> {
Mono<CopyAuthorization> targetMono = client.getCopyAuthorization(resourceId, resourceRegion);
CopyAuthorization target = targetMono.block();
if (actualModel == null) {
assertTrue(false);
return;
}
FormRecognizerException formRecognizerException = assertThrows(FormRecognizerException.class,
() -> client.beginCopyModel(actualModel.getModelId(), target)
.getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation = formRecognizerException.getErrorInformation().get(0);
});
});
}
/**
* Verifies the result of the copy authorization for valid parameters.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void copyAuthorization(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginCopyRunner((resourceId, resourceRegion) ->
StepVerifier.create(client.getCopyAuthorization(resourceId, resourceRegion))
.assertNext(copyAuthorization ->
validateCopyAuthorizationResult(resourceId, resourceRegion, copyAuthorization))
.verifyComplete()
);
}
/**
* Verifies the training operation throws FormRecognizerException when an invalid status model is returned.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginTrainingInvalidModelStatus(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingInvalidModelStatusRunner((invalidTrainingFilesUrl, useTrainingLabels) -> {
FormRecognizerException formRecognizerException = assertThrows(FormRecognizerException.class,
() -> client.beginTraining(invalidTrainingFilesUrl, useTrainingLabels).getSyncPoller().getFinalResult());
FormRecognizerErrorInformation errorInformation = formRecognizerException.getErrorInformation().get(0);
assertEquals(EXPECTED_INVALID_MODEL_STATUS_ERROR_CODE, errorInformation.getErrorCode());
assertTrue(formRecognizerException.getMessage().contains(EXPECTED_INVALID_MODEL_STATUS_MESSAGE));
assertEquals(EXPECTED_INVALID_MODEL_ERROR, errorInformation.getMessage());
assertTrue(formRecognizerException.getMessage().contains(EXPECTED_INVALID_STATUS_EXCEPTION_MESSAGE));
});
}
/**
* Verifies the result of the training operation for a valid labeled model Id and JPG training set Url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginTrainingWithTrainingLabelsForJPGTrainingSet(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller =
client.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions()
.setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
validateCustomModelData(trainingPoller.getFinalResult(), true);
});
}
/**
* Verifies the result of the training operation for a valid unlabeled model Id and JPG training set Url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginTrainingWithoutTrainingLabelsForJPGTrainingSet(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = client.beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
validateCustomModelData(trainingPoller.getFinalResult(), false);
});
}
/**
* Verifies the result of the training operation for a valid labeled model Id and multi-page PDF training set Url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginTrainingWithTrainingLabelsForMultiPagePDFTrainingSet(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingMultipageRunner(trainingFilesUrl -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = client.beginTraining(trainingFilesUrl,
true, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
validateCustomModelData(trainingPoller.getFinalResult(), true);
});
}
/**
* Verifies the result of the training operation for a valid unlabeled model Id and multi-page PDF training set Url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginTrainingWithoutTrainingLabelsForMultiPagePDFTrainingSet(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingMultipageRunner(trainingFilesUrl -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = client.beginTraining(trainingFilesUrl,
false, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
validateCustomModelData(trainingPoller.getFinalResult(), false);
});
}
/**
* Verifies the result of the training operation for a valid labeled model Id and include subfolder training set
* Url.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginTrainingWithoutTrainingLabelsIncludeSubfolderWithPrefixName(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = client.beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions()
.setPollInterval(durationTestMode)
.setTrainingFileFilter(new TrainingFileFilter().setSubfoldersIncluded(true)
.setPrefix(PREFIX_SUBFOLDER))).getSyncPoller();
trainingPoller.waitForCompletion();
validateCustomModelData(trainingPoller.getFinalResult(), false);
});
}
/**
* Verifies the result of the training operation for a valid unlabeled model ID and exclude subfolder training set
* URL with existing prefix name.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginTrainingWithoutTrainingLabelsExcludeSubfolderWithPrefixName(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingUnlabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> trainingPoller = client.beginTraining(trainingFilesUrl,
useTrainingLabels, new TrainingOptions()
.setTrainingFileFilter(new TrainingFileFilter().setPrefix(PREFIX_SUBFOLDER))
.setPollInterval(durationTestMode)).getSyncPoller();
trainingPoller.waitForCompletion();
validateCustomModelData(trainingPoller.getFinalResult(), false);
});
}
/**
* Verifies the result of the training operation for a valid unlabeled model Id and include subfolder training set
* Url with non-existing prefix name.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginTrainingWithoutTrainingLabelsIncludeSubfolderWithNonExistPrefixName(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingMultipageRunner(trainingFilesUrl -> {
FormRecognizerException thrown = assertThrows(FormRecognizerException.class, () ->
client.beginTraining(trainingFilesUrl, false, new TrainingOptions()
.setTrainingFileFilter(new TrainingFileFilter().setSubfoldersIncluded(true)
.setPrefix(INVALID_PREFIX_FILE_NAME))
.setPollInterval(durationTestMode)).getSyncPoller().getFinalResult());
assertEquals(NO_VALID_BLOB_FOUND, thrown.getErrorInformation().get(0).getMessage());
});
}
/**
* Verifies the result of the training operation for a valid unlabeled model Id and exclude subfolder training set
* Url with non-existing prefix name.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.ai.formrecognizer.TestUtils
public void beginTrainingWithoutTrainingLabelsExcludeSubfolderWithNonExistPrefixName(HttpClient httpClient,
FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingMultipageRunner(trainingFilesUrl -> {
FormRecognizerException thrown = assertThrows(FormRecognizerException.class, () ->
client.beginTraining(trainingFilesUrl, false,
new TrainingOptions()
.setTrainingFileFilter(new TrainingFileFilter().setPrefix(INVALID_PREFIX_FILE_NAME))
.setPollInterval(durationTestMode)).getSyncPoller()
.getFinalResult());
assertEquals(NO_VALID_BLOB_FOUND, thrown.getErrorInformation().get(0).getMessage());
});
}
} |
In the configurations client code, their builder never overwrites the values of the instance variables in the builder. Instead it creates local copies that can be altered instead | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
Configuration buildConfiguration = this.configuration;
if (buildConfiguration == null)
{
buildConfiguration = Configuration.getGlobalConfiguration().clone();
}
DigitalTwinsServiceVersion serviceVersion = this.serviceVersion;
if (serviceVersion == null)
{
serviceVersion = DigitalTwinsServiceVersion.getLatest();
}
HttpPipelinePolicy retryPolicy = this.retryPolicy;
if (retryPolicy == null)
{
retryPolicy = DEFAULT_RETRY_POLICY;
}
if (this.httpPipeline == null) {
this.httpPipeline = buildPipeline(
this.tokenCredential,
this.endpoint,
this.httpLogOptions,
this.httpClient,
this.additionalPolicies,
retryPolicy,
buildConfiguration,
this.properties);
}
return new DigitalTwinsAsyncClient(this.httpPipeline, serviceVersion, this.endpoint);
} | } | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
Configuration buildConfiguration = this.configuration;
if (buildConfiguration == null)
{
buildConfiguration = Configuration.getGlobalConfiguration().clone();
}
DigitalTwinsServiceVersion serviceVersion = this.serviceVersion;
if (serviceVersion == null)
{
serviceVersion = DigitalTwinsServiceVersion.getLatest();
}
HttpPipelinePolicy retryPolicy = this.retryPolicy;
if (retryPolicy == null)
{
retryPolicy = DEFAULT_RETRY_POLICY;
}
if (this.httpPipeline == null) {
this.httpPipeline = buildPipeline(
this.tokenCredential,
this.endpoint,
this.httpLogOptions,
this.httpClient,
this.additionalPolicies,
retryPolicy,
buildConfiguration,
this.properties);
}
return new DigitalTwinsAsyncClient(this.httpPipeline, serviceVersion, this.endpoint);
} | class DigitalTwinsClientBuilder {
private static final Pattern ADT_PUBLIC_SCOPE_VALIDATION_PATTERN = Pattern.compile("(ppe|azure)\\.net");
private static final String[] ADT_PUBLIC_SCOPE = new String[]{"https:
private static final String DIGITAL_TWINS_PROPERTIES = "azure-digital-twins.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final List<HttpPipelinePolicy> additionalPolicies;
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private HttpPipelinePolicy retryPolicy;
private static final String retryAfterHeader = null;
private static final ChronoUnit retryAfterTimeUnit = null;
private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy(retryAfterHeader, retryAfterTimeUnit);
private final Map<String, String> properties;
private Configuration configuration;
public DigitalTwinsClientBuilder()
{
additionalPolicies = new ArrayList<>();
properties = CoreUtils.getProperties(DIGITAL_TWINS_PROPERTIES);
httpLogOptions = new HttpLogOptions();
}
private static HttpPipeline buildPipeline(TokenCredential tokenCredential, String endpoint,
HttpLogOptions httpLogOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, HttpPipelinePolicy retryPolicy,
Configuration configuration, Map<String, String> properties) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, configuration));
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential, getAuthorizationScopes(endpoint));
policies.add(credentialPolicy);
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private static String[] getAuthorizationScopes(String endpoint) {
if (ADT_PUBLIC_SCOPE_VALIDATION_PATTERN.matcher(endpoint).find()) {
return ADT_PUBLIC_SCOPE;
}
throw new IllegalArgumentException(String.format("Azure digital twins instance endpoint %s is not valid.", endpoint));
}
/**
* Create a {@link DigitalTwinsClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsClient
*/
public DigitalTwinsClient buildClient() {
return new DigitalTwinsClient(buildAsyncClient());
}
/**
* Create a {@link DigitalTwinsAsyncClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsAsyncClient
*/
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Set the authentication token provider that the built client will use for all service requests. This field is
* mandatory to set unless you set the http pipeline directly and that set pipeline has an authentication policy configured.
*
* @param tokenCredential the authentication token provider.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder tokenCredential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link DigitalTwinsServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder serviceVersion(DigitalTwinsServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code httpLogOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.httpLogOptions = logOptions;
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public DigitalTwinsClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used as the retry policy for each request that is sent.
*
* The default retry policy will be used if not provided. The default retry policy is {@link RetryPolicy
* For implementing custom retry logic, see {@link RetryPolicy} as an example.
*
* @param retryPolicy the retry policy applied to each request.
* @return The updated ConfigurationClientBuilder object.
*/
public DigitalTwinsClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpPipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
* @return The updated DigitalTwinsClientBuilder object for fluent building.
*/
public DigitalTwinsClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
} | class DigitalTwinsClientBuilder {
private static final Pattern ADT_PUBLIC_SCOPE_VALIDATION_PATTERN = Pattern.compile("(ppe|azure)\\.net");
private static final String[] ADT_PUBLIC_SCOPE = new String[]{"https:
private static final String DIGITAL_TWINS_PROPERTIES = "azure-digital-twins.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final List<HttpPipelinePolicy> additionalPolicies;
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private HttpPipelinePolicy retryPolicy;
private static final String retryAfterHeader = null;
private static final ChronoUnit retryAfterTimeUnit = null;
private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy(retryAfterHeader, retryAfterTimeUnit);
private final Map<String, String> properties;
private Configuration configuration;
public DigitalTwinsClientBuilder()
{
additionalPolicies = new ArrayList<>();
properties = CoreUtils.getProperties(DIGITAL_TWINS_PROPERTIES);
httpLogOptions = new HttpLogOptions();
}
private static HttpPipeline buildPipeline(TokenCredential tokenCredential, String endpoint,
HttpLogOptions httpLogOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, HttpPipelinePolicy retryPolicy,
Configuration configuration, Map<String, String> properties) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, configuration));
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential, getAuthorizationScopes(endpoint));
policies.add(credentialPolicy);
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private static String[] getAuthorizationScopes(String endpoint) {
if (ADT_PUBLIC_SCOPE_VALIDATION_PATTERN.matcher(endpoint).find()) {
return ADT_PUBLIC_SCOPE;
}
throw new IllegalArgumentException(String.format("Azure digital twins instance endpoint %s is not valid.", endpoint));
}
/**
* Create a {@link DigitalTwinsClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsClient
*/
public DigitalTwinsClient buildClient() {
return new DigitalTwinsClient(buildAsyncClient());
}
/**
* Create a {@link DigitalTwinsAsyncClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsAsyncClient
*/
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Set the authentication token provider that the built client will use for all service requests. This field is
* mandatory to set unless you set the http pipeline directly and that set pipeline has an authentication policy configured.
*
* @param tokenCredential the authentication token provider.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder tokenCredential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link DigitalTwinsServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder serviceVersion(DigitalTwinsServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code httpLogOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.httpLogOptions = logOptions;
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public DigitalTwinsClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used as the retry policy for each request that is sent.
*
* The default retry policy will be used if not provided. The default retry policy is {@link RetryPolicy
* For implementing custom retry logic, see {@link RetryPolicy} as an example.
*
* @param retryPolicy the retry policy applied to each request.
* @return The updated ConfigurationClientBuilder object.
*/
public DigitalTwinsClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpPipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
* @return The updated DigitalTwinsClientBuilder object for fluent building.
*/
public DigitalTwinsClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
} |
Do we know why? Is this more efficient, or is it the defined process? | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
Configuration buildConfiguration = this.configuration;
if (buildConfiguration == null)
{
buildConfiguration = Configuration.getGlobalConfiguration().clone();
}
DigitalTwinsServiceVersion serviceVersion = this.serviceVersion;
if (serviceVersion == null)
{
serviceVersion = DigitalTwinsServiceVersion.getLatest();
}
HttpPipelinePolicy retryPolicy = this.retryPolicy;
if (retryPolicy == null)
{
retryPolicy = DEFAULT_RETRY_POLICY;
}
if (this.httpPipeline == null) {
this.httpPipeline = buildPipeline(
this.tokenCredential,
this.endpoint,
this.httpLogOptions,
this.httpClient,
this.additionalPolicies,
retryPolicy,
buildConfiguration,
this.properties);
}
return new DigitalTwinsAsyncClient(this.httpPipeline, serviceVersion, this.endpoint);
} | } | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
Configuration buildConfiguration = this.configuration;
if (buildConfiguration == null)
{
buildConfiguration = Configuration.getGlobalConfiguration().clone();
}
DigitalTwinsServiceVersion serviceVersion = this.serviceVersion;
if (serviceVersion == null)
{
serviceVersion = DigitalTwinsServiceVersion.getLatest();
}
HttpPipelinePolicy retryPolicy = this.retryPolicy;
if (retryPolicy == null)
{
retryPolicy = DEFAULT_RETRY_POLICY;
}
if (this.httpPipeline == null) {
this.httpPipeline = buildPipeline(
this.tokenCredential,
this.endpoint,
this.httpLogOptions,
this.httpClient,
this.additionalPolicies,
retryPolicy,
buildConfiguration,
this.properties);
}
return new DigitalTwinsAsyncClient(this.httpPipeline, serviceVersion, this.endpoint);
} | class DigitalTwinsClientBuilder {
private static final Pattern ADT_PUBLIC_SCOPE_VALIDATION_PATTERN = Pattern.compile("(ppe|azure)\\.net");
private static final String[] ADT_PUBLIC_SCOPE = new String[]{"https:
private static final String DIGITAL_TWINS_PROPERTIES = "azure-digital-twins.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final List<HttpPipelinePolicy> additionalPolicies;
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private HttpPipelinePolicy retryPolicy;
private static final String retryAfterHeader = null;
private static final ChronoUnit retryAfterTimeUnit = null;
private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy(retryAfterHeader, retryAfterTimeUnit);
private final Map<String, String> properties;
private Configuration configuration;
public DigitalTwinsClientBuilder()
{
additionalPolicies = new ArrayList<>();
properties = CoreUtils.getProperties(DIGITAL_TWINS_PROPERTIES);
httpLogOptions = new HttpLogOptions();
}
private static HttpPipeline buildPipeline(TokenCredential tokenCredential, String endpoint,
HttpLogOptions httpLogOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, HttpPipelinePolicy retryPolicy,
Configuration configuration, Map<String, String> properties) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, configuration));
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential, getAuthorizationScopes(endpoint));
policies.add(credentialPolicy);
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private static String[] getAuthorizationScopes(String endpoint) {
if (ADT_PUBLIC_SCOPE_VALIDATION_PATTERN.matcher(endpoint).find()) {
return ADT_PUBLIC_SCOPE;
}
throw new IllegalArgumentException(String.format("Azure digital twins instance endpoint %s is not valid.", endpoint));
}
/**
* Create a {@link DigitalTwinsClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsClient
*/
public DigitalTwinsClient buildClient() {
return new DigitalTwinsClient(buildAsyncClient());
}
/**
* Create a {@link DigitalTwinsAsyncClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsAsyncClient
*/
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Set the authentication token provider that the built client will use for all service requests. This field is
* mandatory to set unless you set the http pipeline directly and that set pipeline has an authentication policy configured.
*
* @param tokenCredential the authentication token provider.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder tokenCredential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link DigitalTwinsServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder serviceVersion(DigitalTwinsServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code httpLogOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.httpLogOptions = logOptions;
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public DigitalTwinsClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used as the retry policy for each request that is sent.
*
* The default retry policy will be used if not provided. The default retry policy is {@link RetryPolicy
* For implementing custom retry logic, see {@link RetryPolicy} as an example.
*
* @param retryPolicy the retry policy applied to each request.
* @return The updated ConfigurationClientBuilder object.
*/
public DigitalTwinsClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpPipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
* @return The updated DigitalTwinsClientBuilder object for fluent building.
*/
public DigitalTwinsClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
} | class DigitalTwinsClientBuilder {
private static final Pattern ADT_PUBLIC_SCOPE_VALIDATION_PATTERN = Pattern.compile("(ppe|azure)\\.net");
private static final String[] ADT_PUBLIC_SCOPE = new String[]{"https:
private static final String DIGITAL_TWINS_PROPERTIES = "azure-digital-twins.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final List<HttpPipelinePolicy> additionalPolicies;
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private HttpPipelinePolicy retryPolicy;
private static final String retryAfterHeader = null;
private static final ChronoUnit retryAfterTimeUnit = null;
private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy(retryAfterHeader, retryAfterTimeUnit);
private final Map<String, String> properties;
private Configuration configuration;
public DigitalTwinsClientBuilder()
{
additionalPolicies = new ArrayList<>();
properties = CoreUtils.getProperties(DIGITAL_TWINS_PROPERTIES);
httpLogOptions = new HttpLogOptions();
}
private static HttpPipeline buildPipeline(TokenCredential tokenCredential, String endpoint,
HttpLogOptions httpLogOptions, HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies, HttpPipelinePolicy retryPolicy,
Configuration configuration, Map<String, String> properties) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, configuration));
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
HttpPipelinePolicy credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential, getAuthorizationScopes(endpoint));
policies.add(credentialPolicy);
policies.addAll(additionalPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private static String[] getAuthorizationScopes(String endpoint) {
if (ADT_PUBLIC_SCOPE_VALIDATION_PATTERN.matcher(endpoint).find()) {
return ADT_PUBLIC_SCOPE;
}
throw new IllegalArgumentException(String.format("Azure digital twins instance endpoint %s is not valid.", endpoint));
}
/**
* Create a {@link DigitalTwinsClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsClient
*/
public DigitalTwinsClient buildClient() {
return new DigitalTwinsClient(buildAsyncClient());
}
/**
* Create a {@link DigitalTwinsAsyncClient} based on the builder settings.
*
* @return the created synchronous DigitalTwinsAsyncClient
*/
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Set the authentication token provider that the built client will use for all service requests. This field is
* mandatory to set unless you set the http pipeline directly and that set pipeline has an authentication policy configured.
*
* @param tokenCredential the authentication token provider.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder tokenCredential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
return this;
}
/**
* Sets the {@link DigitalTwinsServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder serviceVersion(DigitalTwinsServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code httpLogOptions} is {@code null}.
*/
public DigitalTwinsClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.httpLogOptions = logOptions;
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public DigitalTwinsClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used as the retry policy for each request that is sent.
*
* The default retry policy will be used if not provided. The default retry policy is {@link RetryPolicy
* For implementing custom retry logic, see {@link RetryPolicy} as an example.
*
* @param retryPolicy the retry policy applied to each request.
* @return The updated ConfigurationClientBuilder object.
*/
public DigitalTwinsClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated DigitalTwinsClientBuilder instance for fluent building.
*/
public DigitalTwinsClientBuilder httpPipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
* @return The updated DigitalTwinsClientBuilder object for fluent building.
*/
public DigitalTwinsClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
} |
nit: not sure if we want to rename the sample file to reflect the change. | public static void main(String[] args) {
FormRecognizerClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildClient();
String modelId = "{model_Id}";
String formUrl = "{form_url}";
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> recognizeFormPoller =
client.beginRecognizeCustomFormsFromUrl(modelId, formUrl, new RecognizeCustomFormsOptions()
.setFieldElementsIncluded(true), Context.NONE);
List<RecognizedForm> recognizedForms = recognizeFormPoller.getFinalResult();
for (int i = 0; i < recognizedForms.size(); i++) {
final RecognizedForm recognizedForm = recognizedForms.get(i);
System.out.printf("Form %d has type: %s%n", i, recognizedForm.getFormType());
recognizedForm.getFields().forEach((fieldText, formField) -> System.out.printf("Field %s has value data "
+ "text %s with a confidence score of %.2f.%n",
fieldText, formField.getValueData().getText(),
formField.getConfidence()));
final List<FormPage> pages = recognizedForm.getPages();
for (int i1 = 0; i1 < pages.size(); i1++) {
final FormPage formPage = pages.get(i1);
System.out.printf("------- Recognizing info on page %s of Form ------- %n", i1);
System.out.printf("Has width: %f, angle: %.2f, height: %f %n", formPage.getWidth(),
formPage.getTextAngle(), formPage.getHeight());
System.out.println("Recognized Tables: ");
final List<FormTable> tables = formPage.getTables();
for (int i2 = 0; i2 < tables.size(); i2++) {
final FormTable formTable = tables.get(i2);
System.out.printf("Table %d%n", i2);
formTable.getCells()
.forEach(formTableCell -> {
System.out.printf("Cell text %s has following words: %n", formTableCell.getText());
formTableCell.getFieldElements().stream()
.filter(formContent -> formContent instanceof FormWord)
.map(formContent -> (FormWord) (formContent))
.forEach(formWordElement -> {
String boundingBoxStr = null;
if (formWordElement.getBoundingBox() != null) {
boundingBoxStr = formWordElement.getBoundingBox().toString();
}
System.out.printf("Word '%s' within bounding box %s with a confidence of %.2f.%n",
formWordElement.getText(), boundingBoxStr, formWordElement.getConfidence());
});
});
System.out.println();
}
}
}
} | System.out.printf("------- Recognizing info on page %s of Form ------- %n", i1); | public static void main(String[] args) {
FormRecognizerClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildClient();
String modelId = "{model_Id}";
String formUrl = "{form_url}";
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> recognizeFormPoller =
client.beginRecognizeCustomFormsFromUrl(modelId, formUrl, new RecognizeCustomFormsOptions()
.setFieldElementsIncluded(true), Context.NONE);
List<RecognizedForm> recognizedForms = recognizeFormPoller.getFinalResult();
for (int i = 0; i < recognizedForms.size(); i++) {
final RecognizedForm recognizedForm = recognizedForms.get(i);
System.out.printf("Form %d has type: %s%n", i, recognizedForm.getFormType());
recognizedForm.getFields().forEach((fieldText, formField) -> System.out.printf("Field %s has value data "
+ "text %s with a confidence score of %.2f.%n",
fieldText, formField.getValueData().getText(),
formField.getConfidence()));
final List<FormPage> pages = recognizedForm.getPages();
for (int i1 = 0; i1 < pages.size(); i1++) {
final FormPage formPage = pages.get(i1);
System.out.printf("------- Recognizing info on page %s of Form ------- %n", i1);
System.out.printf("Has width: %f, angle: %.2f, height: %f %n", formPage.getWidth(),
formPage.getTextAngle(), formPage.getHeight());
System.out.println("Recognized Tables: ");
final List<FormTable> tables = formPage.getTables();
for (int i2 = 0; i2 < tables.size(); i2++) {
final FormTable formTable = tables.get(i2);
System.out.printf("Table %d%n", i2);
formTable.getCells()
.forEach(formTableCell -> {
System.out.printf("Cell text %s has following words: %n", formTableCell.getText());
formTableCell.getFieldElements().stream()
.filter(formContent -> formContent instanceof FormWord)
.map(formContent -> (FormWord) (formContent))
.forEach(formWordElement -> {
String boundingBoxStr = null;
if (formWordElement.getBoundingBox() != null) {
boundingBoxStr = formWordElement.getBoundingBox().toString();
}
System.out.printf("Word '%s' within bounding box %s with a confidence of %.2f.%n",
formWordElement.getText(), boundingBoxStr, formWordElement.getConfidence());
});
});
System.out.println();
}
}
}
} | class GetBoundingBoxes {
/**
* Main method to invoke this demo.
*
* @param args Unused arguments to the program.
*/
} | class GetBoundingBoxes {
/**
* Main method to invoke this demo.
*
* @param args Unused arguments to the program.
*/
} |
Should we put `Pattern.compile("\\w+\\.\\w+/([^;]+);(\\d+)")` to a static, to save runtime cost to do it every time? | public ResourceManagerThrottlingInfo(HttpHeaders headers) {
commonRateLimits = new HashMap<>();
for (String header : COMMON_RATE_LIMIT_HEADERS) {
String value = headers.getValue(header);
if (value != null && !value.isEmpty()) {
commonRateLimits.put(header, value);
}
}
resourceRateLimit = headers.getValue(RESOURCE_RATE_LIMIT_HEADERS);
Matcher matcher = Pattern.compile("\\w+\\.\\w+/([^;]+);(\\d+)").matcher(resourceRateLimit);
while (matcher.find()) {
commonRateLimits.put(
String.format("%s-%s", RESOURCE_RATE_LIMIT_HEADERS, matcher.group(1)), matcher.group(2));
}
} | Matcher matcher = Pattern.compile("\\w+\\.\\w+/([^;]+);(\\d+)").matcher(resourceRateLimit); | public ResourceManagerThrottlingInfo(HttpHeaders headers) {
commonRateLimits = new HashMap<>();
for (String header : COMMON_RATE_LIMIT_HEADERS) {
String value = headers.getValue(header);
if (value != null && !value.isEmpty()) {
commonRateLimits.put(header, value);
}
}
resourceRateLimit = headers.getValue(RESOURCE_RATE_LIMIT_HEADER);
Matcher matcher = RESOURCE_RATE_LIMIT_HEADER_PATTERN.matcher(resourceRateLimit);
while (matcher.find()) {
commonRateLimits.put(
String.format("%s-%s", RESOURCE_RATE_LIMIT_HEADER, matcher.group(1)), matcher.group(2));
}
} | class from response headers
* @param headers the response headers
*/ | class from response headers
* @param headers the response headers
*/ |
done | public ResourceManagerThrottlingInfo(HttpHeaders headers) {
commonRateLimits = new HashMap<>();
for (String header : COMMON_RATE_LIMIT_HEADERS) {
String value = headers.getValue(header);
if (value != null && !value.isEmpty()) {
commonRateLimits.put(header, value);
}
}
resourceRateLimit = headers.getValue(RESOURCE_RATE_LIMIT_HEADERS);
Matcher matcher = Pattern.compile("\\w+\\.\\w+/([^;]+);(\\d+)").matcher(resourceRateLimit);
while (matcher.find()) {
commonRateLimits.put(
String.format("%s-%s", RESOURCE_RATE_LIMIT_HEADERS, matcher.group(1)), matcher.group(2));
}
} | Matcher matcher = Pattern.compile("\\w+\\.\\w+/([^;]+);(\\d+)").matcher(resourceRateLimit); | public ResourceManagerThrottlingInfo(HttpHeaders headers) {
commonRateLimits = new HashMap<>();
for (String header : COMMON_RATE_LIMIT_HEADERS) {
String value = headers.getValue(header);
if (value != null && !value.isEmpty()) {
commonRateLimits.put(header, value);
}
}
resourceRateLimit = headers.getValue(RESOURCE_RATE_LIMIT_HEADER);
Matcher matcher = RESOURCE_RATE_LIMIT_HEADER_PATTERN.matcher(resourceRateLimit);
while (matcher.find()) {
commonRateLimits.put(
String.format("%s-%s", RESOURCE_RATE_LIMIT_HEADER, matcher.group(1)), matcher.group(2));
}
} | class from response headers
* @param headers the response headers
*/ | class from response headers
* @param headers the response headers
*/ |
Is `Jdk8Module` is used for support `Optional` type in json? Can we use null instead of `Optional`? | private List<UserGroup> loadUserGroups(String graphApiToken) throws IOException {
String responseInJson = getUserMemberships(graphApiToken, Optional.empty());
final List<UserGroup> lUserGroups = new ArrayList<>();
final ObjectMapper objectMapper = JacksonObjectMapperFactory.getInstance();
objectMapper.registerModule(new Jdk8Module());
UserGroups groupsFromJson = objectMapper.readValue(responseInJson, UserGroups.class);
if (groupsFromJson.getValue() != null) {
lUserGroups.addAll(groupsFromJson.getValue().stream().filter(this::isMatchingUserGroupKey)
.collect(Collectors.toList()));
}
while (groupsFromJson.getOdataNextLink().isPresent()) {
responseInJson = getUserMemberships(graphApiToken, groupsFromJson.getOdataNextLink());
groupsFromJson = objectMapper.readValue(responseInJson, UserGroups.class);
lUserGroups.addAll(groupsFromJson.getValue().stream().filter(this::isMatchingUserGroupKey)
.collect(Collectors.toList()));
}
return lUserGroups;
} | objectMapper.registerModule(new Jdk8Module()); | private List<UserGroup> loadUserGroups(String graphApiToken) throws IOException {
String responseInJson = getUserMemberships(graphApiToken, null);
final List<UserGroup> lUserGroups = new ArrayList<>();
final ObjectMapper objectMapper = JacksonObjectMapperFactory.getInstance();
UserGroups groupsFromJson = objectMapper.readValue(responseInJson, UserGroups.class);
if (groupsFromJson.getValue() != null) {
lUserGroups.addAll(groupsFromJson.getValue().stream().filter(this::isMatchingUserGroupKey)
.collect(Collectors.toList()));
}
while (groupsFromJson.getOdataNextLink() != null) {
responseInJson = getUserMemberships(graphApiToken, groupsFromJson.getOdataNextLink());
groupsFromJson = objectMapper.readValue(responseInJson, UserGroups.class);
lUserGroups.addAll(groupsFromJson.getValue().stream().filter(this::isMatchingUserGroupKey)
.collect(Collectors.toList()));
}
return lUserGroups;
} | class AzureADGraphClient {
private static final Logger LOGGER = LoggerFactory.getLogger(AzureADGraphClient.class);
private static final SimpleGrantedAuthority DEFAULT_AUTHORITY = new SimpleGrantedAuthority("ROLE_USER");
private static final String DEFAULT_ROLE_PREFIX = "ROLE_";
private static final String MICROSOFT_GRAPH_SCOPE = "https:
private static final String AAD_GRAPH_API_SCOPE = "https:
private static final String REQUEST_ID_SUFFIX = "aadfeed6";
private final String clientId;
private final String clientSecret;
private final ServiceEndpoints serviceEndpoints;
private final AADAuthenticationProperties aadAuthenticationProperties;
private static final String V2_VERSION_ENV_FLAG = "v2-graph";
private boolean aadMicrosoftGraphApiBool;
public AzureADGraphClient(String clientId, String clientSecret, AADAuthenticationProperties aadAuthProps,
ServiceEndpointsProperties serviceEndpointsProps) {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.aadAuthenticationProperties = aadAuthProps;
this.serviceEndpoints = serviceEndpointsProps.getServiceEndpoints(aadAuthProps.getEnvironment());
this.initAADMicrosoftGraphApiBool(aadAuthProps.getEnvironment());
}
private void initAADMicrosoftGraphApiBool(String endpointEnv) {
this.aadMicrosoftGraphApiBool = endpointEnv.contains(V2_VERSION_ENV_FLAG);
}
private String getUserMemberships(String accessToken, Optional<String> odataNextLink) throws IOException {
final URL url = new URL(serviceEndpoints.getAadMembershipRestUri());
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (this.aadMicrosoftGraphApiBool) {
conn.setRequestMethod(HttpMethod.GET.toString());
conn.setRequestProperty(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", accessToken));
conn.setRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
} else {
conn.setRequestMethod(HttpMethod.GET.toString());
conn.setRequestProperty("api-version", "1.6");
conn.setRequestProperty(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", accessToken));
conn.setRequestProperty(HttpHeaders.ACCEPT, "application/json;odata=minimalmetadata");
}
final String responseInJson = getResponseStringFromConn(conn);
final int responseCode = conn.getResponseCode();
if (responseCode == HTTPResponse.SC_OK) {
return responseInJson;
} else {
throw new IllegalStateException("Response is not "
+ HTTPResponse.SC_OK + ", response json: " + responseInJson);
}
}
private static String getResponseStringFromConn(HttpURLConnection conn) throws IOException {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
final StringBuilder stringBuffer = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuffer.append(line);
}
return stringBuffer.toString();
}
}
public List<UserGroup> getGroups(String graphApiToken) throws IOException {
return loadUserGroups(graphApiToken);
}
/**
* Checks that the JSON Node is a valid User Group to extract User Groups from
*
* @param node - json node to look for a key/value to equate against the
* {@link AADAuthenticationProperties.UserGroupProperties}
* @return true if the json node contains the correct key, and expected value to identify a user group.
*/
private boolean isMatchingUserGroupKey(final UserGroup group) {
return group.getObjectType().equals(aadAuthenticationProperties.getUserGroup().getValue());
}
public Set<GrantedAuthority> getGrantedAuthorities(String graphApiToken) throws IOException {
final List<UserGroup> groups = getGroups(graphApiToken);
return convertGroupsToGrantedAuthorities(groups);
}
/**
* Converts UserGroup list to Set of GrantedAuthorities
*
* @param groups user groups
* @return granted authorities
*/
public Set<GrantedAuthority> convertGroupsToGrantedAuthorities(final List<UserGroup> groups) {
final Set<GrantedAuthority> mappedAuthorities = groups.stream().filter(this::isValidUserGroupToGrantAuthority)
.map(userGroup -> new SimpleGrantedAuthority(DEFAULT_ROLE_PREFIX + userGroup.getDisplayName()))
.collect(Collectors.toCollection(LinkedHashSet::new));
if (mappedAuthorities.isEmpty()) {
mappedAuthorities.add(DEFAULT_AUTHORITY);
}
return mappedAuthorities;
}
/**
* Determines if this is a valid {@link UserGroup} to build to a GrantedAuthority.
* <p>
* If the {@link AADAuthenticationProperties.UserGroupProperties
* contains the {@link UserGroup
* true.
*
* @param group - User Group to check if valid to grant an authority to.
* @return true if allowed-groups contains the UserGroup display name
*/
private boolean isValidUserGroupToGrantAuthority(final UserGroup group) {
return aadAuthenticationProperties.getUserGroup().getAllowedGroups().contains(group.getDisplayName());
}
public IAuthenticationResult acquireTokenForGraphApi(String idToken, String tenantId)
throws ServiceUnavailableException {
final IClientCredential clientCredential = ClientCredentialFactory.createFromSecret(clientSecret);
final UserAssertion assertion = new UserAssertion(idToken);
IAuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
final ConfidentialClientApplication application = ConfidentialClientApplication
.builder(clientId, clientCredential)
.authority(serviceEndpoints.getAadSigninUri() + tenantId + "/")
.correlationId(getCorrelationId())
.build();
final Set<String> scopes = new HashSet<>();
scopes.add(aadMicrosoftGraphApiBool ? MICROSOFT_GRAPH_SCOPE : AAD_GRAPH_API_SCOPE);
final OnBehalfOfParameters onBehalfOfParameters = OnBehalfOfParameters
.builder(scopes, assertion)
.build();
final CompletableFuture<IAuthenticationResult> future = application.acquireToken(onBehalfOfParameters);
result = future.get();
} catch (ExecutionException | InterruptedException | MalformedURLException e) {
final Throwable cause = e.getCause();
if (cause instanceof MsalServiceException) {
final MsalServiceException exception = (MsalServiceException) cause;
if (exception.claims() != null && !exception.claims().isEmpty()) {
throw exception;
}
}
LOGGER.error("acquire on behalf of token for graph api error", e);
} finally {
if (service != null) {
service.shutdown();
}
}
if (result == null) {
throw new ServiceUnavailableException("unable to acquire on-behalf-of token for client " + clientId);
}
return result;
}
private static String getCorrelationId() {
final String uuid = UUID.randomUUID().toString();
return uuid.substring(0, uuid.length() - REQUEST_ID_SUFFIX.length()) + REQUEST_ID_SUFFIX;
}
} | class AzureADGraphClient {
private static final Logger LOGGER = LoggerFactory.getLogger(AzureADGraphClient.class);
private static final SimpleGrantedAuthority DEFAULT_AUTHORITY = new SimpleGrantedAuthority("ROLE_USER");
private static final String DEFAULT_ROLE_PREFIX = "ROLE_";
private static final String MICROSOFT_GRAPH_SCOPE = "https:
private static final String AAD_GRAPH_API_SCOPE = "https:
private static final String REQUEST_ID_SUFFIX = "aadfeed6";
private final String clientId;
private final String clientSecret;
private final ServiceEndpoints serviceEndpoints;
private final AADAuthenticationProperties aadAuthenticationProperties;
private static final String V2_VERSION_ENV_FLAG = "v2-graph";
private boolean aadMicrosoftGraphApiBool;
public AzureADGraphClient(String clientId, String clientSecret, AADAuthenticationProperties aadAuthProps,
ServiceEndpointsProperties serviceEndpointsProps) {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.aadAuthenticationProperties = aadAuthProps;
this.serviceEndpoints = serviceEndpointsProps.getServiceEndpoints(aadAuthProps.getEnvironment());
this.initAADMicrosoftGraphApiBool(aadAuthProps.getEnvironment());
}
private void initAADMicrosoftGraphApiBool(String endpointEnv) {
this.aadMicrosoftGraphApiBool = endpointEnv.contains(V2_VERSION_ENV_FLAG);
}
private String getUserMemberships(String accessToken, String odataNextLink) throws IOException {
final URL url = buildUrl(odataNextLink);
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (this.aadMicrosoftGraphApiBool) {
conn.setRequestMethod(HttpMethod.GET.toString());
conn.setRequestProperty(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", accessToken));
conn.setRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
} else {
conn.setRequestMethod(HttpMethod.GET.toString());
conn.setRequestProperty("api-version", "1.6");
conn.setRequestProperty(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", accessToken));
conn.setRequestProperty(HttpHeaders.ACCEPT, "application/json;odata=minimalmetadata");
}
final String responseInJson = getResponseStringFromConn(conn);
final int responseCode = conn.getResponseCode();
if (responseCode == HTTPResponse.SC_OK) {
return responseInJson;
} else {
throw new IllegalStateException("Response is not "
+ HTTPResponse.SC_OK + ", response json: " + responseInJson);
}
}
private String getSkipTokenFromLink(String odataNextLink) {
String[] parts = odataNextLink.split("/memberOf\\?");
return parts[1];
}
private URL buildUrl(String odataNextLink) throws MalformedURLException {
URL url;
if (odataNextLink != null) {
if (this.aadMicrosoftGraphApiBool) {
url = new URL(odataNextLink);
} else {
String skipToken = getSkipTokenFromLink(odataNextLink);
url = new URL(serviceEndpoints.getAadMembershipRestUri() + "&" + skipToken);
}
} else {
url = new URL(serviceEndpoints.getAadMembershipRestUri());
}
return url;
}
private static String getResponseStringFromConn(HttpURLConnection conn) throws IOException {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
final StringBuilder stringBuffer = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuffer.append(line);
}
return stringBuffer.toString();
}
}
public List<UserGroup> getGroups(String graphApiToken) throws IOException {
return loadUserGroups(graphApiToken);
}
/**
* Checks that the UserGroup has a Group object type.
*
* @param node - json node to look for a key/value to equate against the
* {@link AADAuthenticationProperties.UserGroupProperties}
* @return true if the json node contains the correct key, and expected value to identify a user group.
*/
private boolean isMatchingUserGroupKey(final UserGroup group) {
return group.getObjectType().equals(aadAuthenticationProperties.getUserGroup().getValue());
}
public Set<GrantedAuthority> getGrantedAuthorities(String graphApiToken) throws IOException {
final List<UserGroup> groups = getGroups(graphApiToken);
return convertGroupsToGrantedAuthorities(groups);
}
/**
* Converts UserGroup list to Set of GrantedAuthorities
*
* @param groups user groups
* @return granted authorities
*/
public Set<GrantedAuthority> convertGroupsToGrantedAuthorities(final List<UserGroup> groups) {
final Set<GrantedAuthority> mappedAuthorities = groups.stream().filter(this::isValidUserGroupToGrantAuthority)
.map(userGroup -> new SimpleGrantedAuthority(DEFAULT_ROLE_PREFIX + userGroup.getDisplayName()))
.collect(Collectors.toCollection(LinkedHashSet::new));
if (mappedAuthorities.isEmpty()) {
mappedAuthorities.add(DEFAULT_AUTHORITY);
}
return mappedAuthorities;
}
/**
* Determines if this is a valid {@link UserGroup} to build to a GrantedAuthority.
* <p>
* If the {@link AADAuthenticationProperties.UserGroupProperties
* contains the {@link UserGroup
* true.
*
* @param group - User Group to check if valid to grant an authority to.
* @return true if allowed-groups contains the UserGroup display name
*/
private boolean isValidUserGroupToGrantAuthority(final UserGroup group) {
return aadAuthenticationProperties.getUserGroup().getAllowedGroups().contains(group.getDisplayName());
}
public IAuthenticationResult acquireTokenForGraphApi(String idToken, String tenantId)
throws ServiceUnavailableException {
final IClientCredential clientCredential = ClientCredentialFactory.createFromSecret(clientSecret);
final UserAssertion assertion = new UserAssertion(idToken);
IAuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
final ConfidentialClientApplication application = ConfidentialClientApplication
.builder(clientId, clientCredential)
.authority(serviceEndpoints.getAadSigninUri() + tenantId + "/")
.correlationId(getCorrelationId())
.build();
final Set<String> scopes = new HashSet<>();
scopes.add(aadMicrosoftGraphApiBool ? MICROSOFT_GRAPH_SCOPE : AAD_GRAPH_API_SCOPE);
final OnBehalfOfParameters onBehalfOfParameters = OnBehalfOfParameters
.builder(scopes, assertion)
.build();
final CompletableFuture<IAuthenticationResult> future = application.acquireToken(onBehalfOfParameters);
result = future.get();
} catch (ExecutionException | InterruptedException | MalformedURLException e) {
final Throwable cause = e.getCause();
if (cause instanceof MsalServiceException) {
final MsalServiceException exception = (MsalServiceException) cause;
if (exception.claims() != null && !exception.claims().isEmpty()) {
throw exception;
}
}
LOGGER.error("acquire on behalf of token for graph api error", e);
} finally {
if (service != null) {
service.shutdown();
}
}
if (result == null) {
throw new ServiceUnavailableException("unable to acquire on-behalf-of token for client " + clientId);
}
return result;
}
private static String getCorrelationId() {
final String uuid = UUID.randomUUID().toString();
return uuid.substring(0, uuid.length() - REQUEST_ID_SUFFIX.length()) + REQUEST_ID_SUFFIX;
}
} |
I debugged in my localhost, `groupsFromJson.getOdataNextLink()` will return `null`, not `Optional.empty()`, so `groupsFromJson.getOdataNextLink().isPresent()` will throw `NullPointerExceotion`. Json:  Screenshot of IDE:  | private List<UserGroup> loadUserGroups(String graphApiToken) throws IOException {
String responseInJson = getUserMemberships(graphApiToken, Optional.empty());
final List<UserGroup> lUserGroups = new ArrayList<>();
final ObjectMapper objectMapper = JacksonObjectMapperFactory.getInstance();
objectMapper.registerModule(new Jdk8Module());
UserGroups groupsFromJson = objectMapper.readValue(responseInJson, UserGroups.class);
if (groupsFromJson.getValue() != null) {
lUserGroups.addAll(groupsFromJson.getValue().stream().filter(this::isMatchingUserGroupKey)
.collect(Collectors.toList()));
}
while (groupsFromJson.getOdataNextLink().isPresent()) {
responseInJson = getUserMemberships(graphApiToken, groupsFromJson.getOdataNextLink());
groupsFromJson = objectMapper.readValue(responseInJson, UserGroups.class);
lUserGroups.addAll(groupsFromJson.getValue().stream().filter(this::isMatchingUserGroupKey)
.collect(Collectors.toList()));
}
return lUserGroups;
} | while (groupsFromJson.getOdataNextLink().isPresent()) { | private List<UserGroup> loadUserGroups(String graphApiToken) throws IOException {
String responseInJson = getUserMemberships(graphApiToken, null);
final List<UserGroup> lUserGroups = new ArrayList<>();
final ObjectMapper objectMapper = JacksonObjectMapperFactory.getInstance();
UserGroups groupsFromJson = objectMapper.readValue(responseInJson, UserGroups.class);
if (groupsFromJson.getValue() != null) {
lUserGroups.addAll(groupsFromJson.getValue().stream().filter(this::isMatchingUserGroupKey)
.collect(Collectors.toList()));
}
while (groupsFromJson.getOdataNextLink() != null) {
responseInJson = getUserMemberships(graphApiToken, groupsFromJson.getOdataNextLink());
groupsFromJson = objectMapper.readValue(responseInJson, UserGroups.class);
lUserGroups.addAll(groupsFromJson.getValue().stream().filter(this::isMatchingUserGroupKey)
.collect(Collectors.toList()));
}
return lUserGroups;
} | class AzureADGraphClient {
private static final Logger LOGGER = LoggerFactory.getLogger(AzureADGraphClient.class);
private static final SimpleGrantedAuthority DEFAULT_AUTHORITY = new SimpleGrantedAuthority("ROLE_USER");
private static final String DEFAULT_ROLE_PREFIX = "ROLE_";
private static final String MICROSOFT_GRAPH_SCOPE = "https:
private static final String AAD_GRAPH_API_SCOPE = "https:
private static final String REQUEST_ID_SUFFIX = "aadfeed6";
private final String clientId;
private final String clientSecret;
private final ServiceEndpoints serviceEndpoints;
private final AADAuthenticationProperties aadAuthenticationProperties;
private static final String V2_VERSION_ENV_FLAG = "v2-graph";
private boolean aadMicrosoftGraphApiBool;
public AzureADGraphClient(String clientId, String clientSecret, AADAuthenticationProperties aadAuthProps,
ServiceEndpointsProperties serviceEndpointsProps) {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.aadAuthenticationProperties = aadAuthProps;
this.serviceEndpoints = serviceEndpointsProps.getServiceEndpoints(aadAuthProps.getEnvironment());
this.initAADMicrosoftGraphApiBool(aadAuthProps.getEnvironment());
}
private void initAADMicrosoftGraphApiBool(String endpointEnv) {
this.aadMicrosoftGraphApiBool = endpointEnv.contains(V2_VERSION_ENV_FLAG);
}
private String getUserMemberships(String accessToken, Optional<String> odataNextLink) throws IOException {
final URL url = new URL(serviceEndpoints.getAadMembershipRestUri());
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (this.aadMicrosoftGraphApiBool) {
conn.setRequestMethod(HttpMethod.GET.toString());
conn.setRequestProperty(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", accessToken));
conn.setRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
} else {
conn.setRequestMethod(HttpMethod.GET.toString());
conn.setRequestProperty("api-version", "1.6");
conn.setRequestProperty(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", accessToken));
conn.setRequestProperty(HttpHeaders.ACCEPT, "application/json;odata=minimalmetadata");
}
final String responseInJson = getResponseStringFromConn(conn);
final int responseCode = conn.getResponseCode();
if (responseCode == HTTPResponse.SC_OK) {
return responseInJson;
} else {
throw new IllegalStateException("Response is not "
+ HTTPResponse.SC_OK + ", response json: " + responseInJson);
}
}
private static String getResponseStringFromConn(HttpURLConnection conn) throws IOException {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
final StringBuilder stringBuffer = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuffer.append(line);
}
return stringBuffer.toString();
}
}
public List<UserGroup> getGroups(String graphApiToken) throws IOException {
return loadUserGroups(graphApiToken);
}
/**
* Checks that the JSON Node is a valid User Group to extract User Groups from
*
* @param node - json node to look for a key/value to equate against the
* {@link AADAuthenticationProperties.UserGroupProperties}
* @return true if the json node contains the correct key, and expected value to identify a user group.
*/
private boolean isMatchingUserGroupKey(final UserGroup group) {
return group.getObjectType().equals(aadAuthenticationProperties.getUserGroup().getValue());
}
public Set<GrantedAuthority> getGrantedAuthorities(String graphApiToken) throws IOException {
final List<UserGroup> groups = getGroups(graphApiToken);
return convertGroupsToGrantedAuthorities(groups);
}
/**
* Converts UserGroup list to Set of GrantedAuthorities
*
* @param groups user groups
* @return granted authorities
*/
public Set<GrantedAuthority> convertGroupsToGrantedAuthorities(final List<UserGroup> groups) {
final Set<GrantedAuthority> mappedAuthorities = groups.stream().filter(this::isValidUserGroupToGrantAuthority)
.map(userGroup -> new SimpleGrantedAuthority(DEFAULT_ROLE_PREFIX + userGroup.getDisplayName()))
.collect(Collectors.toCollection(LinkedHashSet::new));
if (mappedAuthorities.isEmpty()) {
mappedAuthorities.add(DEFAULT_AUTHORITY);
}
return mappedAuthorities;
}
/**
* Determines if this is a valid {@link UserGroup} to build to a GrantedAuthority.
* <p>
* If the {@link AADAuthenticationProperties.UserGroupProperties
* contains the {@link UserGroup
* true.
*
* @param group - User Group to check if valid to grant an authority to.
* @return true if allowed-groups contains the UserGroup display name
*/
private boolean isValidUserGroupToGrantAuthority(final UserGroup group) {
return aadAuthenticationProperties.getUserGroup().getAllowedGroups().contains(group.getDisplayName());
}
public IAuthenticationResult acquireTokenForGraphApi(String idToken, String tenantId)
throws ServiceUnavailableException {
final IClientCredential clientCredential = ClientCredentialFactory.createFromSecret(clientSecret);
final UserAssertion assertion = new UserAssertion(idToken);
IAuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
final ConfidentialClientApplication application = ConfidentialClientApplication
.builder(clientId, clientCredential)
.authority(serviceEndpoints.getAadSigninUri() + tenantId + "/")
.correlationId(getCorrelationId())
.build();
final Set<String> scopes = new HashSet<>();
scopes.add(aadMicrosoftGraphApiBool ? MICROSOFT_GRAPH_SCOPE : AAD_GRAPH_API_SCOPE);
final OnBehalfOfParameters onBehalfOfParameters = OnBehalfOfParameters
.builder(scopes, assertion)
.build();
final CompletableFuture<IAuthenticationResult> future = application.acquireToken(onBehalfOfParameters);
result = future.get();
} catch (ExecutionException | InterruptedException | MalformedURLException e) {
final Throwable cause = e.getCause();
if (cause instanceof MsalServiceException) {
final MsalServiceException exception = (MsalServiceException) cause;
if (exception.claims() != null && !exception.claims().isEmpty()) {
throw exception;
}
}
LOGGER.error("acquire on behalf of token for graph api error", e);
} finally {
if (service != null) {
service.shutdown();
}
}
if (result == null) {
throw new ServiceUnavailableException("unable to acquire on-behalf-of token for client " + clientId);
}
return result;
}
private static String getCorrelationId() {
final String uuid = UUID.randomUUID().toString();
return uuid.substring(0, uuid.length() - REQUEST_ID_SUFFIX.length()) + REQUEST_ID_SUFFIX;
}
} | class AzureADGraphClient {
private static final Logger LOGGER = LoggerFactory.getLogger(AzureADGraphClient.class);
private static final SimpleGrantedAuthority DEFAULT_AUTHORITY = new SimpleGrantedAuthority("ROLE_USER");
private static final String DEFAULT_ROLE_PREFIX = "ROLE_";
private static final String MICROSOFT_GRAPH_SCOPE = "https:
private static final String AAD_GRAPH_API_SCOPE = "https:
private static final String REQUEST_ID_SUFFIX = "aadfeed6";
private final String clientId;
private final String clientSecret;
private final ServiceEndpoints serviceEndpoints;
private final AADAuthenticationProperties aadAuthenticationProperties;
private static final String V2_VERSION_ENV_FLAG = "v2-graph";
private boolean aadMicrosoftGraphApiBool;
public AzureADGraphClient(String clientId, String clientSecret, AADAuthenticationProperties aadAuthProps,
ServiceEndpointsProperties serviceEndpointsProps) {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.aadAuthenticationProperties = aadAuthProps;
this.serviceEndpoints = serviceEndpointsProps.getServiceEndpoints(aadAuthProps.getEnvironment());
this.initAADMicrosoftGraphApiBool(aadAuthProps.getEnvironment());
}
private void initAADMicrosoftGraphApiBool(String endpointEnv) {
this.aadMicrosoftGraphApiBool = endpointEnv.contains(V2_VERSION_ENV_FLAG);
}
private String getUserMemberships(String accessToken, String odataNextLink) throws IOException {
final URL url = buildUrl(odataNextLink);
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (this.aadMicrosoftGraphApiBool) {
conn.setRequestMethod(HttpMethod.GET.toString());
conn.setRequestProperty(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", accessToken));
conn.setRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
} else {
conn.setRequestMethod(HttpMethod.GET.toString());
conn.setRequestProperty("api-version", "1.6");
conn.setRequestProperty(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", accessToken));
conn.setRequestProperty(HttpHeaders.ACCEPT, "application/json;odata=minimalmetadata");
}
final String responseInJson = getResponseStringFromConn(conn);
final int responseCode = conn.getResponseCode();
if (responseCode == HTTPResponse.SC_OK) {
return responseInJson;
} else {
throw new IllegalStateException("Response is not "
+ HTTPResponse.SC_OK + ", response json: " + responseInJson);
}
}
private String getSkipTokenFromLink(String odataNextLink) {
String[] parts = odataNextLink.split("/memberOf\\?");
return parts[1];
}
private URL buildUrl(String odataNextLink) throws MalformedURLException {
URL url;
if (odataNextLink != null) {
if (this.aadMicrosoftGraphApiBool) {
url = new URL(odataNextLink);
} else {
String skipToken = getSkipTokenFromLink(odataNextLink);
url = new URL(serviceEndpoints.getAadMembershipRestUri() + "&" + skipToken);
}
} else {
url = new URL(serviceEndpoints.getAadMembershipRestUri());
}
return url;
}
private static String getResponseStringFromConn(HttpURLConnection conn) throws IOException {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
final StringBuilder stringBuffer = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuffer.append(line);
}
return stringBuffer.toString();
}
}
public List<UserGroup> getGroups(String graphApiToken) throws IOException {
return loadUserGroups(graphApiToken);
}
/**
* Checks that the UserGroup has a Group object type.
*
* @param node - json node to look for a key/value to equate against the
* {@link AADAuthenticationProperties.UserGroupProperties}
* @return true if the json node contains the correct key, and expected value to identify a user group.
*/
private boolean isMatchingUserGroupKey(final UserGroup group) {
return group.getObjectType().equals(aadAuthenticationProperties.getUserGroup().getValue());
}
public Set<GrantedAuthority> getGrantedAuthorities(String graphApiToken) throws IOException {
final List<UserGroup> groups = getGroups(graphApiToken);
return convertGroupsToGrantedAuthorities(groups);
}
/**
* Converts UserGroup list to Set of GrantedAuthorities
*
* @param groups user groups
* @return granted authorities
*/
public Set<GrantedAuthority> convertGroupsToGrantedAuthorities(final List<UserGroup> groups) {
final Set<GrantedAuthority> mappedAuthorities = groups.stream().filter(this::isValidUserGroupToGrantAuthority)
.map(userGroup -> new SimpleGrantedAuthority(DEFAULT_ROLE_PREFIX + userGroup.getDisplayName()))
.collect(Collectors.toCollection(LinkedHashSet::new));
if (mappedAuthorities.isEmpty()) {
mappedAuthorities.add(DEFAULT_AUTHORITY);
}
return mappedAuthorities;
}
/**
* Determines if this is a valid {@link UserGroup} to build to a GrantedAuthority.
* <p>
* If the {@link AADAuthenticationProperties.UserGroupProperties
* contains the {@link UserGroup
* true.
*
* @param group - User Group to check if valid to grant an authority to.
* @return true if allowed-groups contains the UserGroup display name
*/
private boolean isValidUserGroupToGrantAuthority(final UserGroup group) {
return aadAuthenticationProperties.getUserGroup().getAllowedGroups().contains(group.getDisplayName());
}
public IAuthenticationResult acquireTokenForGraphApi(String idToken, String tenantId)
throws ServiceUnavailableException {
final IClientCredential clientCredential = ClientCredentialFactory.createFromSecret(clientSecret);
final UserAssertion assertion = new UserAssertion(idToken);
IAuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
final ConfidentialClientApplication application = ConfidentialClientApplication
.builder(clientId, clientCredential)
.authority(serviceEndpoints.getAadSigninUri() + tenantId + "/")
.correlationId(getCorrelationId())
.build();
final Set<String> scopes = new HashSet<>();
scopes.add(aadMicrosoftGraphApiBool ? MICROSOFT_GRAPH_SCOPE : AAD_GRAPH_API_SCOPE);
final OnBehalfOfParameters onBehalfOfParameters = OnBehalfOfParameters
.builder(scopes, assertion)
.build();
final CompletableFuture<IAuthenticationResult> future = application.acquireToken(onBehalfOfParameters);
result = future.get();
} catch (ExecutionException | InterruptedException | MalformedURLException e) {
final Throwable cause = e.getCause();
if (cause instanceof MsalServiceException) {
final MsalServiceException exception = (MsalServiceException) cause;
if (exception.claims() != null && !exception.claims().isEmpty()) {
throw exception;
}
}
LOGGER.error("acquire on behalf of token for graph api error", e);
} finally {
if (service != null) {
service.shutdown();
}
}
if (result == null) {
throw new ServiceUnavailableException("unable to acquire on-behalf-of token for client " + clientId);
}
return result;
}
private static String getCorrelationId() {
final String uuid = UUID.randomUUID().toString();
return uuid.substring(0, uuid.length() - REQUEST_ID_SUFFIX.length()) + REQUEST_ID_SUFFIX;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.