Repository navigation
Expand file tree
/
Copy pathWebPubSubChatCustomization.java
More file actions
171 lines (159 loc) · 9.67 KB
/
Copy pathWebPubSubChatCustomization.java
File metadata and controls
171 lines (159 loc) · 9.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import com.azure.autorest.customization.Customization;
import com.azure.autorest.customization.LibraryCustomization;
import com.azure.autorest.customization.PackageCustomization;
import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import org.slf4j.Logger;
/** Customizes the generated Azure Web PubSub Chat client library. */
public final class WebPubSubChatCustomization extends Customization {
private static final String PACKAGE_NAME = "com.azure.messaging.webpubsub.chat";
@Override
public void customize(LibraryCustomization libraryCustomization, Logger logger) {
PackageCustomization chatPackage = libraryCustomization.getPackage(PACKAGE_NAME);
chatPackage.getClass("WebPubSubChatServiceClientBuilder").customizeAst(ast -> {
ast.getClassByName("WebPubSubChatServiceClientBuilder").ifPresent(builder -> {
if (builder.getImplementedTypes()
.stream()
.noneMatch(type -> type.getNameAsString().equals("AzureKeyCredentialTrait"))) {
builder.addImplementedType("AzureKeyCredentialTrait<WebPubSubChatServiceClientBuilder>");
}
if (builder.getImplementedTypes()
.stream()
.noneMatch(type -> type.getNameAsString().equals("ConnectionStringTrait"))) {
builder.addImplementedType("ConnectionStringTrait<WebPubSubChatServiceClientBuilder>");
}
for (String methodName : new String[] { "buildClient", "buildAsyncClient" }) {
MethodDeclaration method = builder.getMethodsByName(methodName)
.stream()
.findFirst()
.orElseThrow(() -> new IllegalStateException("Missing builder method: " + methodName));
method.setBody(StaticJavaParser.parseBlock(
"{ return new " + method.getTypeAsString() + "(buildInnerClient(), keyCredential); }"));
}
});
});
customizeTokenClient(chatPackage, "WebPubSubChatServiceClient");
customizeTokenClient(chatPackage, "WebPubSubChatServiceAsyncClient");
libraryCustomization.getPackage(PACKAGE_NAME + ".models")
.getClass("MessageContent")
.customizeAst(WebPubSubChatCustomization::customizeMessageContent);
customizeLifecycleDocumentation(libraryCustomization);
removeTrailingJavadocWhitespace(libraryCustomization);
}
static void customizeLifecycleDocumentation(LibraryCustomization libraryCustomization) {
String root = "src/main/java/com/azure/messaging/webpubsub/chat/";
for (String file : new String[] {
"WebPubSubChatServiceClient.java",
"WebPubSubChatServiceAsyncClient.java",
"implementation/WebPubSubChatServiceClientImpl.java" }) {
String path = root + file;
String source = libraryCustomization.getRawEditor().getFileContent(path);
libraryCustomization.getRawEditor().replaceFile(path, correctLifecycleDocumentation(source));
}
}
static String correctLifecycleDocumentation(String source) {
for (MethodDeclaration method : StaticJavaParser.parse(source).findAll(MethodDeclaration.class)) {
if (!method.getJavadocComment().isPresent()) {
continue;
}
String original = method.getJavadocComment().get().getContent();
String corrected = original;
String responseHeading = "<p><strong>Response Body Schema</strong></p>";
int responseStart = corrected.indexOf(responseHeading);
if (responseStart >= 0) {
// Topic state is required on read even though it isn't accepted on create.
corrected = corrected.substring(0, responseStart)
+ corrected.substring(responseStart)
.replace("(Optional, Required on create)", "(Required)")
.replace("state: String(Normal/Archived/SoftDeleted) (Optional)",
"state: String(Normal/Archived/SoftDeleted) (Required)");
}
int requestStart = corrected.indexOf("<p><strong>Request Body Schema</strong></p>");
if (requestStart >= 0) {
if (responseStart < requestStart) {
throw new IllegalStateException("Missing response schema for " + method.getNameAsString());
}
String request = corrected.substring(requestStart, responseStart);
String readOnlyFields;
String name = method.getNameAsString();
if (name.startsWith("updateMessage")) {
readOnlyFields = "id|createdAt|etag";
} else if (name.startsWith("createOrReplaceRole")) {
readOnlyFields = "name|etag";
} else if (name.startsWith("createOrReplaceRoomMember")) {
readOnlyFields = "userId|etag";
} else if (name.startsWith("createOrReplaceRoom")) {
readOnlyFields = "id|defaultConversation|etag";
} else if (name.startsWith("createOrReplaceUser")) {
readOnlyFields = "id|etag";
} else if (name.startsWith("createOrReplaceTopic") || name.startsWith("updateTopic")) {
readOnlyFields = "id|createdAt|createdBy|conversationId|etag";
} else {
throw new IllegalStateException("Unrecognized request schema for " + name);
}
request = request.replaceAll("(?m)^\\h*\\*\\h+(?:" + readOnlyFields + "):[^\\r\\n]*\\R", "");
request = request.replace("(Optional, Required on create)",
name.startsWith("update") ? "(Optional)" : "(Required)");
if (name.startsWith("createOrReplaceTopic")) {
request = request.replaceAll("(state: [^\\r\\n]+)\\(Required\\)", "$1(Optional)");
}
corrected = corrected.substring(0, requestStart) + request + corrected.substring(responseStart);
}
if (method.getNameAsString().startsWith("createOrReplaceTopic")
&& !corrected.contains("When creating a topic, omit state")) {
corrected = corrected.replace("Create or replace a topic.",
"Create or replace a topic.\n *\n"
+ " * <p>When creating a topic, omit state. "
+ "Other states are only valid when replacing an existing topic.</p>");
}
if (!original.equals(corrected)) {
source = source.replace(original, corrected);
}
}
return source;
}
static void customizeMessageContent(CompilationUnit ast) {
// Partial update preserves handwritten members without @Generated, but regenerates removed setters.
ClassOrInterfaceDeclaration model = ast.getClassByName("MessageContent")
.orElseThrow(() -> new IllegalStateException("MessageContent model not found."));
ast.getImports()
.removeIf(
importDeclaration -> importDeclaration.getNameAsString().equals("com.azure.core.annotation.Fluent")
|| importDeclaration.getNameAsString().equals("java.util.HashSet")
|| importDeclaration.getNameAsString().equals("java.util.Set"));
ast.addImport("com.azure.core.annotation.Immutable");
model.getAnnotations().removeIf(annotation -> annotation.getNameAsString().equals("Fluent"));
if (!model.getAnnotationByName("Immutable").isPresent()) {
model.addMarkerAnnotation("Immutable");
}
model.setJavadocComment("Message content containing exactly one of text or binary data.\n"
+ "Use {@link #fromText(String)} or {@link #fromBinary(byte[])} to create content.\n"
+ "The getter for the unselected representation returns {@code null}.");
model.getFieldByName("updatedProperties").ifPresent(field -> field.remove());
model.getMethodsByName("setText").forEach(method -> method.remove());
model.getMethodsByName("setBinary").forEach(method -> method.remove());
model.getMethodsByName("toJsonMergePatch").forEach(method -> method.remove());
}
private static void customizeTokenClient(PackageCustomization chatPackage, String className) {
chatPackage.getClass(className).customizeAst(ast -> {
ast.getImports()
.removeIf(importDeclaration -> importDeclaration.getNameAsString()
.equals("com.azure.messaging.webpubsub.chat.implementation.models.GenerateClientTokenResponse"));
ast.getClassByName(className).ifPresent(client -> {
client.getMethodsByName("generateClientToken").forEach(method -> method.remove());
client.getMethodsByName("generateClientTokenWithResponse").forEach(method -> method.remove());
});
});
}
private static void removeTrailingJavadocWhitespace(LibraryCustomization libraryCustomization) {
String path
= "src/main/java/com/azure/messaging/webpubsub/chat/implementation/WebPubSubChatServiceClientImpl.java";
String implementation = libraryCustomization.getRawEditor().getFileContent(path);
libraryCustomization.getRawEditor()
.replaceFile(path, implementation.replace("* \r\n", "*\r\n").replace("* \n", "*\n"));
}
}