Java Http client generator: generate tests (#4251)

This commit is contained in:
Srikanta 2024-08-27 00:31:07 -07:00 коммит произвёл GitHub
Родитель 9e37021186
Коммит 7600a2bb58
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: B5690EEEBB952194
2228 изменённых файлов: 321393 добавлений и 11688 удалений

Просмотреть файл

@ -62,3 +62,6 @@ grammars/
# auto generated code model files
packages/http-client-csharp/generator/TestProjects/**/tspCodeModel.json
# auto generated api view properties files
packages/http-client-java/generator/http-client-generator-test/src/main/**/*.json

Просмотреть файл

@ -27,6 +27,7 @@ words:
- cobertura
- codehaus
- codeql
- collisons
- Contoso
- CORGE
- createsorreplacesresource
@ -74,6 +75,7 @@ words:
- LINUXNEXTVMIMAGE
- LINUXOS
- LINUXVMIMAGE
- lropaging
- lzutf
- MACVMIMAGE
- mgmt
@ -123,9 +125,9 @@ words:
- sint
- snakeyaml
- srnagar
- statment
- sses
- ssvs
- statment
- strs
- syncpack
- TCGC
@ -178,6 +180,7 @@ ignorePaths:
- common/scripts/*
- "**/ThirdPartyNotices.txt"
- packages/compiler/test/formatter/scenarios/**
- packages/http-client-java/generator/http-client-generator-test/**
- pnpm-lock.yaml
- "**/*.mp4"
- .git/**

Просмотреть файл

@ -11,5 +11,5 @@ if ($RebuildJar) {
# re-build http-client-java
npm install
npm run clean && npm run build:emitter
npm run clean && npm run build

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -52,3 +52,7 @@ export class ServiceVersion extends Metadata {
export interface CrossLanguageDefinition {
crossLanguageDefinitionId?: string;
}
export interface EncodedSchema {
encode?: string;
}

Просмотреть файл

@ -29,7 +29,6 @@ export interface EmitterOptions {
"generate-samples"?: boolean;
"generate-tests"?: boolean;
"examples-directory"?: string;
"enable-sync-stack"?: boolean;
"stream-style-serialization"?: boolean;
@ -80,7 +79,6 @@ const EmitterOptionsSchema: JSONSchemaType<EmitterOptions> = {
// sample and test
"generate-samples": { type: "boolean", nullable: true, default: true },
"generate-tests": { type: "boolean", nullable: true, default: true },
"examples-directory": { type: "string", nullable: true },
"enable-sync-stack": { type: "boolean", nullable: true, default: true },
"stream-style-serialization": { type: "boolean", nullable: true, default: true },

Просмотреть файл

@ -15,7 +15,7 @@ import {
SdkType,
} from "@azure-tools/typespec-client-generator-core";
import { CrossLanguageDefinition } from "./common/client.js";
import { getJavaNamespace, getNamespace, pascalCase } from "./utils.js";
import { getNamespace, pascalCase } from "./utils.js";
/*
* These schema need to reflect
@ -142,7 +142,12 @@ export function createPollOperationDetailsSchema(
const fileDetailsMap: Map<string, ObjectSchema> = new Map();
function getFileSchemaName(baseName: string) {
function getFileSchemaName(baseName: string, sdkModelType?: SdkModelType): string {
// If the TypeSpec Model exists and is not TypeSpec.Http.File, directly use its name
if (sdkModelType && sdkModelType.crossLanguageDefinitionId !== "TypeSpec.Http.File") {
return baseName;
}
// make sure suffix "FileDetails"
if (baseName.toLocaleLowerCase().endsWith("filedetails")) {
return pascalCase(baseName);
@ -157,6 +162,7 @@ function createFileDetailsSchema(
schemaName: string,
propertyName: string,
namespace: string,
javaNamespace: string | undefined,
schemas: Schemas
) {
const fileDetailsSchema = new ObjectSchema(
@ -168,7 +174,7 @@ function createFileDetailsSchema(
namespace: namespace,
},
java: {
namespace: getJavaNamespace(namespace),
namespace: javaNamespace,
},
},
serializationFormats: [KnownMediaType.Multipart],
@ -238,6 +244,7 @@ function addContentTypeProperty(
export function getFileDetailsSchema(
property: SdkBodyModelPropertyType,
namespace: string,
javaNamespace: string | undefined,
schemas: Schemas,
binarySchema: BinarySchema,
stringSchema: StringSchema,
@ -262,7 +269,7 @@ export function getFileDetailsSchema(
*/
const filePropertyName = property.name;
const fileSchemaName = fileSdkType.name;
const schemaName = getFileSchemaName(fileSchemaName);
const schemaName = getFileSchemaName(fileSchemaName, fileSdkType);
let fileDetailsSchema = fileDetailsMap.get(schemaName);
if (!fileDetailsSchema) {
const typeNamespace = getNamespace(property.type.__raw) ?? namespace;
@ -270,6 +277,7 @@ export function getFileDetailsSchema(
schemaName,
filePropertyName,
typeNamespace,
javaNamespace,
schemas
);
@ -316,7 +324,13 @@ export function getFileDetailsSchema(
const schemaName = getFileSchemaName(filePropertyName);
let fileDetailsSchema = fileDetailsMap.get(schemaName);
if (!fileDetailsSchema) {
fileDetailsSchema = createFileDetailsSchema(schemaName, filePropertyName, namespace, schemas);
fileDetailsSchema = createFileDetailsSchema(
schemaName,
filePropertyName,
namespace,
javaNamespace,
schemas
);
addContentProperty(fileDetailsSchema, binarySchema);
addFilenameProperty(fileDetailsSchema, stringSchema);

Просмотреть файл

@ -1,5 +1,6 @@
import { Parameter } from "@autorest/codemodel";
import { LroMetadata } from "@azure-tools/typespec-azure-core";
import { SdkHttpOperation } from "@azure-tools/typespec-client-generator-core";
import { ModelProperty, Operation, Program, Type, Union } from "@typespec/compiler";
import {
HttpOperation,
@ -23,7 +24,7 @@ export const SPECIAL_HEADER_NAMES = new Set([
export const ORIGIN_API_VERSION = "modelerfour:synthesized/api-version";
const CONTENT_TYPE_KEY = "content-type";
export const CONTENT_TYPE_KEY = "content-type";
// azure-core SerializerEncoding.SUPPORTED_MIME_TYPES
const SUPPORTED_MIME_TYPES = new Set<string>([
@ -47,18 +48,18 @@ export function isKnownContentType(contentTypes: string[]): boolean {
});
}
export function operationIsJsonMergePatch(op: HttpOperation): boolean {
export function operationIsJsonMergePatch(op: SdkHttpOperation): boolean {
return operationIsContentType(op, "application/merge-patch+json");
}
export function operationIsMultipart(op: HttpOperation): boolean {
export function operationIsMultipart(op: SdkHttpOperation): boolean {
return operationIsContentType(op, "multipart/form-data");
}
function operationIsContentType(op: HttpOperation, contentType: string): boolean {
for (const param of op.parameters.parameters) {
if (param.type === "header" && param.name.toLowerCase() === CONTENT_TYPE_KEY) {
if (param.param.type.kind === "String" && param.param.type.value === contentType) {
function operationIsContentType(op: SdkHttpOperation, contentType: string): boolean {
for (const param of op.parameters) {
if (param.kind === "header" && param.serializedName.toLowerCase() === CONTENT_TYPE_KEY) {
if (param.type.kind === "constant" && param.type.value === contentType) {
return true;
}
}
@ -66,14 +67,14 @@ function operationIsContentType(op: HttpOperation, contentType: string): boolean
return false;
}
export function operationIsMultipleContentTypes(op: HttpOperation): boolean {
export function operationIsMultipleContentTypes(op: SdkHttpOperation): boolean {
if (
op.parameters.parameters &&
op.parameters.parameters.some(
op.parameters &&
op.parameters.some(
(parameter) =>
parameter?.type === "header" &&
parameter?.name?.toLowerCase() === CONTENT_TYPE_KEY &&
parameter?.param?.type?.kind === "Union"
parameter.kind === "header" &&
parameter.serializedName.toLowerCase() === CONTENT_TYPE_KEY &&
parameter.type.kind === "enum"
)
) {
return true;

Просмотреть файл

@ -96,7 +96,7 @@ export class PreNamer {
const deduplicateSchemaNames =
!!this.options["lenient-model-deduplication"] ||
!!this.options["resolve-schema-name-collisions"];
!!this.options["resolve-schema-name-collisons"];
const scopeNamer = new ScopeNamer({
deduplicateNames: deduplicateSchemaNames,

Просмотреть файл

@ -9,7 +9,6 @@ import {
import {
DecoratedType,
DecoratorApplication,
EncodeData,
EnumMember,
IntrinsicScalarName,
Model,
@ -27,7 +26,6 @@ import {
isTemplateInstance,
isTypeSpecValueTypeOf,
} from "@typespec/compiler";
import { Version } from "@typespec/versioning";
import { DurationSchema } from "./common/schemas/time.js";
import { getNamespace } from "./utils.js";
@ -56,8 +54,8 @@ export class ProcessingCache<In, Out> {
}
}
export function isStable(version: Version): boolean {
return !version.value.toLowerCase().includes("preview");
export function isStable(version: string): boolean {
return !version.toLowerCase().includes("preview");
}
/** adds only if the item is not in the collection already
@ -120,24 +118,6 @@ export function getDefaultValue(value: Value | undefined): any {
return undefined;
}
export function getDurationFormat(encode: EncodeData): DurationSchema["format"] {
let format: DurationSchema["format"] = "duration-rfc3339";
// duration encoded as seconds
if (encode.encoding === "seconds") {
const scalarName = encode.type.name;
if (scalarName.startsWith("int") || scalarName.startsWith("uint") || scalarName === "safeint") {
format = "seconds-integer";
} else if (scalarName.startsWith("float")) {
format = "seconds-number";
} else {
throw new Error(
`Unrecognized scalar type used by duration encoded as seconds: '${scalarName}'.`
);
}
}
return format;
}
export function getDurationFormatFromSdkType(type: SdkDurationType): DurationSchema["format"] {
let format: DurationSchema["format"] = "duration-rfc3339";
// duration encoded as seconds

Просмотреть файл

@ -42,12 +42,13 @@ export function getNamespace(type: Type | undefined): string | undefined {
}
}
export function getJavaNamespace(namespace: string | undefined): string | undefined {
return namespace ? "com." + namespace.toLowerCase() : undefined;
}
export function stringArrayContainsIgnoreCase(stringList: string[], str: string): boolean {
return stringList && str
? stringList.findIndex((s) => s.toLowerCase() === str.toLowerCase()) !== -1
: false;
}
export function removeClientSuffix(clientName: string): string {
const clientSuffix = "Client";
return clientName.endsWith(clientSuffix) ? clientName.slice(0, -clientSuffix.length) : clientName;
}

Просмотреть файл

@ -18,4 +18,7 @@ Invoke "npm run build:emitter"
$testDir = Join-Path $repoRoot 'test'
Invoke "npx tsp compile $testDir/literal.tsp --trace @typespec/http-client-java --emit @typespec/http-client-java --option @typespec/http-client-java.emitter-output-dir=$testDir/tsp-output --option @typespec/http-client-java.save-inputs=true"
$generatorTestDir = Join-Path $repoRoot 'generator/http-client-generator-test'
Set-Location $generatorTestDir
./Generate.ps1
Set-Location $PSScriptRoot

Просмотреть файл

@ -6,7 +6,8 @@ param(
[string] $Filter = "."
)
$ErrorActionPreference = 'Stop'
$ErrorActionPreference = 'Continue'
Set-StrictMode -Version 3.0
$packageRoot = (Resolve-Path "$PSScriptRoot/../..").Path.Replace('\', '/')
. "$packageRoot/../../eng/emitters/scripts/CommandInvocation-Helpers.ps1"
@ -45,14 +46,14 @@ try {
& "$packageRoot/eng/scripts/Generate.ps1"
Write-Host 'Code generation is completed.'
# try {
# Write-Host 'Checking for differences in generated code...'
# & "$packageRoot/eng/scripts/Check-GitChanges.ps1"
# Write-Host 'Done. No code generation differences detected.'
# }
# catch {
# Write-Error 'Generated code is not up to date. Please run: eng/Generate.ps1'
# }
try {
Write-Host 'Checking for differences in generated code...'
& "$packageRoot/eng/scripts/Check-GitChanges.ps1"
Write-Host 'Done. No code generation differences detected.'
}
catch {
Write-Error 'Generated code is not up to date. Please run: eng/Generate.ps1'
}
}
}
finally {

Просмотреть файл

@ -44,7 +44,6 @@
<artifactId>slf4j-api</artifactId>
<version>1.7.36</version>
</dependency>
<dependency>
<groupId>com.github.javaparser</groupId>
<artifactId>javaparser-core</artifactId>

Просмотреть файл

@ -13,167 +13,189 @@ import java.io.IOException;
* Represents a Number value.
*/
public class NumberSchema extends PrimitiveSchema {
private double precision;
private double multipleOf;
private double maximum;
private boolean exclusiveMaximum;
private double minimum;
private boolean exclusiveMinimum;
private double precision;
private double multipleOf;
private double maximum;
private boolean exclusiveMaximum;
private double minimum;
private boolean exclusiveMinimum;
private String encode;
/**
* Creates a new instance of the NumberSchema class.
*/
public NumberSchema() {
}
/**
* Creates a new instance of the NumberSchema class.
*/
public NumberSchema() {
}
/**
* The precision of the number. (Required)
*
* @return The precision of the number.
*/
public double getPrecision() {
return precision;
}
/**
* The precision of the number. (Required)
*
* @return The precision of the number.
*/
public double getPrecision() {
return precision;
}
/**
* Sets the precision of the number. (Required)
*
* @param precision The precision of the number.
*/
public void setPrecision(double precision) {
this.precision = precision;
}
/**
* Sets the precision of the number. (Required)
*
* @param precision The precision of the number.
*/
public void setPrecision(double precision) {
this.precision = precision;
}
/**
* Gets the multiple of this number must be, if set.
*
* @return The multiple of this number must be, if set.
*/
public double getMultipleOf() {
return multipleOf;
}
/**
* Gets the multiple of this number must be, if set.
*
* @return The multiple of this number must be, if set.
*/
public double getMultipleOf() {
return multipleOf;
}
/**
* Sets the multiple of this number must be, if set.
*
* @param multipleOf The multiple of this number must be, if set.
*/
public void setMultipleOf(double multipleOf) {
this.multipleOf = multipleOf;
}
/**
* Sets the multiple of this number must be, if set.
*
* @param multipleOf The multiple of this number must be, if set.
*/
public void setMultipleOf(double multipleOf) {
this.multipleOf = multipleOf;
}
/**
* Gets the maximum value, if set.
*
* @return The maximum value, if set.
*/
public double getMaximum() {
return maximum;
}
/**
* Gets the maximum value, if set.
*
* @return The maximum value, if set.
*/
public double getMaximum() {
return maximum;
}
/**
* Sets the maximum value, if set.
*
* @param maximum The maximum value, if set.
*/
public void setMaximum(double maximum) {
this.maximum = maximum;
}
/**
* Sets the maximum value, if set.
*
* @param maximum The maximum value, if set.
*/
public void setMaximum(double maximum) {
this.maximum = maximum;
}
/**
* Gets whether the maximum value is exclusive.
*
* @return Whether the maximum value is exclusive.
*/
public boolean isExclusiveMaximum() {
return exclusiveMaximum;
}
/**
* Gets whether the maximum value is exclusive.
*
* @return Whether the maximum value is exclusive.
*/
public boolean isExclusiveMaximum() {
return exclusiveMaximum;
}
/**
* Sets whether the maximum value is exclusive.
*
* @param exclusiveMaximum Whether the maximum value is exclusive.
*/
public void setExclusiveMaximum(boolean exclusiveMaximum) {
this.exclusiveMaximum = exclusiveMaximum;
}
/**
* Sets whether the maximum value is exclusive.
*
* @param exclusiveMaximum Whether the maximum value is exclusive.
*/
public void setExclusiveMaximum(boolean exclusiveMaximum) {
this.exclusiveMaximum = exclusiveMaximum;
}
/**
* Gets the minimum value, if set.
*
* @return The minimum value, if set.
*/
public double getMinimum() {
return minimum;
}
/**
* Gets the minimum value, if set.
*
* @return The minimum value, if set.
*/
public double getMinimum() {
return minimum;
}
/**
* Sets the minimum value, if set.
*
* @param minimum The minimum value, if set.
*/
public void setMinimum(double minimum) {
this.minimum = minimum;
}
/**
* Sets the minimum value, if set.
*
* @param minimum The minimum value, if set.
*/
public void setMinimum(double minimum) {
this.minimum = minimum;
}
/**
* Gets whether the minimum value is exclusive.
*
* @return Whether the minimum value is exclusive.
*/
public boolean isExclusiveMinimum() {
return exclusiveMinimum;
}
/**
* Gets whether the minimum value is exclusive.
*
* @return Whether the minimum value is exclusive.
*/
public boolean isExclusiveMinimum() {
return exclusiveMinimum;
}
/**
* Sets whether the minimum value is exclusive.
*
* @param exclusiveMinimum Whether the minimum value is exclusive.
*/
public void setExclusiveMinimum(boolean exclusiveMinimum) {
this.exclusiveMinimum = exclusiveMinimum;
}
/**
* Sets whether the minimum value is exclusive.
*
* @param exclusiveMinimum Whether the minimum value is exclusive.
*/
public void setExclusiveMinimum(boolean exclusiveMinimum) {
this.exclusiveMinimum = exclusiveMinimum;
}
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
return super.writeParentProperties(jsonWriter.writeStartObject())
.writeDoubleField("precision", precision)
.writeDoubleField("multipleOf", multipleOf)
.writeDoubleField("maximum", maximum)
.writeBooleanField("exclusiveMaximum", exclusiveMaximum)
.writeDoubleField("minimum", minimum)
.writeBooleanField("exclusiveMinimum", exclusiveMinimum)
.writeEndObject();
}
/**
* Gets the encode for the number.
*
* @return the encode for the number.
*/
public String getEncode() {
return encode;
}
/**
* Deserializes a NumberSchema instance from the JSON data.
*
* @param jsonReader The JSON reader to deserialize from.
* @return A NumberSchema instance deserialized from the JSON data.
* @throws IOException If an error occurs during deserialization.
*/
public static NumberSchema fromJson(JsonReader jsonReader) throws IOException {
return JsonUtils.readObject(jsonReader, NumberSchema::new, (schema, fieldName, reader) -> {
if (schema.tryConsumeParentProperties(schema, fieldName, reader)) {
return;
}
/**
* Sets the encode for the number. Currently only "string" is supported.
*
* @param encode the encode for the number.
*/
public void setEncode(String encode) {
this.encode = encode;
}
if ("precision".equals(fieldName)) {
schema.precision = reader.getDouble();
} else if ("multipleOf".equals(fieldName)) {
schema.multipleOf = reader.getDouble();
} else if ("maximum".equals(fieldName)) {
schema.maximum = reader.getDouble();
} else if ("exclusiveMaximum".equals(fieldName)) {
schema.exclusiveMaximum = reader.getBoolean();
} else if ("minimum".equals(fieldName)) {
schema.minimum = reader.getDouble();
} else if ("exclusiveMinimum".equals(fieldName)) {
schema.exclusiveMinimum = reader.getBoolean();
} else {
reader.skipChildren();
}
});
}
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
return super.writeParentProperties(jsonWriter.writeStartObject())
.writeDoubleField("precision", precision)
.writeDoubleField("multipleOf", multipleOf)
.writeDoubleField("maximum", maximum)
.writeBooleanField("exclusiveMaximum", exclusiveMaximum)
.writeDoubleField("minimum", minimum)
.writeBooleanField("exclusiveMinimum", exclusiveMinimum)
.writeStringField("encode", encode)
.writeEndObject();
}
/**
* Deserializes a NumberSchema instance from the JSON data.
*
* @param jsonReader The JSON reader to deserialize from.
* @return A NumberSchema instance deserialized from the JSON data.
* @throws IOException If an error occurs during deserialization.
*/
public static NumberSchema fromJson(JsonReader jsonReader) throws IOException {
return JsonUtils.readObject(jsonReader, NumberSchema::new, (schema, fieldName, reader) -> {
if (schema.tryConsumeParentProperties(schema, fieldName, reader)) {
return;
}
if ("precision".equals(fieldName)) {
schema.precision = reader.getDouble();
} else if ("multipleOf".equals(fieldName)) {
schema.multipleOf = reader.getDouble();
} else if ("maximum".equals(fieldName)) {
schema.maximum = reader.getDouble();
} else if ("exclusiveMaximum".equals(fieldName)) {
schema.exclusiveMaximum = reader.getBoolean();
} else if ("minimum".equals(fieldName)) {
schema.minimum = reader.getDouble();
} else if ("exclusiveMinimum".equals(fieldName)) {
schema.exclusiveMinimum = reader.getBoolean();
} else if ("encode".equals(fieldName)) {
schema.encode = reader.getString();
} else {
reader.skipChildren();
}
});
}
}

Просмотреть файл

@ -0,0 +1,163 @@
package com.microsoft.typespec.http.client.generator.core.implementation;
import com.microsoft.typespec.http.client.generator.core.extension.plugin.JavaSettings;
import com.microsoft.typespec.http.client.generator.core.model.clientmodel.ClientModel;
import com.microsoft.typespec.http.client.generator.core.model.clientmodel.ClientModelProperty;
import com.microsoft.typespec.http.client.generator.core.model.clientmodel.IType;
import com.microsoft.typespec.http.client.generator.core.model.javamodel.JavaBlock;
import com.microsoft.typespec.http.client.generator.core.model.javamodel.JavaClass;
import com.microsoft.typespec.http.client.generator.core.model.javamodel.JavaFile;
import com.microsoft.typespec.http.client.generator.core.model.javamodel.JavaVisibility;
import com.microsoft.typespec.http.client.generator.core.util.ClientModelUtil;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* This class handles generating code for polymorphic discriminators.
* <p>
* This class exists to contain all logic for polymorphic discriminators in one location rather that having repetitive
* logic in multiple places.
*/
public final class PolymorphicDiscriminatorHandler {
public static void addAnnotationToField(ClientModel model, JavaFile javaFile, JavaSettings settings) {
if (!model.isPolymorphic() || settings.isStreamStyleSerialization()) {
return;
}
// After removing the concept of passing discriminator to children models and always doing it, there is no need
// to set the 'include' property of the JsonTypeInfo annotation. We use 'JsonTypeInfo.As.PROPERTY' as the value,
// which is the default value, so it doesn't need to be declared.
// And to support unknown subtypes, we always set a default implementation to the class being generated.
// And the discriminator is passed to child models, so the discriminator property needs to be set to visible.
String jsonTypeInfo = "JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = \""
+ model.getPolymorphicDiscriminatorName() + "\", defaultImpl = " + model.getName()
+ ".class, visible = true)";
javaFile.annotation(jsonTypeInfo);
javaFile.annotation("JsonTypeName(\"" + model.getSerializedName() + "\")");
if (!model.getDerivedModels().isEmpty()) {
javaFile.line("@JsonSubTypes({");
javaFile.indent(() -> {
Function<ClientModel, String> getDerivedTypeAnnotation = derivedType -> "@JsonSubTypes.Type(name = \""
+ derivedType.getSerializedName() + "\", value = " + derivedType.getName() + ".class)";
for (int i = 0; i != model.getDerivedModels().size() - 1; i++) {
ClientModel derivedModel = model.getDerivedModels().get(i);
javaFile.line(getDerivedTypeAnnotation.apply(derivedModel) + ',');
}
javaFile.line(getDerivedTypeAnnotation.apply(model.getDerivedModels()
.get(model.getDerivedModels().size() - 1)));
});
javaFile.line("})");
}
}
public static void declareField(ClientModel model, JavaClass classBlock, Consumer<JavaClass> addGeneratedAnnotation,
Consumer<ClientModelProperty> addFieldAnnotations, JavaSettings settings) {
if (!model.isPolymorphic()) {
return;
}
for (ClientModelProperty discriminator : model.getParentPolymorphicDiscriminators()) {
declareFieldInternal(discriminator, model, false, classBlock, addGeneratedAnnotation, addFieldAnnotations,
settings);
}
declareFieldInternal(model.getPolymorphicDiscriminator(), model,
ClientModelUtil.modelDefinesProperty(model, model.getPolymorphicDiscriminator()), classBlock,
addGeneratedAnnotation, addFieldAnnotations, settings);
}
private static void declareFieldInternal(ClientModelProperty discriminator, ClientModel model,
boolean discriminatorDefinedByModel, JavaClass classBlock, Consumer<JavaClass> addGeneratedAnnotation,
Consumer<ClientModelProperty> addFieldAnnotations, JavaSettings settings) {
boolean allPolymorphicModelsInSamePackage = model.isAllPolymorphicModelsInSamePackage();
boolean discriminatorUsedInConstructor = ClientModelUtil.includePropertyInConstructor(discriminator, settings);
String propertyName = discriminator.getName();
IType propertyType = discriminator.getWireType();
String discriminatorValue = (discriminator.getDefaultValue() == null)
? discriminator.getClientType().defaultValueExpression(model.getSerializedName())
: discriminator.getDefaultValue();
// Only set the property to a default value if the property isn't included in the constructor.
// There can be cases with polymorphic discriminators where they have both a default value and are
// required, in which case the default value will be set in the constructor.
boolean discriminatorFieldIsInitialized = (!discriminatorUsedInConstructor || discriminator.isConstant())
&& (discriminatorValue != null && !allPolymorphicModelsInSamePackage);
String fieldSignature = discriminatorFieldIsInitialized
? propertyType + " " + propertyName + " = " + discriminatorValue
: propertyType + " " + propertyName;
boolean generateCommentAndAnnotations = discriminatorUsedInConstructor
|| (allPolymorphicModelsInSamePackage && discriminatorDefinedByModel)
|| !allPolymorphicModelsInSamePackage;
if (generateCommentAndAnnotations) {
classBlock.blockComment(comment -> comment.line(discriminator.getDescription()));
addGeneratedAnnotation.accept(classBlock);
addFieldAnnotations.accept(discriminator);
}
if (discriminatorUsedInConstructor) {
classBlock.privateFinalMemberVariable(fieldSignature);
} else {
// If the model defines the discriminator and all models in the polymorphic hierarchy are in the same
// package, make it package-private to allow derived models to access it.
if (allPolymorphicModelsInSamePackage && discriminatorDefinedByModel) {
classBlock.memberVariable(JavaVisibility.PackagePrivate, fieldSignature);
} else if (!allPolymorphicModelsInSamePackage) {
classBlock.privateMemberVariable(fieldSignature);
}
}
}
public static void initializeInConstructor(ClientModel model, JavaBlock constructor, JavaSettings settings) {
if (!model.isPolymorphic()) {
return;
}
// Polymorphic models are contained in different packages, so the discriminator value was set in the field
// declaration.
if (!model.isAllPolymorphicModelsInSamePackage()) {
return;
}
for (ClientModelProperty discriminator : model.getParentPolymorphicDiscriminators()) {
initializeInConstructorInternal(discriminator, model, constructor, settings);
}
initializeInConstructorInternal(model.getPolymorphicDiscriminator(), model, constructor, settings);
}
private static void initializeInConstructorInternal(ClientModelProperty discriminator, ClientModel model,
JavaBlock constructor, JavaSettings settings) {
// When the polymorphic discriminator is used in the constructor it will be initialized by the constructor.
if (ClientModelUtil.includePropertyInConstructor(discriminator, settings)) {
return;
}
String discriminatorValue = (discriminator.getDefaultValue() == null)
? discriminator.getClientType().defaultValueExpression(model.getSerializedName())
: discriminator.getDefaultValue();
constructor.line("this." + discriminator.getName() + " = " + discriminatorValue + ";");
}
/**
* Determines whether a getter method should be generated for the discriminator property.
*
* @return Whether a getter method should be generated for the discriminator property.
*/
public static boolean generateGetter(ClientModel model, ClientModelProperty discriminator) {
// If all the polymorphic models aren't in the same package the getter for the discriminator value will be
// generated for each model as each model defines properties for all discriminators.
if (!model.isAllPolymorphicModelsInSamePackage()) {
return true;
}
// If all polymorphic models are in the same package, only the declaring model needs to generate the getter.
return ClientModelUtil.modelDefinesProperty(model, discriminator);
}
}

Просмотреть файл

@ -18,101 +18,101 @@ import java.util.HashMap;
import java.util.Map;
public class PrimitiveMapper implements IMapper<PrimitiveSchema, IType> {
private static final PrimitiveMapper INSTANCE = new PrimitiveMapper();
protected Map<PrimitiveSchema, IType> parsed = new HashMap<>();
private static final PrimitiveMapper INSTANCE = new PrimitiveMapper();
protected Map<PrimitiveSchema, IType> parsed = new HashMap<>();
protected PrimitiveMapper() {
protected PrimitiveMapper() {
}
public static PrimitiveMapper getInstance() {
return INSTANCE;
}
@Override
public IType map(PrimitiveSchema primaryType) {
if (primaryType == null) {
return null;
}
public static PrimitiveMapper getInstance() {
return INSTANCE;
}
return parsed.computeIfAbsent(primaryType, this::createPrimitiveType);
}
@Override
public IType map(PrimitiveSchema primaryType) {
if (primaryType == null) {
return null;
}
/**
* Extension.
*
* @param primaryType the primitive schema.
* @return the client model type.
*/
protected IType createPrimitiveType(PrimitiveSchema primaryType) {
boolean isLowLevelClient = JavaSettings.getInstance().isDataPlaneClient();
boolean urlAsString = JavaSettings.getInstance().urlAsString();
boolean uuidAsString = JavaSettings.getInstance().uuidAsString();
return parsed.computeIfAbsent(primaryType, this::createPrimitiveType);
}
/**
* Extension.
*
* @param primaryType the primitive schema.
* @return the client model type.
*/
protected IType createPrimitiveType(PrimitiveSchema primaryType) {
boolean isLowLevelClient = JavaSettings.getInstance().isDataPlaneClient();
boolean urlAsString = JavaSettings.getInstance().urlAsString();
boolean uuidAsString = JavaSettings.getInstance().uuidAsString();
switch (primaryType.getType()) {
switch (primaryType.getType()) {
// case null:
// iType = PrimitiveType.Void;
// break;
case BOOLEAN: return PrimitiveType.BOOLEAN;
case BYTE_ARRAY:
ByteArraySchema byteArraySchema = (ByteArraySchema) primaryType;
return (byteArraySchema.getFormat() == ByteArraySchema.Format.BASE_64_URL)
? ClassType.BASE_64_URL
: ArrayType.BYTE_ARRAY;
case CHAR: return PrimitiveType.CHAR;
case DATE: return isLowLevelClient ? ClassType.STRING : ClassType.LOCAL_DATE;
case DATE_TIME:
DateTimeSchema dateTimeSchema = (DateTimeSchema) primaryType;
return (dateTimeSchema.getFormat() == DateTimeSchema.Format.DATE_TIME_RFC_1123)
? ClassType.DATE_TIME_RFC_1123
: ClassType.DATE_TIME;
case TIME:
case BOOLEAN: return PrimitiveType.BOOLEAN;
case BYTE_ARRAY:
ByteArraySchema byteArraySchema = (ByteArraySchema) primaryType;
return (byteArraySchema.getFormat() == ByteArraySchema.Format.BASE_64_URL)
? ClassType.BASE_64_URL
: ArrayType.BYTE_ARRAY;
case CHAR: return PrimitiveType.CHAR;
case DATE: return isLowLevelClient ? ClassType.STRING : ClassType.LOCAL_DATE;
case DATE_TIME:
DateTimeSchema dateTimeSchema = (DateTimeSchema) primaryType;
return (dateTimeSchema.getFormat() == DateTimeSchema.Format.DATE_TIME_RFC_1123)
? ClassType.DATE_TIME_RFC_1123
: ClassType.DATE_TIME;
case TIME:
// TimeSchema timeSchema = (TimeSchema) primaryType;
return ClassType.STRING;
return ClassType.STRING;
// case KnownPrimaryType.DateTimeRfc1123:
// iType = ClassType.DateTimeRfc1123;
// break;
case NUMBER:
NumberSchema numberSchema = (NumberSchema) primaryType;
if (numberSchema.getPrecision() == 64) {
return PrimitiveType.DOUBLE;
} else if (numberSchema.getPrecision() == 32) {
return PrimitiveType.FLOAT;
} else {
return ClassType.BIG_DECIMAL;
}
case INTEGER:
NumberSchema intSchema = (NumberSchema) primaryType;
return (intSchema.getPrecision() == 64)
? PrimitiveType.LONG
: PrimitiveType.INT;
// case KnownPrimaryType.Long:
// iType = PrimitiveType.Long;
// break;
// case KnownPrimaryType.Stream:
// iType = GenericType.FluxByteBuffer;
// break;
case STRING: return ClassType.STRING;
case ARM_ID: return ClassType.STRING;
case URI: return isLowLevelClient || urlAsString ? ClassType.STRING : ClassType.URL;
case DURATION:
DurationSchema durationSchema = (DurationSchema) primaryType;
IType durationType = ClassType.DURATION;
if (durationSchema.getFormat() != null) {
switch (durationSchema.getFormat()) {
case SECONDS_INTEGER:
return PrimitiveType.DURATION_LONG;
case SECONDS_NUMBER:
return PrimitiveType.DURATION_DOUBLE;
}
}
return durationType;
case UNIXTIME: return isLowLevelClient ? PrimitiveType.LONG : PrimitiveType.UNIX_TIME_LONG;
case UUID: return isLowLevelClient || uuidAsString ? ClassType.STRING : ClassType.UUID;
case OBJECT: return ClassType.OBJECT;
case CREDENTIAL: return ClassType.TOKEN_CREDENTIAL;
default:
throw new UnsupportedOperationException(String.format("Unrecognized AutoRest Primitive Type: %s",
primaryType.getType()));
case NUMBER:
NumberSchema numberSchema = (NumberSchema) primaryType;
if (numberSchema.getPrecision() == 64) {
return PrimitiveType.DOUBLE;
} else if (numberSchema.getPrecision() == 32) {
return PrimitiveType.FLOAT;
} else {
return ClassType.BIG_DECIMAL;
}
case INTEGER:
NumberSchema intSchema = (NumberSchema) primaryType;
if ("string".equals(intSchema.getEncode())) {
return (intSchema.getPrecision() == 64)
? PrimitiveType.LONG_AS_STRING
: PrimitiveType.INT_AS_STRING;
} else {
return (intSchema.getPrecision() == 64)
? PrimitiveType.LONG
: PrimitiveType.INT;
}
case STRING: return ClassType.STRING;
case ARM_ID: return ClassType.STRING;
case URI: return isLowLevelClient || urlAsString ? ClassType.STRING : ClassType.URL;
case DURATION:
DurationSchema durationSchema = (DurationSchema) primaryType;
IType durationType = ClassType.DURATION;
if (durationSchema.getFormat() != null) {
switch (durationSchema.getFormat()) {
case SECONDS_INTEGER:
return PrimitiveType.DURATION_LONG;
case SECONDS_NUMBER:
return PrimitiveType.DURATION_DOUBLE;
}
}
return durationType;
case UNIXTIME: return isLowLevelClient ? PrimitiveType.LONG : PrimitiveType.UNIX_TIME_LONG;
case UUID: return isLowLevelClient || uuidAsString ? ClassType.STRING : ClassType.UUID;
case OBJECT: return ClassType.OBJECT;
case CREDENTIAL: return ClassType.TOKEN_CREDENTIAL;
default:
throw new UnsupportedOperationException(String.format("Unrecognized AutoRest Primitive Type: %s",
primaryType.getType()));
}
}
}

Просмотреть файл

@ -12,127 +12,152 @@ import java.util.function.Function;
* A basic type used by a client.
*/
public class PrimitiveType implements IType {
public static final PrimitiveType VOID = new Builder()
.name("void")
.nullableType(ClassType.VOID)
.build();
public static final PrimitiveType VOID = new Builder()
.name("void")
.nullableType(ClassType.VOID)
.build();
public static final PrimitiveType BOOLEAN = new Builder()
.name("boolean")
.nullableType(ClassType.BOOLEAN)
.defaultValueExpressionConverter(String::toLowerCase)
.defaultValue("false")
.jsonToken("JsonToken.BOOLEAN")
.serializationMethodBase("writeBoolean")
.jsonDeserializationMethod("getBoolean()")
.xmlAttributeDeserializationTemplate("%s.getBooleanAttribute(%s, %s)")
.xmlElementDeserializationMethod("getBooleanElement()")
.build();
public static final PrimitiveType BOOLEAN = new Builder()
.name("boolean")
.nullableType(ClassType.BOOLEAN)
.defaultValueExpressionConverter(String::toLowerCase)
.defaultValue("false")
.jsonToken("JsonToken.BOOLEAN")
.serializationMethodBase("writeBoolean")
.jsonDeserializationMethod("getBoolean()")
.xmlAttributeDeserializationTemplate("%s.getBooleanAttribute(%s, %s)")
.xmlElementDeserializationMethod("getBooleanElement()")
.build();
public static final PrimitiveType BYTE = new Builder()
.name("byte")
.nullableType(ClassType.BYTE)
.defaultValueExpressionConverter(Function.identity())
.defaultValue("0")
.jsonToken("JsonToken.NUMBER")
.serializationMethodBase("writeInt")
.jsonDeserializationMethod("getInt()")
.xmlAttributeDeserializationTemplate("%s.getIntAttribute(%s, %s)")
.xmlElementDeserializationMethod("getIntElement()")
.build();
public static final PrimitiveType BYTE = new Builder()
.name("byte")
.nullableType(ClassType.BYTE)
.defaultValueExpressionConverter(Function.identity())
.defaultValue("0")
.jsonToken("JsonToken.NUMBER")
.serializationMethodBase("writeInt")
.jsonDeserializationMethod("getInt()")
.xmlAttributeDeserializationTemplate("%s.getIntAttribute(%s, %s)")
.xmlElementDeserializationMethod("getIntElement()")
.build();
public static final PrimitiveType INT = new Builder()
.name("int")
.nullableType(ClassType.INTEGER)
.defaultValueExpressionConverter(Function.identity())
.defaultValue("0")
.jsonToken("JsonToken.NUMBER")
.serializationMethodBase("writeInt")
.jsonDeserializationMethod("getInt()")
.xmlAttributeDeserializationTemplate("%s.getIntAttribute(%s, %s)")
.xmlElementDeserializationMethod("getIntElement()")
.build();
public static final PrimitiveType INT = new Builder()
.name("int")
.nullableType(ClassType.INTEGER)
.defaultValueExpressionConverter(Function.identity())
.defaultValue("0")
.jsonToken("JsonToken.NUMBER")
.serializationMethodBase("writeInt")
.jsonDeserializationMethod("getInt()")
.xmlAttributeDeserializationTemplate("%s.getIntAttribute(%s, %s)")
.xmlElementDeserializationMethod("getIntElement()")
.build();
public static final PrimitiveType LONG = new Builder()
.prototypeAsLong()
.build();
public static final PrimitiveType LONG = new Builder()
.prototypeAsLong()
.build();
public static final PrimitiveType FLOAT = new Builder()
.name("float")
.nullableType(ClassType.FLOAT)
.defaultValueExpressionConverter(defaultValueExpression -> defaultValueExpression + "f")
.defaultValue("0.0")
.jsonToken("JsonToken.NUMBER")
.serializationMethodBase("writeFloat")
.jsonDeserializationMethod("getFloat()")
.xmlAttributeDeserializationTemplate("%s.getFloatAttribute(%s, %s)")
.xmlElementDeserializationMethod("getFloatElement()")
.build();
public static final PrimitiveType INT_AS_STRING = new Builder()
.name("int")
.nullableType(ClassType.INTEGER_AS_STRING)
.defaultValueExpressionConverter(defaultValueExpression -> "Integer.parseInt(\"" + defaultValueExpression + "\")")
.jsonToken("JsonToken.STRING")
.defaultValue("0")
.serializationMethodBase("writeString")
.wrapSerializationWithObjectsToString(true)
.jsonDeserializationMethod("getNullable(nonNullReader -> Integer.parseInt(nonNullReader.getString()))")
.xmlElementDeserializationMethod("getNullableElement(Integer::valueOf)")
.xmlAttributeDeserializationTemplate("%s.getNullableAttribute(%s, %s, Integer::valueOf)")
.build();
public static final PrimitiveType DOUBLE = new Builder()
.prototypeAsDouble()
.build();
public static final PrimitiveType LONG_AS_STRING = new Builder()
.prototypeAsLong()
.nullableType(ClassType.LONG_AS_STRING)
.defaultValueExpressionConverter(defaultValueExpression -> "Long.parseLong(\"" + defaultValueExpression + "\")")
.jsonToken("JsonToken.STRING")
.serializationMethodBase("writeString")
.wrapSerializationWithObjectsToString(true)
.jsonDeserializationMethod("getNullable(nonNullReader -> Long.parseLong(nonNullReader.getString()))")
.xmlElementDeserializationMethod("getNullableElement(Long::valueOf)")
.xmlAttributeDeserializationTemplate("%s.getNullableAttribute(%s, %s, Long::valueOf)")
.build();
public static final PrimitiveType CHAR = new Builder()
.name("char")
.nullableType(ClassType.CHARACTER)
.defaultValueExpressionConverter(defaultValueExpression -> Integer.toString(defaultValueExpression.charAt(0)))
.defaultValue("\u0000")
.jsonToken("JsonToken.STRING")
.serializationMethodBase("writeString")
.wrapSerializationWithObjectsToString(true)
.jsonDeserializationMethod("getString().charAt(0)")
.xmlAttributeDeserializationTemplate("%s.getStringAttribute(%s, %s).charAt(0)")
.xmlElementDeserializationMethod("getStringElement().charAt(0)")
.build();
public static final PrimitiveType FLOAT = new Builder()
.name("float")
.nullableType(ClassType.FLOAT)
.defaultValueExpressionConverter(defaultValueExpression -> defaultValueExpression + "f")
.defaultValue("0.0")
.jsonToken("JsonToken.NUMBER")
.serializationMethodBase("writeFloat")
.jsonDeserializationMethod("getFloat()")
.xmlAttributeDeserializationTemplate("%s.getFloatAttribute(%s, %s)")
.xmlElementDeserializationMethod("getFloatElement()")
.build();
public static final PrimitiveType UNIX_TIME_LONG = new Builder()
.prototypeAsLong()
.nullableType(ClassType.UNIX_TIME_LONG)
.build();
public static final PrimitiveType DOUBLE = new Builder()
.prototypeAsDouble()
.build();
public static final PrimitiveType DURATION_LONG = new Builder()
.prototypeAsLong()
.nullableType(ClassType.DURATION_LONG)
.build();
public static final PrimitiveType CHAR = new Builder()
.name("char")
.nullableType(ClassType.CHARACTER)
.defaultValueExpressionConverter(defaultValueExpression -> Integer.toString(defaultValueExpression.charAt(0)))
.defaultValue("\u0000")
.jsonToken("JsonToken.STRING")
.serializationMethodBase("writeString")
.wrapSerializationWithObjectsToString(true)
.jsonDeserializationMethod("getString().charAt(0)")
.xmlAttributeDeserializationTemplate("%s.getStringAttribute(%s, %s).charAt(0)")
.xmlElementDeserializationMethod("getStringElement().charAt(0)")
.build();
public static final PrimitiveType DURATION_DOUBLE = new Builder()
.prototypeAsDouble()
.nullableType(ClassType.DURATION_DOUBLE)
.build();
public static final PrimitiveType UNIX_TIME_LONG = new Builder()
.prototypeAsLong()
.nullableType(ClassType.UNIX_TIME_LONG)
.build();
/**
* The name of this type.
*/
private final String name;
/**
* The nullable version of this primitive type.
*/
private final ClassType nullableType;
private final Function<String, String> defaultValueExpressionConverter;
private final String defaultValue;
private final String jsonToken;
private final String serializationMethodBase;
private final boolean wrapSerializationWithObjectsToString;
private final String jsonDeserializationMethod;
private final String xmlAttributeDeserializationTemplate;
private final String xmlElementDeserializationMethod;
public static final PrimitiveType DURATION_LONG = new Builder()
.prototypeAsLong()
.nullableType(ClassType.DURATION_LONG)
.build();
private PrimitiveType(String name, ClassType nullableType, Function<String, String> defaultValueExpressionConverter,
String defaultValue, String jsonToken, String serializationMethodBase,
boolean wrapSerializationWithObjectsToString, String jsonDeserializationMethod,
String xmlAttributeDeserializationTemplate, String xmlElementDeserializationMethod) {
this.name = name;
this.nullableType = nullableType;
this.defaultValueExpressionConverter = defaultValueExpressionConverter;
this.defaultValue = defaultValue;
this.jsonToken = jsonToken;
this.serializationMethodBase = serializationMethodBase;
this.wrapSerializationWithObjectsToString = wrapSerializationWithObjectsToString;
this.jsonDeserializationMethod = jsonDeserializationMethod;
this.xmlAttributeDeserializationTemplate = xmlAttributeDeserializationTemplate;
this.xmlElementDeserializationMethod = xmlElementDeserializationMethod;
}
public static final PrimitiveType DURATION_DOUBLE = new Builder()
.prototypeAsDouble()
.nullableType(ClassType.DURATION_DOUBLE)
.build();
/**
* The name of this type.
*/
private final String name;
/**
* The nullable version of this primitive type.
*/
private final ClassType nullableType;
private final Function<String, String> defaultValueExpressionConverter;
private final String defaultValue;
private final String jsonToken;
private final String serializationMethodBase;
private final boolean wrapSerializationWithObjectsToString;
private final String jsonDeserializationMethod;
private final String xmlAttributeDeserializationTemplate;
private final String xmlElementDeserializationMethod;
private PrimitiveType(String name, ClassType nullableType, Function<String, String> defaultValueExpressionConverter,
String defaultValue, String jsonToken, String serializationMethodBase,
boolean wrapSerializationWithObjectsToString, String jsonDeserializationMethod,
String xmlAttributeDeserializationTemplate, String xmlElementDeserializationMethod) {
this.name = name;
this.nullableType = nullableType;
this.defaultValueExpressionConverter = defaultValueExpressionConverter;
this.defaultValue = defaultValue;
this.jsonToken = jsonToken;
this.serializationMethodBase = serializationMethodBase;
this.wrapSerializationWithObjectsToString = wrapSerializationWithObjectsToString;
this.jsonDeserializationMethod = jsonDeserializationMethod;
this.xmlAttributeDeserializationTemplate = xmlAttributeDeserializationTemplate;
this.xmlElementDeserializationMethod = xmlElementDeserializationMethod;
}
// public static PrimitiveType fromNullableType(ClassType nullableType) {
// if (nullableType == ClassType.Void) {
@ -154,262 +179,262 @@ public class PrimitiveType implements IType {
// }
// }
public final String getName() {
return name;
public final String getName() {
return name;
}
private ClassType getNullableType() {
return nullableType;
}
@Override
public final void addImportsTo(Set<String> imports, boolean includeImplementationImports) {
if (this == PrimitiveType.UNIX_TIME_LONG) {
imports.add(Instant.class.getName());
imports.add(ZoneOffset.class.getName());
}
}
@Override
public final boolean isNullable() {
return false;
}
@Override
public final IType asNullable() {
return getNullableType();
}
@Override
public final boolean contains(IType type) {
return this == type;
}
private Function<String, String> getDefaultValueExpressionConverter() {
return defaultValueExpressionConverter;
}
@Override
public final String defaultValueExpression(String sourceExpression) {
String result = sourceExpression;
if (result != null && getDefaultValueExpressionConverter() != null) {
result = defaultValueExpressionConverter.apply(sourceExpression);
}
return result;
}
@Override
public final String defaultValueExpression() {
return defaultValueExpression(defaultValue);
}
@Override
public final IType getClientType() {
IType clientType = this;
if (this == PrimitiveType.UNIX_TIME_LONG) {
clientType = ClassType.UNIX_TIME_DATE_TIME;
} else if (this == PrimitiveType.DURATION_LONG) {
clientType = ClassType.DURATION;
} else if (this == PrimitiveType.DURATION_DOUBLE) {
clientType = ClassType.DURATION;
}
return clientType;
}
@Override
public final String convertToClientType(String expression) {
if (getClientType() == this) {
return expression;
}
private ClassType getNullableType() {
return nullableType;
if (this == PrimitiveType.UNIX_TIME_LONG) {
expression = String.format("OffsetDateTime.ofInstant(Instant.ofEpochSecond(%1$s), ZoneOffset.UTC)", expression);
} else if (this == PrimitiveType.DURATION_LONG) {
expression = String.format("Duration.ofSeconds(%s)", expression);
} else if (this == PrimitiveType.DURATION_DOUBLE) {
expression = String.format("Duration.ofNanos((long) (%s * 1000_000_000L))", expression);
}
return expression;
}
@Override
public final String convertFromClientType(String expression) {
if (getClientType() == this) {
return expression;
}
@Override
public final void addImportsTo(Set<String> imports, boolean includeImplementationImports) {
if (this == PrimitiveType.UNIX_TIME_LONG) {
imports.add(Instant.class.getName());
imports.add(ZoneOffset.class.getName());
}
if (this == PrimitiveType.UNIX_TIME_LONG) {
expression = String.format("%1$s.toEpochSecond()", expression);
} else if (this == PrimitiveType.DURATION_LONG) {
expression = String.format("%s.getSeconds()", expression);
} else if (this == PrimitiveType.DURATION_DOUBLE) {
expression = String.format("(double) %s.toNanos() / 1000_000_000L", expression);
}
return expression;
}
@Override
public final String validate(String expression) {
return null;
}
@Override
public String jsonToken() {
return jsonToken;
}
@Override
public String jsonDeserializationMethod(String jsonReaderName) {
if (jsonDeserializationMethod == null) {
return null;
}
@Override
public final boolean isNullable() {
return false;
return jsonReaderName + "." + jsonDeserializationMethod;
}
@Override
public String jsonSerializationMethodCall(String jsonWriterName, String fieldName, String valueGetter,
boolean jsonMergePatch) {
if (wrapSerializationWithObjectsToString) {
return fieldName == null
? String.format("%s.%s(Objects.toString(%s, null))", jsonWriterName, serializationMethodBase, valueGetter)
: String.format("%s.%sField(\"%s\", Objects.toString(%s, null))", jsonWriterName,
serializationMethodBase, fieldName, valueGetter);
}
@Override
public final IType asNullable() {
return getNullableType();
return fieldName == null
? String.format("%s.%s(%s)", jsonWriterName, serializationMethodBase, valueGetter)
: String.format("%s.%sField(\"%s\", %s)", jsonWriterName, serializationMethodBase, fieldName, valueGetter);
}
@Override
public String xmlDeserializationMethod(String xmlReaderName, String attributeName, String attributeNamespace,
boolean namespaceIsConstant) {
if (attributeName == null) {
return xmlReaderName + "." + xmlElementDeserializationMethod;
} else if (attributeNamespace == null) {
return String.format(xmlAttributeDeserializationTemplate, xmlReaderName, "null",
"\"" + attributeName + "\"");
} else {
String namespace = namespaceIsConstant ? attributeNamespace : "\"" + attributeNamespace + "\"";
return String.format(xmlAttributeDeserializationTemplate, xmlReaderName, namespace,
"\"" + attributeName + "\"");
}
}
@Override
public String xmlSerializationMethodCall(String xmlWriterName, String attributeOrElementName, String namespaceUri,
String valueGetter, boolean isAttribute, boolean nameIsVariable, boolean namespaceIsConstant) {
String value = wrapSerializationWithObjectsToString
? "Objects.toString(" + valueGetter + ", null)" : valueGetter;
return ClassType.xmlSerializationCallHelper(xmlWriterName, serializationMethodBase, attributeOrElementName,
namespaceUri, value, isAttribute, nameIsVariable, namespaceIsConstant);
}
@Override
public boolean isUsedInXml() {
return false;
}
@Override
public String toString() {
return getName();
}
private static class Builder {
private String name;
private ClassType nullableType;
private Function<String, String> defaultValueExpressionConverter;
private String defaultValue;
private String jsonToken;
private String serializationMethodBase;
private boolean wrapSerializationWithObjectsToString = false;
private String jsonDeserializationMethod;
private String xmlAttributeDeserializationTemplate;
private String xmlElementDeserializationMethod;
public Builder name(String name) {
this.name = name;
return this;
}
@Override
public final boolean contains(IType type) {
return this == type;
public Builder prototypeAsLong() {
return this.name("long")
.nullableType(ClassType.LONG)
.defaultValueExpressionConverter(defaultValueExpression -> defaultValueExpression + 'L')
.defaultValue("0")
.jsonToken("JsonToken.NUMBER")
.serializationMethodBase("writeLong")
.wrapSerializationWithObjectsToString(false)
.jsonDeserializationMethod("getLong()")
.xmlAttributeDeserializationTemplate("%s.getLongAttribute(%s, %s)")
.xmlElementDeserializationMethod("getLongElement()");
}
private Function<String, String> getDefaultValueExpressionConverter() {
return defaultValueExpressionConverter;
public Builder prototypeAsDouble() {
return this.name("double")
.nullableType(ClassType.DOUBLE)
.defaultValueExpressionConverter(defaultValueExpression -> java.lang.Double.toString(java.lang.Double.parseDouble(defaultValueExpression)))
.defaultValue("0.0")
.jsonToken("JsonToken.NUMBER")
.serializationMethodBase("writeDouble")
.wrapSerializationWithObjectsToString(false)
.jsonDeserializationMethod("getDouble()")
.xmlAttributeDeserializationTemplate("%s.getDoubleAttribute(%s, %s)")
.xmlElementDeserializationMethod("getDoubleElement()");
}
@Override
public final String defaultValueExpression(String sourceExpression) {
String result = sourceExpression;
if (result != null && getDefaultValueExpressionConverter() != null) {
result = defaultValueExpressionConverter.apply(sourceExpression);
}
return result;
public Builder nullableType(ClassType nullableType) {
this.nullableType = nullableType;
return this;
}
@Override
public final String defaultValueExpression() {
return defaultValueExpression(defaultValue);
public Builder defaultValue(String defaultValue) {
this.defaultValue = defaultValue;
return this;
}
@Override
public final IType getClientType() {
IType clientType = this;
if (this == PrimitiveType.UNIX_TIME_LONG) {
clientType = ClassType.UNIX_TIME_DATE_TIME;
} else if (this == PrimitiveType.DURATION_LONG) {
clientType = ClassType.DURATION;
} else if (this == PrimitiveType.DURATION_DOUBLE) {
clientType = ClassType.DURATION;
}
return clientType;
public Builder defaultValueExpressionConverter(java.util.function.Function<String, String> defaultValueExpressionConverter) {
this.defaultValueExpressionConverter = defaultValueExpressionConverter;
return this;
}
@Override
public final String convertToClientType(String expression) {
if (getClientType() == this) {
return expression;
}
if (this == PrimitiveType.UNIX_TIME_LONG) {
expression = String.format("OffsetDateTime.ofInstant(Instant.ofEpochSecond(%1$s), ZoneOffset.UTC)", expression);
} else if (this == PrimitiveType.DURATION_LONG) {
expression = String.format("Duration.ofSeconds(%s)", expression);
} else if (this == PrimitiveType.DURATION_DOUBLE) {
expression = String.format("Duration.ofNanos((long) (%s * 1000_000_000L))", expression);
}
return expression;
public Builder wrapSerializationWithObjectsToString(boolean wrapSerializationWithObjectsToString) {
this.wrapSerializationWithObjectsToString = wrapSerializationWithObjectsToString;
return this;
}
@Override
public final String convertFromClientType(String expression) {
if (getClientType() == this) {
return expression;
}
if (this == PrimitiveType.UNIX_TIME_LONG) {
expression = String.format("%1$s.toEpochSecond()", expression);
} else if (this == PrimitiveType.DURATION_LONG) {
expression = String.format("%s.getSeconds()", expression);
} else if (this == PrimitiveType.DURATION_DOUBLE) {
expression = String.format("(double) %s.toNanos() / 1000_000_000L", expression);
}
return expression;
public Builder jsonToken(String jsonToken) {
this.jsonToken = jsonToken;
return this;
}
@Override
public final String validate(String expression) {
return null;
public Builder jsonDeserializationMethod(String jsonDeserializationMethod) {
this.jsonDeserializationMethod = jsonDeserializationMethod;
return this;
}
@Override
public String jsonToken() {
return jsonToken;
public Builder serializationMethodBase(String serializationMethodBase) {
this.serializationMethodBase = serializationMethodBase;
return this;
}
@Override
public String jsonDeserializationMethod(String jsonReaderName) {
if (jsonDeserializationMethod == null) {
return null;
}
return jsonReaderName + "." + jsonDeserializationMethod;
public Builder xmlAttributeDeserializationTemplate(String xmlAttributeDeserializationTemplate) {
this.xmlAttributeDeserializationTemplate = xmlAttributeDeserializationTemplate;
return this;
}
@Override
public String jsonSerializationMethodCall(String jsonWriterName, String fieldName, String valueGetter,
boolean jsonMergePatch) {
if (wrapSerializationWithObjectsToString) {
return fieldName == null
? String.format("%s.%s(Objects.toString(%s, null))", jsonWriterName, serializationMethodBase, valueGetter)
: String.format("%s.%sField(\"%s\", Objects.toString(%s, null))", jsonWriterName,
serializationMethodBase, fieldName, valueGetter);
}
return fieldName == null
? String.format("%s.%s(%s)", jsonWriterName, serializationMethodBase, valueGetter)
: String.format("%s.%sField(\"%s\", %s)", jsonWriterName, serializationMethodBase, fieldName, valueGetter);
public Builder xmlElementDeserializationMethod(String xmlElementDeserializationMethod) {
this.xmlElementDeserializationMethod = xmlElementDeserializationMethod;
return this;
}
@Override
public String xmlDeserializationMethod(String xmlReaderName, String attributeName, String attributeNamespace,
boolean namespaceIsConstant) {
if (attributeName == null) {
return xmlReaderName + "." + xmlElementDeserializationMethod;
} else if (attributeNamespace == null) {
return String.format(xmlAttributeDeserializationTemplate, xmlReaderName, "null",
"\"" + attributeName + "\"");
} else {
String namespace = namespaceIsConstant ? attributeNamespace : "\"" + attributeNamespace + "\"";
return String.format(xmlAttributeDeserializationTemplate, xmlReaderName, namespace,
"\"" + attributeName + "\"");
}
}
@Override
public String xmlSerializationMethodCall(String xmlWriterName, String attributeOrElementName, String namespaceUri,
String valueGetter, boolean isAttribute, boolean nameIsVariable, boolean namespaceIsConstant) {
String value = wrapSerializationWithObjectsToString
? "Objects.toString(" + valueGetter + ", null)" : valueGetter;
return ClassType.xmlSerializationCallHelper(xmlWriterName, serializationMethodBase, attributeOrElementName,
namespaceUri, value, isAttribute, nameIsVariable, namespaceIsConstant);
}
@Override
public boolean isUsedInXml() {
return false;
}
@Override
public String toString() {
return getName();
}
private static class Builder {
private String name;
private ClassType nullableType;
private Function<String, String> defaultValueExpressionConverter;
private String defaultValue;
private String jsonToken;
private String serializationMethodBase;
private boolean wrapSerializationWithObjectsToString = false;
private String jsonDeserializationMethod;
private String xmlAttributeDeserializationTemplate;
private String xmlElementDeserializationMethod;
public Builder name(String name) {
this.name = name;
return this;
}
public Builder prototypeAsLong() {
return this.name("long")
.nullableType(ClassType.LONG)
.defaultValueExpressionConverter(defaultValueExpression -> defaultValueExpression + 'L')
.defaultValue("0")
.jsonToken("JsonToken.NUMBER")
.serializationMethodBase("writeLong")
.wrapSerializationWithObjectsToString(false)
.jsonDeserializationMethod("getLong()")
.xmlAttributeDeserializationTemplate("%s.getLongAttribute(%s, %s)")
.xmlElementDeserializationMethod("getLongElement()");
}
public Builder prototypeAsDouble() {
return this.name("double")
.nullableType(ClassType.DOUBLE)
.defaultValueExpressionConverter(defaultValueExpression -> java.lang.Double.toString(java.lang.Double.parseDouble(defaultValueExpression)))
.defaultValue("0.0")
.jsonToken("JsonToken.NUMBER")
.serializationMethodBase("writeDouble")
.wrapSerializationWithObjectsToString(false)
.jsonDeserializationMethod("getDouble()")
.xmlAttributeDeserializationTemplate("%s.getDoubleAttribute(%s, %s)")
.xmlElementDeserializationMethod("getDoubleElement()");
}
public Builder nullableType(ClassType nullableType) {
this.nullableType = nullableType;
return this;
}
public Builder defaultValue(String defaultValue) {
this.defaultValue = defaultValue;
return this;
}
public Builder defaultValueExpressionConverter(java.util.function.Function<String, String> defaultValueExpressionConverter) {
this.defaultValueExpressionConverter = defaultValueExpressionConverter;
return this;
}
public Builder wrapSerializationWithObjectsToString(boolean wrapSerializationWithObjectsToString) {
this.wrapSerializationWithObjectsToString = wrapSerializationWithObjectsToString;
return this;
}
public Builder jsonToken(String jsonToken) {
this.jsonToken = jsonToken;
return this;
}
public Builder jsonDeserializationMethod(String jsonDeserializationMethod) {
this.jsonDeserializationMethod = jsonDeserializationMethod;
return this;
}
public Builder serializationMethodBase(String serializationMethodBase) {
this.serializationMethodBase = serializationMethodBase;
return this;
}
public Builder xmlAttributeDeserializationTemplate(String xmlAttributeDeserializationTemplate) {
this.xmlAttributeDeserializationTemplate = xmlAttributeDeserializationTemplate;
return this;
}
public Builder xmlElementDeserializationMethod(String xmlElementDeserializationMethod) {
this.xmlElementDeserializationMethod = xmlElementDeserializationMethod;
return this;
}
public PrimitiveType build() {
return new PrimitiveType(name, nullableType, defaultValueExpressionConverter, defaultValue, jsonToken,
serializationMethodBase, wrapSerializationWithObjectsToString, jsonDeserializationMethod,
xmlAttributeDeserializationTemplate, xmlElementDeserializationMethod);
}
public PrimitiveType build() {
return new PrimitiveType(name, nullableType, defaultValueExpressionConverter, defaultValue, jsonToken,
serializationMethodBase, wrapSerializationWithObjectsToString, jsonDeserializationMethod,
xmlAttributeDeserializationTemplate, xmlElementDeserializationMethod);
}
}
}

Просмотреть файл

@ -29,351 +29,316 @@ import java.util.stream.Stream;
public class ProxyMethodExample {
private final Logger logger = new PluginLogger(Javagen.getPluginInstance(), ProxyMethodExample.class);
private static final String SLASH = "/";
private final Logger logger = new PluginLogger(Javagen.getPluginInstance(), ProxyMethodExample.class);
private static final String SLASH = "/";
private static String tspDirectory = null;
// https://azure.github.io/autorest/extensions/#x-ms-examples
// https://github.com/Azure/azure-rest-api-specs/blob/main/documentation/x-ms-examples.md
public static void setTspDirectory(String tspDirectory) {
ProxyMethodExample.tspDirectory = tspDirectory;
public static class ParameterValue {
private final Object objectValue;
public ParameterValue(Object objectValue) {
this.objectValue = objectValue;
}
// https://azure.github.io/autorest/extensions/#x-ms-examples
// https://github.com/Azure/azure-rest-api-specs/blob/main/documentation/x-ms-examples.md
public static class ParameterValue {
private final Object objectValue;
public ParameterValue(Object objectValue) {
this.objectValue = objectValue;
}
/**
* @return the object value of the parameter
*/
public Object getObjectValue() {
return objectValue;
}
/**
* Gets the un-escaped query value.
* <p>
* This is done by heuristic, and not guaranteed to be correct.
*
* @return the un-escaped query value
*/
public Object getUnescapedQueryValue() {
Object unescapedValue = objectValue;
if (objectValue instanceof String) {
unescapedValue = URLDecoder.decode((String) objectValue, StandardCharsets.UTF_8);
}
return unescapedValue;
}
@Override
public String toString() {
return "ParameterValue{objectValue=" + getJsonString() + '}';
}
public String getJsonString() {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) {
jsonWriter.writeUntyped(objectValue).flush();
return outputStream.toString(StandardCharsets.UTF_8);
} catch (IOException e) {
return objectValue.toString();
}
}
}
public static class Response {
private final int statusCode;
private final HttpHeaders httpHeaders;
private final Object body;
@SuppressWarnings("unchecked")
public Response(int statusCode, Object response) {
this.statusCode = statusCode;
this.httpHeaders = new HttpHeaders();
if (response instanceof Map) {
Map<String, Object> responseMap = (Map<String, Object>) response;
if (responseMap.containsKey("headers") && responseMap.get("headers") instanceof Map) {
Map<String, Object> headersMap = (Map<String, Object>) responseMap.get("headers");
headersMap.forEach(
(header, value) -> httpHeaders.add(HttpHeaderName.fromString(header), String.valueOf(value)));
}
this.body = responseMap.getOrDefault("body", null);
} else {
this.body = null;
}
}
/** @return the status code */
public int getStatusCode() {
return statusCode;
}
/** @return the http headers */
public HttpHeaders getHttpHeaders() {
return httpHeaders;
}
/** @return the response body */
public Object getBody() {
return body;
}
/** @return the response body as JSON string */
public String getJsonBody() {
return getJson(body);
}
/**
* @param obj the object for JSON string
* @return the object as JSON string
*/
public String getJson(Object obj) {
if (obj != null) {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) {
jsonWriter.writeUntyped(obj).flush();
return outputStream.toString(StandardCharsets.UTF_8);
} catch (IOException e) {
return obj.toString();
}
} else {
return "";
}
}
@Override
public String toString() {
return "Response{statusCode=" + statusCode + ", httpHeaders=" + httpHeaders + ", body=" + getJsonBody()
+ '}';
}
}
private final Map<String, ParameterValue> parameters = new LinkedHashMap<>();
private final Map<Integer, Response> responses = new LinkedHashMap<>();
private final String originalFile;
private String relativeOriginalFileName;
private String codeSnippetIdentifier;
private String name;
/**
* @return the map of parameter name to parameter object values
* @return the object value of the parameter
*/
public Map<String, ParameterValue> getParameters() {
return parameters;
public Object getObjectValue() {
return objectValue;
}
/**
* @return the map of status code to response
*/
public Map<Integer, Response> getResponses() {
return responses;
}
/**
* @return the primary response
*/
public Response getPrimaryResponse() {
if (responses.isEmpty()) {
return null;
}
Response firstResponse = null;
for (Response response : responses.values()) {
if (firstResponse == null) {
firstResponse = response;
}
if (response.statusCode / 100 == 2) {
return response;
}
}
return firstResponse;
}
/**
* @return value of "x-ms-original-file" extension
*/
public String getOriginalFile() {
return originalFile;
}
/**
* Heuristically find relative path of the original file to the repository.
* Gets the un-escaped query value.
* <p>
* For instance,
* "specification/resources/resource-manager/Microsoft.Authorization/stable/2020-09-01/examples/getDataPolicyManifest.json"
* This is done by heuristic, and not guaranteed to be correct.
*
* @return the relative path of the original file
* @return the un-escaped query value
*/
public String getRelativeOriginalFileName() {
if (relativeOriginalFileName == null && !CoreUtils.isNullOrEmpty(this.getOriginalFile())) {
String originalFileName = this.getOriginalFile();
try {
URL url = new URI(originalFileName).toURL();
switch (url.getProtocol()) {
case "http":
case "https": {
String[] segments = url.getPath().split(SLASH);
if (segments.length > 3) {
// first 3 should be owner, name, branch
originalFileName = Arrays.stream(segments)
.filter(s -> !s.isEmpty())
.skip(3)
.collect(Collectors.joining(SLASH));
}
break;
}
case "file": {
String relativeFileName = tspDirectory != null
? getRelativeOriginalFileNameForTsp(url)
: getRelativeOriginalFileNameForSwagger(url);
if (relativeFileName != null) {
originalFileName = relativeFileName;
}
break;
}
default: {
logger.error("Unknown protocol in x-ms-original-file: '{}'", originalFileName);
break;
}
}
} catch (MalformedURLException | URISyntaxException | IllegalArgumentException e) {
logger.error("Failed to parse x-ms-original-file: '{}'", originalFileName);
}
relativeOriginalFileName = originalFileName;
}
return relativeOriginalFileName;
}
/**
* identifier of the codesnippet label from codesnippet-maven-plugin
*
* @return the identifier of the codesnippet label that wraps around the example code
* @see <a
* href="https://github.com/Azure/azure-sdk-tools/blob/main/packages/java-packages/codesnippet-maven-plugin/README.md">codesnippet-maven-plugin</a>
*/
public String getCodeSnippetIdentifier() {
return codeSnippetIdentifier;
}
/** @return example name */
public String getName() {
return name;
}
private ProxyMethodExample(String originalFile) {
this.originalFile = originalFile;
}
static String getRelativeOriginalFileNameForTsp(URL url) {
// TypeSpec
/*
* Example:
* directory "specification/standbypool/StandbyPool.Management"
* originalFileName "file:///C:/github/azure-sdk-for-java/sdk/standbypool/azure-resourcemanager-standbypool/TempTypeSpecFiles/StandbyPool.Management/examples/2023-12-01-preview/StandbyVirtualMachinePools_Update.json"
*
* There is an overlap of "StandbyPool.Management", so that we can combine the 2 to Result:
* "specification/standbypool/StandbyPool.Management/examples/2023-12-01-preview/StandbyVirtualMachinePools_Update.json"
*/
String originalFileName = null;
String[] directorySegments = tspDirectory.split(SLASH);
String directoryLastSegment = directorySegments[directorySegments.length - 1];
int sharedDirectorySegment = -1;
String[] segments = url.getPath().split(SLASH);
for (int i = segments.length - 1; i >= 0; --i) {
if (Objects.equals(directoryLastSegment, segments[i])) {
sharedDirectorySegment = i;
break;
}
}
if (sharedDirectorySegment >= 0) {
originalFileName = Stream.concat(Arrays.stream(directorySegments),
Arrays.stream(segments).skip(sharedDirectorySegment + 1)).collect(Collectors.joining(SLASH));
}
return originalFileName;
}
static String getRelativeOriginalFileNameForSwagger(URL url) {
// Swagger
/*
* The examples should be under "specification/<service>/resource-manager"
* or "specification/<service>/data-plane"
*/
String originalFileName = null;
String[] segments = url.getPath().split(SLASH);
int resourceManagerOrDataPlaneSegmentIndex = -1;
for (int i = 0; i < segments.length; ++i) {
if ("resource-manager".equals(segments[i]) || "data-plane".equals(segments[i])) {
resourceManagerOrDataPlaneSegmentIndex = i;
break;
}
}
if (resourceManagerOrDataPlaneSegmentIndex > 2) {
originalFileName = Arrays.stream(segments)
.skip(resourceManagerOrDataPlaneSegmentIndex - 2)
.collect(Collectors.joining(SLASH));
}
return originalFileName;
public Object getUnescapedQueryValue() {
Object unescapedValue = objectValue;
if (objectValue instanceof String) {
unescapedValue = URLDecoder.decode((String) objectValue, StandardCharsets.UTF_8);
}
return unescapedValue;
}
@Override
public String toString() {
return "ProxyMethodExample{" + "parameters=" + parameters + ", responses=" + responses + '}';
return "ParameterValue{objectValue=" + getJsonString() + '}';
}
public static final class Builder {
private final Map<String, ParameterValue> parameters = new LinkedHashMap<>();
private final Map<Integer, Response> responses = new LinkedHashMap<>();
private String originalFile;
private String codeSnippetIdentifier;
private String name;
public String getJsonString() {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) {
jsonWriter.writeUntyped(objectValue).flush();
return outputStream.toString(StandardCharsets.UTF_8);
} catch (IOException e) {
return objectValue.toString();
}
}
}
public Builder() {
public static class Response {
private final int statusCode;
private final HttpHeaders httpHeaders;
private final Object body;
@SuppressWarnings("unchecked")
public Response(int statusCode, Object response) {
this.statusCode = statusCode;
this.httpHeaders = new HttpHeaders();
if (response instanceof Map) {
Map<String, Object> responseMap = (Map<String, Object>) response;
if (responseMap.containsKey("headers") && responseMap.get("headers") instanceof Map) {
Map<String, Object> headersMap = (Map<String, Object>) responseMap.get("headers");
headersMap.forEach(
(header, value) -> httpHeaders.add(HttpHeaderName.fromString(header), String.valueOf(value)));
}
this.body = responseMap.getOrDefault("body", null);
} else {
this.body = null;
}
}
public Builder parameter(String parameterName, Object parameterValue) {
if (parameterValue != null) {
this.parameters.put(parameterName, new ParameterValue(parameterValue));
/** @return the status code */
public int getStatusCode() {
return statusCode;
}
/** @return the http headers */
public HttpHeaders getHttpHeaders() {
return httpHeaders;
}
/** @return the response body */
public Object getBody() {
return body;
}
/** @return the response body as JSON string */
public String getJsonBody() {
return getJson(body);
}
/**
* @param obj the object for JSON string
* @return the object as JSON string
*/
public String getJson(Object obj) {
if (obj != null) {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) {
jsonWriter.writeUntyped(obj).flush();
return outputStream.toString(StandardCharsets.UTF_8);
} catch (IOException e) {
return obj.toString();
}
} else {
return "";
}
}
@Override
public String toString() {
return "Response{statusCode=" + statusCode + ", httpHeaders=" + httpHeaders + ", body=" + getJsonBody()
+ '}';
}
}
private final Map<String, ParameterValue> parameters = new LinkedHashMap<>();
private final Map<Integer, Response> responses = new LinkedHashMap<>();
private final String originalFile;
private String relativeOriginalFileName;
private String codeSnippetIdentifier;
private String name;
/**
* @return the map of parameter name to parameter object values
*/
public Map<String, ParameterValue> getParameters() {
return parameters;
}
/**
* @return the map of status code to response
*/
public Map<Integer, Response> getResponses() {
return responses;
}
/**
* @return the primary response
*/
public Response getPrimaryResponse() {
if (responses.isEmpty()) {
return null;
}
Response firstResponse = null;
for (Response response : responses.values()) {
if (firstResponse == null) {
firstResponse = response;
}
if (response.statusCode / 100 == 2) {
return response;
}
}
return firstResponse;
}
/**
* @return value of "x-ms-original-file" extension
*/
public String getOriginalFile() {
return originalFile;
}
/**
* Heuristically find relative path of the original file to the repository.
* <p>
* For instance,
* "specification/resources/resource-manager/Microsoft.Authorization/stable/2020-09-01/examples/getDataPolicyManifest.json"
*
* @return the relative path of the original file
*/
public String getRelativeOriginalFileName() {
if (relativeOriginalFileName == null && !CoreUtils.isNullOrEmpty(this.getOriginalFile())) {
String originalFileName = this.getOriginalFile();
try {
URL url = new URI(originalFileName).toURL();
switch (url.getProtocol()) {
case "http":
case "https": {
String[] segments = url.getPath().split(SLASH);
if (segments.length > 3) {
// first 3 should be owner, name, branch
originalFileName = Arrays.stream(segments)
.filter(s -> !s.isEmpty())
.skip(3)
.collect(Collectors.joining(SLASH));
}
return this;
}
break;
}
public Builder response(Integer statusCode, Object response) {
this.responses.put(statusCode, new Response(statusCode, response));
return this;
}
case "file": {
String relativeFileName = getRelativeOriginalFileNameForSwagger(url);
if (relativeFileName != null) {
originalFileName = relativeFileName;
}
break;
}
public Builder originalFile(String originalFile) {
this.originalFile = originalFile;
return this;
}
public Builder codeSnippetIdentifier(String identifier) {
this.codeSnippetIdentifier = identifier;
return this;
}
public Builder name(String name) {
this.name = name;
return this;
}
public ProxyMethodExample build() {
ProxyMethodExample proxyMethodExample = new ProxyMethodExample(originalFile);
proxyMethodExample.parameters.putAll(this.parameters);
proxyMethodExample.responses.putAll(this.responses);
proxyMethodExample.codeSnippetIdentifier = this.codeSnippetIdentifier;
proxyMethodExample.name = this.name;
return proxyMethodExample;
default: {
logger.error("Unknown protocol in x-ms-original-file: '{}'", originalFileName);
break;
}
}
} catch (MalformedURLException | URISyntaxException | IllegalArgumentException e) {
// relative file path from TypeSpec, it is not URL
// go with default flow of "relativeOriginalFileName = originalFileName;"
}
relativeOriginalFileName = originalFileName;
}
return relativeOriginalFileName;
}
/**
* identifier of the codesnippet label from codesnippet-maven-plugin
*
* @return the identifier of the codesnippet label that wraps around the example code
* @see <a
* href="https://github.com/Azure/azure-sdk-tools/blob/main/packages/java-packages/codesnippet-maven-plugin/README.md">codesnippet-maven-plugin</a>
*/
public String getCodeSnippetIdentifier() {
return codeSnippetIdentifier;
}
/** @return example name */
public String getName() {
return name;
}
private ProxyMethodExample(String originalFile) {
this.originalFile = originalFile;
}
static String getRelativeOriginalFileNameForSwagger(URL url) {
// Swagger
/*
* The examples should be under "specification/<service>/resource-manager"
* or "specification/<service>/data-plane"
*/
String originalFileName = null;
String[] segments = url.getPath().split(SLASH);
int resourceManagerOrDataPlaneSegmentIndex = -1;
for (int i = 0; i < segments.length; ++i) {
if ("resource-manager".equals(segments[i]) || "data-plane".equals(segments[i])) {
resourceManagerOrDataPlaneSegmentIndex = i;
break;
}
}
if (resourceManagerOrDataPlaneSegmentIndex > 2) {
originalFileName = Arrays.stream(segments)
.skip(resourceManagerOrDataPlaneSegmentIndex - 2)
.collect(Collectors.joining(SLASH));
}
return originalFileName;
}
@Override
public String toString() {
return "ProxyMethodExample{" + "parameters=" + parameters + ", responses=" + responses + '}';
}
public static final class Builder {
private final Map<String, ParameterValue> parameters = new LinkedHashMap<>();
private final Map<Integer, Response> responses = new LinkedHashMap<>();
private String originalFile;
private String codeSnippetIdentifier;
private String name;
public Builder() {
}
public Builder parameter(String parameterName, Object parameterValue) {
if (parameterValue != null) {
this.parameters.put(parameterName, new ParameterValue(parameterValue));
}
return this;
}
public Builder response(Integer statusCode, Object response) {
this.responses.put(statusCode, new Response(statusCode, response));
return this;
}
public Builder originalFile(String originalFile) {
this.originalFile = originalFile;
return this;
}
public Builder codeSnippetIdentifier(String identifier) {
this.codeSnippetIdentifier = identifier;
return this;
}
public Builder name(String name) {
this.name = name;
return this;
}
public ProxyMethodExample build() {
ProxyMethodExample proxyMethodExample = new ProxyMethodExample(originalFile);
proxyMethodExample.parameters.putAll(this.parameters);
proxyMethodExample.responses.putAll(this.responses);
proxyMethodExample.codeSnippetIdentifier = this.codeSnippetIdentifier;
proxyMethodExample.name = this.name;
return proxyMethodExample;
}
}
}

Просмотреть файл

@ -13,205 +13,219 @@ import java.util.function.Consumer;
import java.util.stream.Collectors;
public class JavaClass implements JavaType {
private final JavaFileContents contents;
private boolean addNewLine;
private final JavaFileContents contents;
private boolean addNewLine;
public JavaClass(JavaFileContents contents) {
this.contents = contents;
}
public JavaClass(JavaFileContents contents) {
this.contents = contents;
}
private void addExpectedNewLine() {
if (addNewLine) {
contents.line();
addNewLine = false;
}
private void addExpectedNewLine() {
if (addNewLine) {
contents.line();
addNewLine = false;
}
}
public final void privateMemberVariable(String variableType, String variableName) {
privateMemberVariable(variableType + " " + variableName);
}
public final void privateMemberVariable(String variableType, String variableName) {
memberVariable(JavaVisibility.Private, variableType + " " + variableName);
}
public final void privateMemberVariable(String variableDeclaration) {
addExpectedNewLine();
contents.line("private " + variableDeclaration + ";");
addNewLine = true;
}
public final void privateMemberVariable(String variableDeclaration) {
memberVariable(JavaVisibility.Private, variableDeclaration);
}
public final void privateFinalMemberVariable(String variableDeclaration) {
addExpectedNewLine();
contents.line("private final " + variableDeclaration + ";");
addNewLine = true;
}
/**
* Adds a variable declaration.
* <p>
* If the visibility is null or {@link JavaVisibility#PackagePrivate}, the variable will be package-private.
*
* @param visibility The visibility of the variable.
* @param variableDeclaration The variable declaration.
*/
public final void memberVariable(JavaVisibility visibility, String variableDeclaration) {
addExpectedNewLine();
String line = (visibility == null || visibility == JavaVisibility.PackagePrivate)
? variableDeclaration + ";" : visibility + " " + variableDeclaration + ";";
contents.line(line);
addNewLine = true;
}
public final void privateFinalMemberVariable(String variableType, String variableName) {
addExpectedNewLine();
contents.line("private final " + variableType + " " + variableName + ";");
addNewLine = true;
}
public final void privateFinalMemberVariable(String variableDeclaration) {
addExpectedNewLine();
contents.line("private final " + variableDeclaration + ";");
addNewLine = true;
}
public final void privateFinalMemberVariable(String variableType, String variableName, String finalValue) {
addExpectedNewLine();
contents.line("private final " + variableType + " " + variableName + " = " + finalValue + ";");
addNewLine = true;
}
public final void privateFinalMemberVariable(String variableType, String variableName) {
addExpectedNewLine();
contents.line("private final " + variableType + " " + variableName + ";");
addNewLine = true;
}
public final void publicStaticFinalVariable(String variableDeclaration) {
addExpectedNewLine();
contents.line("public static final " + variableDeclaration + ";");
addNewLine = true;
}
public final void privateFinalMemberVariable(String variableType, String variableName, String finalValue) {
addExpectedNewLine();
contents.line("private final " + variableType + " " + variableName + " = " + finalValue + ";");
addNewLine = true;
}
public final void privateStaticFinalVariable(String variableDeclaration) {
addExpectedNewLine();
contents.line("private static final " + variableDeclaration + ";");
addNewLine = true;
}
public final void publicStaticFinalVariable(String variableDeclaration) {
addExpectedNewLine();
contents.line("public static final " + variableDeclaration + ";");
addNewLine = true;
}
public final void protectedMemberVariable(String variableType, String variableName) {
addExpectedNewLine();
contents.line("protected " + variableType + " " + variableName + ";");
addNewLine = true;
}
public final void privateStaticFinalVariable(String variableDeclaration) {
addExpectedNewLine();
contents.line("private static final " + variableDeclaration + ";");
addNewLine = true;
}
/**
* Adds a variable with the given declaration and visibility.
* <p>
* This doesn't support modifiers. If you need to add modifiers, use
* {@link #variable(String, JavaVisibility, JavaModifier...)}. This will just be a non-final, non-static variable
* with the given visibility.
*
* @param variableDeclaration The variable declaration.
* @param visibility The visibility of the variable.
*/
public final void variable(String variableDeclaration, JavaVisibility visibility) {
addExpectedNewLine();
contents.line(visibility + " " + variableDeclaration + ";");
addNewLine = true;
}
public final void protectedMemberVariable(String variableType, String variableName) {
addExpectedNewLine();
contents.line("protected " + variableType + " " + variableName + ";");
addNewLine = true;
}
/**
* Adds a variable with the given declaration, visibility, and modifiers.
* <p>
* Adding a private constant variable would be:
* {@code variable(declaration, JavaVisibility.Private, JavaModifier.Static, JavaModifier.Final)}
*
* @param variableDeclaration The variable declaration.
* @param visibility The visibility of the variable.
* @param modifiers The modifiers of the variable.
*/
public final void variable(String variableDeclaration, JavaVisibility visibility, JavaModifier... modifiers) {
addExpectedNewLine();
String modifier = CoreUtils.isNullOrEmpty(modifiers) ? ""
: Arrays.stream(modifiers).map(JavaModifier::toString).collect(Collectors.joining(" "));
contents.line(visibility + " " + modifier + " " + variableDeclaration + ";");
addNewLine = true;
}
/**
* Adds a variable with the given declaration and visibility.
* <p>
* This doesn't support modifiers. If you need to add modifiers, use
* {@link #variable(String, JavaVisibility, JavaModifier...)}. This will just be a non-final, non-static variable
* with the given visibility.
*
* @param variableDeclaration The variable declaration.
* @param visibility The visibility of the variable.
*/
public final void variable(String variableDeclaration, JavaVisibility visibility) {
addExpectedNewLine();
contents.line(visibility + " " + variableDeclaration + ";");
addNewLine = true;
}
public final void constructor(JavaVisibility visibility, String constructorSignature, Consumer<JavaBlock> constructor) {
addExpectedNewLine();
contents.constructor(visibility, constructorSignature, constructor);
addNewLine = true;
}
/**
* Adds a variable with the given declaration, visibility, and modifiers.
* <p>
* Adding a private constant variable would be:
* {@code variable(declaration, JavaVisibility.Private, JavaModifier.Static, JavaModifier.Final)}
*
* @param variableDeclaration The variable declaration.
* @param visibility The visibility of the variable.
* @param modifiers The modifiers of the variable.
*/
public final void variable(String variableDeclaration, JavaVisibility visibility, JavaModifier... modifiers) {
addExpectedNewLine();
String modifier = CoreUtils.isNullOrEmpty(modifiers) ? ""
: Arrays.stream(modifiers).map(JavaModifier::toString).collect(Collectors.joining(" "));
contents.line(visibility + " " + modifier + " " + variableDeclaration + ";");
addNewLine = true;
}
public final void privateConstructor(String constructorSignature, Consumer<JavaBlock> constructor) {
constructor(JavaVisibility.Private, constructorSignature, constructor);
}
public final void constructor(JavaVisibility visibility, String constructorSignature, Consumer<JavaBlock> constructor) {
addExpectedNewLine();
contents.constructor(visibility, constructorSignature, constructor);
addNewLine = true;
}
public final void publicConstructor(String constructorSignature, Consumer<JavaBlock> constructor) {
constructor(JavaVisibility.Public, constructorSignature, constructor);
}
public final void privateConstructor(String constructorSignature, Consumer<JavaBlock> constructor) {
constructor(JavaVisibility.Private, constructorSignature, constructor);
}
public final void packagePrivateConstructor(String constructorSignature, Consumer<JavaBlock> constructor) {
constructor(JavaVisibility.PackagePrivate, constructorSignature, constructor);
}
public final void publicConstructor(String constructorSignature, Consumer<JavaBlock> constructor) {
constructor(JavaVisibility.Public, constructorSignature, constructor);
}
public final void method(JavaVisibility visibility, List<JavaModifier> modifiers, String methodSignature, Consumer<JavaBlock> method) {
addExpectedNewLine();
contents.method(visibility, modifiers, methodSignature, method);
addNewLine = true;
}
public final void packagePrivateConstructor(String constructorSignature, Consumer<JavaBlock> constructor) {
constructor(JavaVisibility.PackagePrivate, constructorSignature, constructor);
}
public final void publicMethod(String methodSignature, Consumer<JavaBlock> method) {
method(JavaVisibility.Public, null, methodSignature, method);
}
public final void method(JavaVisibility visibility, List<JavaModifier> modifiers, String methodSignature, Consumer<JavaBlock> method) {
addExpectedNewLine();
contents.method(visibility, modifiers, methodSignature, method);
addNewLine = true;
}
public final void packagePrivateMethod(String methodSignature, Consumer<JavaBlock> method) {
method(JavaVisibility.PackagePrivate, null, methodSignature, method);
}
public final void publicMethod(String methodSignature, Consumer<JavaBlock> method) {
method(JavaVisibility.Public, null, methodSignature, method);
}
public final void privateMethod(String methodSignature, Consumer<JavaBlock> method) {
method(JavaVisibility.Private, null, methodSignature, method);
}
public final void packagePrivateMethod(String methodSignature, Consumer<JavaBlock> method) {
method(JavaVisibility.PackagePrivate, null, methodSignature, method);
}
public final void publicStaticMethod(String methodSignature, Consumer<JavaBlock> method) {
staticMethod(JavaVisibility.Public, methodSignature, method);
}
public final void privateMethod(String methodSignature, Consumer<JavaBlock> method) {
method(JavaVisibility.Private, null, methodSignature, method);
}
/**
* Adds a static method with a declared visibility to the class.
*
* @param visibility The visibility of the method.
* @param methodSignature The method signature.
* @param method The logic to generate the method.
*/
public final void staticMethod(JavaVisibility visibility, String methodSignature, Consumer<JavaBlock> method) {
Objects.requireNonNull(visibility, "'visibility' cannot be null.");
method(visibility, Collections.singletonList(JavaModifier.Static), methodSignature, method);
}
public final void publicStaticMethod(String methodSignature, Consumer<JavaBlock> method) {
staticMethod(JavaVisibility.Public, methodSignature, method);
}
public final void interfaceBlock(JavaVisibility visibility, String interfaceSignature, Consumer<JavaInterface> interfaceBlock) {
addExpectedNewLine();
contents.interfaceBlock(visibility, interfaceSignature, interfaceBlock);
addNewLine = true;
}
/**
* Adds a static method with a declared visibility to the class.
*
* @param visibility The visibility of the method.
* @param methodSignature The method signature.
* @param method The logic to generate the method.
*/
public final void staticMethod(JavaVisibility visibility, String methodSignature, Consumer<JavaBlock> method) {
Objects.requireNonNull(visibility, "'visibility' cannot be null.");
method(visibility, Collections.singletonList(JavaModifier.Static), methodSignature, method);
}
public final void publicInterface(String interfaceSignature, Consumer<JavaInterface> interfaceBlock) {
interfaceBlock(JavaVisibility.Public, interfaceSignature, interfaceBlock);
}
public final void interfaceBlock(JavaVisibility visibility, String interfaceSignature, Consumer<JavaInterface> interfaceBlock) {
addExpectedNewLine();
contents.interfaceBlock(visibility, interfaceSignature, interfaceBlock);
addNewLine = true;
}
public final void privateStaticFinalClass(String classSignature, Consumer<JavaClass> classBlock) {
staticFinalClass(JavaVisibility.Private, classSignature, classBlock);
}
public final void publicInterface(String interfaceSignature, Consumer<JavaInterface> interfaceBlock) {
interfaceBlock(JavaVisibility.Public, interfaceSignature, interfaceBlock);
}
public final void staticFinalClass(JavaVisibility visibility, String classSignature, Consumer<JavaClass> classBlock) {
addExpectedNewLine();
contents.classBlock(visibility, Arrays.asList(JavaModifier.Static, JavaModifier.Final), classSignature,
classBlock);
addNewLine = true;
}
public final void privateStaticFinalClass(String classSignature, Consumer<JavaClass> classBlock) {
staticFinalClass(JavaVisibility.Private, classSignature, classBlock);
}
public final void blockComment(String description) {
addExpectedNewLine();
contents.blockComment(description);
}
public final void staticFinalClass(JavaVisibility visibility, String classSignature, Consumer<JavaClass> classBlock) {
addExpectedNewLine();
contents.classBlock(visibility, Arrays.asList(JavaModifier.Static, JavaModifier.Final), classSignature,
classBlock);
addNewLine = true;
}
public final void lineComment(String description) {
addExpectedNewLine();
contents.lineComment(description);
}
public final void blockComment(String description) {
addExpectedNewLine();
contents.blockComment(description);
}
public final void blockComment(Consumer<JavaLineComment> commentAction) {
addExpectedNewLine();
contents.blockComment(commentAction);
}
public final void lineComment(String description) {
addExpectedNewLine();
contents.lineComment(description);
}
public final void javadocComment(String description) {
addExpectedNewLine();
contents.javadocComment(description);
}
public final void blockComment(Consumer<JavaLineComment> commentAction) {
addExpectedNewLine();
contents.blockComment(commentAction);
}
public final void javadocComment(Consumer<JavaJavadocComment> commentAction) {
addExpectedNewLine();
contents.javadocComment(commentAction);
}
public final void javadocComment(String description) {
addExpectedNewLine();
contents.javadocComment(description);
}
public final void annotation(String... annotations) {
addExpectedNewLine();
contents.annotation(annotations);
}
public final void javadocComment(Consumer<JavaJavadocComment> commentAction) {
addExpectedNewLine();
contents.javadocComment(commentAction);
}
public final void staticBlock(Consumer<JavaBlock> codeBlock) {
addExpectedNewLine();
contents.block("static", codeBlock);
}
public final void annotation(String... annotations) {
addExpectedNewLine();
contents.annotation(annotations);
}
public final void staticBlock(Consumer<JavaBlock> codeBlock) {
addExpectedNewLine();
contents.block("static", codeBlock);
}
}

Просмотреть файл

@ -47,360 +47,362 @@ import java.util.stream.Collectors;
public class ClientMethodExampleWriter {
private final Set<String> imports = new HashSet<>();
private final BiConsumer<JavaBlock, Boolean> methodBodyWriter;
private final Consumer<JavaBlock> responseAssertionWriter;
private final ModelExampleWriter.ExampleNodeModelInitializationVisitor nodeVisitor = new ModelExampleWriter.ExampleNodeModelInitializationVisitor();
private final Set<String> imports = new HashSet<>();
private final BiConsumer<JavaBlock, Boolean> methodBodyWriter;
private final Consumer<JavaBlock> responseAssertionWriter;
private final ModelExampleWriter.ExampleNodeModelInitializationVisitor nodeVisitor = new ModelExampleWriter.ExampleNodeModelInitializationVisitor();
public ClientMethodExampleWriter(ClientMethod method, String clientVarName, ProxyMethodExample proxyMethodExample){
public ClientMethodExampleWriter(ClientMethod method, String clientVarName, ProxyMethodExample proxyMethodExample){
List<MethodParameter> methodParameters = MethodUtil.getParameters(method, true);
List<ExampleNode> exampleNodes = methodParameters
.stream()
.map(methodParameter -> parseNodeFromParameter(method, proxyMethodExample, methodParameter))
.collect(Collectors.toList());
List<MethodParameter> methodParameters = MethodUtil.getParameters(method, true);
List<ExampleNode> exampleNodes = methodParameters
.stream()
.map(methodParameter -> parseNodeFromParameter(method, proxyMethodExample, methodParameter))
.collect(Collectors.toList());
String parameterInvocations = exampleNodes.stream()
.map(nodeVisitor::accept)
.collect(Collectors.joining(", "));
String parameterInvocations = exampleNodes.stream()
.map(nodeVisitor::accept)
.collect(Collectors.joining(", "));
// assertion
this.imports.add("org.junit.jupiter.api.Assertions");
imports.add(LongRunningOperationStatus.class.getName());
ClassType.HTTP_HEADER_NAME.addImportsTo(imports, false);
// assertion
this.imports.add("org.junit.jupiter.api.Assertions");
imports.add(LongRunningOperationStatus.class.getName());
ClassType.HTTP_HEADER_NAME.addImportsTo(imports, false);
method.getReturnValue().getType().addImportsTo(imports, false);
method.getReturnValue().getType().addImportsTo(imports, false);
methodBodyWriter = (methodBlock, isTestCode) -> {
StringBuilder methodInvocation = new StringBuilder();
methodBodyWriter = (methodBlock, isTestCode) -> {
StringBuilder methodInvocation = new StringBuilder();
if (method.getReturnValue().getType().asNullable() != ClassType.VOID) {
String assignment = String.format("%s %s = ", method.getReturnValue().getType(), "response");
methodInvocation.append(assignment);
}
if (method.getReturnValue().getType().asNullable() != ClassType.VOID) {
String assignment = String.format("%s %s = ", method.getReturnValue().getType(), "response");
methodInvocation.append(assignment);
}
String methodCall = String.format("%s.%s(%s)",
clientVarName,
method.getName(),
parameterInvocations);
if (isTestCode) {
if (method.getType() == ClientMethodType.LongRunningBeginSync) {
methodCall = "setPlaybackSyncPollerPollInterval(" + methodCall + ")";
} else if (method.getType() == ClientMethodType.LongRunningBeginAsync) {
methodCall = "setPlaybackPollerFluxPollInterval(" + methodCall + ")";
}
}
methodInvocation.append(methodCall).append(";");
methodBlock.line(methodInvocation.toString());
};
responseAssertionWriter = methodBlock -> {
ProxyMethodExample.Response response = proxyMethodExample.getPrimaryResponse();
if (response != null) {
IType returnType = method.getReturnValue().getType();
if (returnType instanceof GenericType) {
GenericType responseType = (GenericType) returnType;
if (SyncPoller.class.getSimpleName().equals(responseType.getName())) {
// SyncPoller<>
if (response.getStatusCode() / 100 == 2) {
methodBlock.line();
methodBlock.line("// response assertion");
// it should have a 202 leading to SUCCESSFULLY_COMPLETED
// but x-ms-examples usually does not include the final result
methodBlock.line("Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, response.waitForCompletion().getStatus());");
}
} else if (PagedIterable.class.getSimpleName().equals(responseType.getName())) {
// PagedIterable<>
methodBlock.line();
methodBlock.line("// response assertion");
// assert status code
methodBlock.line(String.format("Assertions.assertEquals(%1$s, response.iterableByPage().iterator().next().getStatusCode());", response.getStatusCode()));
// assert headers
response.getHttpHeaders().stream().forEach(header -> {
String expectedValueStr = ClassType.STRING.defaultValueExpression(header.getValue());
String keyStr = ClassType.STRING.defaultValueExpression(header.getName());
methodBlock.line(String.format("Assertions.assertEquals(%1$s, response.iterableByPage().iterator().next().getHeaders().get(HttpHeaderName.fromString(%2$s)).getValue());", expectedValueStr, keyStr));
});
// assert JSON of first item, or assert count=0
if (method.getProxyMethod().getResponseContentTypes() != null
&& method.getProxyMethod().getResponseContentTypes().contains(ContentType.APPLICATION_JSON)
&& responseType.getTypeArguments().length > 0
&& ClientModelUtil.isClientModel(responseType.getTypeArguments()[0])
&& method.getMethodPageDetails() != null
&& response.getBody() instanceof Map) {
Map<String, Object> bodyMap = (Map<String, Object>) response.getBody();
if (bodyMap.containsKey(method.getMethodPageDetails().getSerializedItemName())) {
Object items = bodyMap.get(method.getMethodPageDetails().getSerializedItemName());
if (items instanceof List) {
List<Object> itemArray = (List<Object>) items;
if (itemArray.isEmpty()) {
methodBlock.line("Assertions.assertEquals(0, response.stream().count());");
} else {
Object firstItem = itemArray.iterator().next();
methodBlock.line("%s firstItem = %s;", responseType.getTypeArguments()[0], "response.iterator().next()");
writeModelAssertion(methodBlock, nodeVisitor, responseType.getTypeArguments()[0], responseType.getTypeArguments()[0], firstItem, "firstItem", true);
}
}
}
}
}
} else if (ClassType.BOOLEAN.equals(returnType.asNullable()) && HttpMethod.HEAD.equals(method.getProxyMethod().getHttpMethod())) {
methodBlock.line();
methodBlock.line("// response assertion");
if (response.getStatusCode() == 200) {
methodBlock.line("Assertions.assertTrue(response);");
} else if (response.getStatusCode() == 404) {
methodBlock.line("Assertions.assertFalse(response)");
}
} else if (!ClassType.VOID.equals(returnType.asNullable())){
methodBlock.line();
methodBlock.line("// response assertion");
writeModelAssertion(methodBlock, nodeVisitor, returnType, returnType, response.getBody(), "response", true);
}
} else {
methodBlock.line();
methodBlock.line("// response assertion");
methodBlock.line("Assertions.assertNotNull(response);");
}
};
addNecessaryImports();
}
private void addNecessaryImports() {
// write dummy, allow nodeVisitor to collect all necessary imports
responseAssertionWriter.accept(new JavaBlock(new JavaFileContents()));
this.imports.addAll(nodeVisitor.getImports());
}
/**
* Write assertions for the given model and its example value.
*
* @param methodBlock the method block to write assertions to
* @param nodeVisitor node visitor for example values
* @param modelClientType client type of the model
* @param modelWireType wire type of the model
* @param modelValue example value of the model
* @param modelReference reference of the model that can be used to access the model in generated code
* @param rootModel whether the model is in the root of the response
*/
private void writeModelAssertion(JavaBlock methodBlock, ModelExampleWriter.ExampleNodeModelInitializationVisitor nodeVisitor,
IType modelClientType, IType modelWireType, Object modelValue, String modelReference, boolean rootModel) {
if (modelValue != null) {
modelClientType.addImportsTo(this.imports, false);
if (modelWireType != null) {
modelWireType.addImportsTo(this.imports, false);
}
if (isClientModel(modelClientType, modelValue)) {
methodBlock.line("Assertions.assertNotNull(%s);", modelReference);
// Client Model
ClassType modelClassType = (ClassType) modelClientType;
ClientModel clientModel = ClientModelUtil.getClientModel(modelClassType.getName());
if (clientModel.getProperties() != null) {
for (ClientModelProperty property : clientModel.getProperties()) {
String serializedName = property.getSerializedName();
Object propertyValue = ((Map) modelValue).get(serializedName);
if (propertyValue != null) {
if (rootModel) {
methodBlock.line("// verify property \"%s\"", property.getName());
}
String propertyGetter = String.format("%s.%s()", modelReference, property.getGetterName());
if (isClientModel(property.getClientType(), propertyValue) || isList(property.getClientType(), propertyValue)) {
String propertyReference = String.format("%s%s", modelReference, CodeNamer.toPascalCase(property.getName()));
methodBlock.line("%s %s = %s;", property.getClientType(), propertyReference, propertyGetter);
writeModelAssertion(methodBlock, nodeVisitor, property.getClientType(), property.getWireType(), propertyValue, propertyReference, false);
} else {
writeModelAssertion(methodBlock, nodeVisitor, property.getClientType(), property.getWireType(), propertyValue, propertyGetter, false);
}
}
}
}
} else if (isList(modelClientType, modelValue)) {
// List
List<Object> values = (List<Object>) modelValue;
if (values.size() > 0) {
ListType listType = (ListType) modelClientType;
IType elementType = listType.getElementType();
Object firstItemValue = values.iterator().next();
if (firstItemValue != null) {
String firstItemGetter = String.format("%s.iterator().next()", modelReference);
if (isClientModel(elementType, firstItemValue) || isList(elementType, firstItemValue)) {
String firstItemReference = String.format("%s%s", modelReference, "FirstItem");
methodBlock.line("%s %s = %s;", elementType, firstItemReference, firstItemGetter);
writeModelAssertion(methodBlock, nodeVisitor, elementType, elementType, values.iterator().next(), firstItemReference, rootModel);
} else {
writeModelAssertion(methodBlock, nodeVisitor, elementType, elementType, values.iterator().next(), firstItemGetter, rootModel);
}
}
} else {
methodBlock.line("Assertions.assertEquals(0, %s);", String.format("%s.size()", modelReference));
}
} else if (modelClientType instanceof PrimitiveType || modelClientType instanceof EnumType
|| ClassType.STRING.equals(modelClientType) || ClassType.URL.equals(modelClientType)
|| (modelClientType instanceof ClassType && ((ClassType) modelClientType).isBoxedType())) {
// simple models that can be compared by "Assertions.assertEquals()"
methodBlock.line(String.format(
"Assertions.assertEquals(%s, %s);",
nodeVisitor.accept(ModelExampleUtil.parseNode(modelClientType, modelWireType, modelValue)),
modelReference
));
} else {
methodBlock.line("Assertions.assertNotNull(%s);", modelReference);
}
String methodCall = String.format("%s.%s(%s)",
clientVarName,
method.getName(),
parameterInvocations);
if (isTestCode) {
if (method.getType() == ClientMethodType.LongRunningBeginSync) {
methodCall = "setPlaybackSyncPollerPollInterval(" + methodCall + ")";
} else if (method.getType() == ClientMethodType.LongRunningBeginAsync) {
methodCall = "setPlaybackPollerFluxPollInterval(" + methodCall + ")";
}
}
}
methodInvocation.append(methodCall).append(";");
private boolean isList(IType modelClientType, Object modelValue) {
return modelClientType instanceof ListType && modelValue instanceof List;
}
methodBlock.line(methodInvocation.toString());
};
responseAssertionWriter = methodBlock -> {
ProxyMethodExample.Response response = proxyMethodExample.getPrimaryResponse();
if (response != null) {
IType returnType = method.getReturnValue().getType();
if (returnType instanceof GenericType) {
GenericType responseType = (GenericType) returnType;
if (SyncPoller.class.getSimpleName().equals(responseType.getName())) {
// SyncPoller<>
private boolean isClientModel(IType modelClientType, Object modelValue) {
return modelClientType instanceof ClassType
&& ClientModelUtil.isClientModel(modelClientType)
&& modelValue instanceof Map;
}
if (response.getStatusCode() / 100 == 2) {
methodBlock.line();
methodBlock.line("// response assertion");
// it should have a 202 leading to SUCCESSFULLY_COMPLETED
// but x-ms-examples usually does not include the final result
methodBlock.line("Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, response.waitForCompletion().getStatus());");
}
} else if (PagedIterable.class.getSimpleName().equals(responseType.getName())) {
// PagedIterable<>
/**
* Parse example node from given parameter, taking into account parameter grouping.
*
* @param convenienceMethod the convenience method to generate example for
* @param proxyMethodExample the proxy method example
* @param methodParameter mapped convenience method parameter to protocol(proxy) method parameter
* @return example node
*/
private ExampleNode parseNodeFromParameter(ClientMethod convenienceMethod, ProxyMethodExample proxyMethodExample, MethodParameter methodParameter) {
if (isGroupingParameter(convenienceMethod, methodParameter)) {
// grouping, possible with flattening first
// group example values into a map
Map<String, Object> exampleValue = new HashMap<>();
for (MethodTransformationDetail detail : convenienceMethod.getMethodTransformationDetails()) {
for (ParameterMapping parameterMapping : detail.getParameterMappings()) {
if (parameterMapping.getOutputParameterPropertyName() != null) {
// this is a flattened property, so put flattening(real parameter) value
// output parameter's name is the "escaped reserved client method parameter name" of the real parameter's serialized name
// since flattened parameter is always in body, we can deal with that explicitly
ClientMethodParameter outputParameter = detail.getOutParameter();
Map<String, Object> flattenedParameterValue = getFlattenedBodyParameterExampleValue(proxyMethodExample, outputParameter);
if (flattenedParameterValue != null) {
exampleValue.putAll(flattenedParameterValue);
}
// since it's flattened property, all parameterMappings share the same outputParameter(real parameter)
// we only need to put example value once, which is the flattened(real) parameter's value
break;
} else {
// Group property's "serializedName" is the real parameter's "serializedName" on the wire.
// This implicit equivalence is defined in emitter and preserved in mapping client method.
String serializedParameterName = parameterMapping.getInputParameterProperty().getSerializedName();
ClientMethodParameter parameter = detail.getOutParameter();
exampleValue.put(serializedParameterName,
ModelExampleUtil.getParameterExampleValue(
proxyMethodExample, serializedParameterName, parameter.getRequestParameterLocation()));
}
methodBlock.line();
methodBlock.line("// response assertion");
// assert status code
methodBlock.line(String.format("Assertions.assertEquals(%1$s, response.iterableByPage().iterator().next().getStatusCode());", response.getStatusCode()));
// assert headers
response.getHttpHeaders().stream().forEach(header -> {
String expectedValueStr = ClassType.STRING.defaultValueExpression(header.getValue());
String keyStr = ClassType.STRING.defaultValueExpression(header.getName());
methodBlock.line(String.format("Assertions.assertEquals(%1$s, response.iterableByPage().iterator().next().getHeaders().get(HttpHeaderName.fromString(%2$s)).getValue());", expectedValueStr, keyStr));
});
// assert JSON of first item, or assert count=0
if (method.getProxyMethod().getResponseContentTypes() != null
&& method.getProxyMethod().getResponseContentTypes().contains(ContentType.APPLICATION_JSON)
&& responseType.getTypeArguments().length > 0
&& ClientModelUtil.isClientModel(responseType.getTypeArguments()[0])
&& method.getMethodPageDetails() != null
&& response.getBody() instanceof Map) {
Map<String, Object> bodyMap = (Map<String, Object>) response.getBody();
if (bodyMap.containsKey(method.getMethodPageDetails().getSerializedItemName())) {
Object items = bodyMap.get(method.getMethodPageDetails().getSerializedItemName());
if (items instanceof List) {
List<Object> itemArray = (List<Object>) items;
if (itemArray.isEmpty()) {
methodBlock.line("Assertions.assertEquals(0, response.stream().count());");
} else {
Object firstItem = itemArray.iterator().next();
methodBlock.line("%s firstItem = %s;", responseType.getTypeArguments()[0], "response.iterator().next()");
writeModelAssertion(methodBlock, nodeVisitor, responseType.getTypeArguments()[0], responseType.getTypeArguments()[0], firstItem, "firstItem", true);
}
}
}
}
IType type = methodParameter.getClientMethodParameter().getClientType();
IType wireType = methodParameter.getClientMethodParameter().getWireType();
return ModelExampleUtil.parseNode(type, wireType, exampleValue);
} else if (isFlattenParameter(convenienceMethod, methodParameter)) {
// flatten, no grouping
ClientMethodParameter outputParameter = convenienceMethod.getMethodTransformationDetails().iterator().next().getOutParameter();
Map<String, Object> realParameterValue = getFlattenedBodyParameterExampleValue(proxyMethodExample, outputParameter);
}
} else if (ClassType.BOOLEAN.equals(returnType.asNullable()) && HttpMethod.HEAD.equals(method.getProxyMethod().getHttpMethod())) {
methodBlock.line();
methodBlock.line("// response assertion");
if (response.getStatusCode() == 200) {
methodBlock.line("Assertions.assertTrue(response);");
} else if (response.getStatusCode() == 404) {
methodBlock.line("Assertions.assertFalse(response)");
}
} else if (!ClassType.VOID.equals(returnType.asNullable())){
methodBlock.line();
methodBlock.line("// response assertion");
writeModelAssertion(methodBlock, nodeVisitor, returnType, returnType, response.getBody(), "response", true);
}
} else {
methodBlock.line();
methodBlock.line("// response assertion");
methodBlock.line("Assertions.assertNotNull(response);");
}
};
IType type = methodParameter.getClientMethodParameter().getClientType();
IType wireType = methodParameter.getClientMethodParameter().getWireType();
addNecessaryImports();
}
ParameterMapping parameterMapping = convenienceMethod.getMethodTransformationDetails().iterator().next()
.getParameterMappings()
.stream()
.filter(mapping -> Objects.equals(mapping.getInputParameter().getName(), methodParameter.getClientMethodParameter().getName()))
.findFirst().orElse(null);
private void addNecessaryImports() {
// write dummy, allow nodeVisitor to collect all necessary imports
responseAssertionWriter.accept(new JavaBlock(new JavaFileContents()));
this.imports.addAll(nodeVisitor.getImports());
}
Object methodParameterValue = null;
if (realParameterValue != null && parameterMapping != null) {
methodParameterValue = realParameterValue.get(parameterMapping.getOutputParameterProperty().getSerializedName());
/**
* Write assertions for the given model and its example value.
*
* @param methodBlock the method block to write assertions to
* @param nodeVisitor node visitor for example values
* @param modelClientType client type of the model
* @param modelWireType wire type of the model
* @param modelValue example value of the model
* @param modelReference reference of the model that can be used to access the model in generated code
* @param rootModel whether the model is in the root of the response
*/
private void writeModelAssertion(JavaBlock methodBlock, ModelExampleWriter.ExampleNodeModelInitializationVisitor nodeVisitor,
IType modelClientType, IType modelWireType, Object modelValue, String modelReference, boolean rootModel) {
if (modelValue != null) {
modelClientType.addImportsTo(this.imports, false);
if (modelWireType != null) {
modelWireType.addImportsTo(this.imports, false);
}
if (isClientModel(modelClientType, modelValue)) {
methodBlock.line("Assertions.assertNotNull(%s);", modelReference);
// Client Model
ClassType modelClassType = (ClassType) modelClientType;
ClientModel clientModel = ClientModelUtil.getClientModel(modelClassType.getName());
if (clientModel.getProperties() != null) {
for (ClientModelProperty property : clientModel.getProperties()) {
String serializedName = property.getSerializedName();
Object propertyValue = ((Map) modelValue).get(serializedName);
if (propertyValue != null) {
if (rootModel) {
methodBlock.line("// verify property \"%s\"", property.getName());
}
String propertyGetter = String.format("%s.%s()", modelReference, property.getGetterName());
if (isClientModel(property.getClientType(), propertyValue) || isList(property.getClientType(), propertyValue)) {
String propertyReference = String.format("%s%s", modelReference, CodeNamer.toPascalCase(property.getName()));
methodBlock.line("%s %s = %s;", property.getClientType(), propertyReference, propertyGetter);
writeModelAssertion(methodBlock, nodeVisitor, property.getClientType(), property.getWireType(), propertyValue, propertyReference, false);
} else {
writeModelAssertion(methodBlock, nodeVisitor, property.getClientType(), property.getWireType(), propertyValue, propertyGetter, false);
}
}
return ModelExampleUtil.parseNode(type, wireType, methodParameterValue);
}
}
} else if (isList(modelClientType, modelValue)) {
// List
List<Object> values = (List<Object>) modelValue;
if (values.size() > 0) {
ListType listType = (ListType) modelClientType;
IType elementType = listType.getElementType();
Object firstItemValue = values.iterator().next();
if (firstItemValue != null) {
String firstItemGetter = String.format("%s.iterator().next()", modelReference);
if (isClientModel(elementType, firstItemValue) || isList(elementType, firstItemValue)) {
String firstItemReference = String.format("%s%s", modelReference, "FirstItem");
methodBlock.line("%s %s = %s;", elementType, firstItemReference, firstItemGetter);
writeModelAssertion(methodBlock, nodeVisitor, elementType, elementType, values.iterator().next(), firstItemReference, rootModel);
} else {
writeModelAssertion(methodBlock, nodeVisitor, elementType, elementType, values.iterator().next(), firstItemGetter, rootModel);
}
}
} else {
return ModelExampleUtil.parseNodeFromParameter(proxyMethodExample, methodParameter);
methodBlock.line("Assertions.assertEquals(0, %s);", String.format("%s.size()", modelReference));
}
} else if (modelClientType instanceof PrimitiveType || modelClientType instanceof EnumType
|| ClassType.STRING.equals(modelClientType) || ClassType.URL.equals(modelClientType)
|| (modelClientType instanceof ClassType && ((ClassType) modelClientType).isBoxedType())) {
// simple models that can be compared by "Assertions.assertEquals()"
methodBlock.line(String.format(
"Assertions.assertEquals(%s, %s);",
nodeVisitor.accept(ModelExampleUtil.parseNode(modelClientType, modelWireType, modelValue)),
modelReference
));
} else {
methodBlock.line("Assertions.assertNotNull(%s);", modelReference);
}
}
}
@SuppressWarnings("unchecked")
private Map<String, Object> getFlattenedBodyParameterExampleValue(ProxyMethodExample example, ClientMethodParameter clientMethodParameter) {
String clientMethodParameterName = clientMethodParameter.getName();
Function<String, ProxyMethodExample.ParameterValue> getParameterValue = (parameterSerializedName) -> example.getParameters().entrySet()
.stream().filter(
p -> CodeNamer.getEscapedReservedClientMethodParameterName(p.getKey())
.equalsIgnoreCase(parameterSerializedName))
.map(Map.Entry::getValue)
.findFirst()
.orElse(null);
ProxyMethodExample.ParameterValue parameterValue = getParameterValue.apply(clientMethodParameterName);
private boolean isList(IType modelClientType, Object modelValue) {
return modelClientType instanceof ListType && modelValue instanceof List;
}
if (parameterValue == null && clientMethodParameter.getRequestParameterLocation() == RequestParameterLocation.BODY && !"body".equalsIgnoreCase(clientMethodParameterName)) {
// fallback, "body" is commonly used in example JSON for request body
clientMethodParameterName = "body";
parameterValue = getParameterValue.apply(clientMethodParameterName);
private boolean isClientModel(IType modelClientType, Object modelValue) {
return modelClientType instanceof ClassType
&& ClientModelUtil.isClientModel(modelClientType)
&& modelValue instanceof Map;
}
/**
* Parse example node from given parameter, taking into account parameter grouping.
*
* @param convenienceMethod the convenience method to generate example for
* @param proxyMethodExample the proxy method example
* @param methodParameter mapped convenience method parameter to protocol(proxy) method parameter
* @return example node
*/
private ExampleNode parseNodeFromParameter(ClientMethod convenienceMethod, ProxyMethodExample proxyMethodExample, MethodParameter methodParameter) {
ExampleNode node;
if (isGroupingParameter(convenienceMethod, methodParameter)) {
// grouping, possible with flattening first
// group example values into a map
Map<String, Object> exampleValue = new HashMap<>();
for (MethodTransformationDetail detail : convenienceMethod.getMethodTransformationDetails()) {
for (ParameterMapping parameterMapping : detail.getParameterMappings()) {
if (parameterMapping.getOutputParameterPropertyName() != null) {
// this is a flattened property, so put flattening(real parameter) value
// output parameter's name is the "escaped reserved client method parameter name" of the real parameter's serialized name
// since flattened parameter is always in body, we can deal with that explicitly
ClientMethodParameter outputParameter = detail.getOutParameter();
Map<String, Object> flattenedParameterValue = getFlattenedBodyParameterExampleValue(proxyMethodExample, outputParameter);
if (flattenedParameterValue != null) {
exampleValue.putAll(flattenedParameterValue);
}
// since it's flattened property, all parameterMappings share the same outputParameter(real parameter)
// we only need to put example value once, which is the flattened(real) parameter's value
break;
} else {
// Group property's "serializedName" is the real parameter's "serializedName" on the wire.
// This implicit equivalence is defined in emitter and preserved in mapping client method.
String serializedParameterName = parameterMapping.getInputParameterProperty().getSerializedName();
ClientMethodParameter parameter = detail.getOutParameter();
exampleValue.put(serializedParameterName,
ModelExampleUtil.getParameterExampleValue(
proxyMethodExample, serializedParameterName, parameter.getRequestParameterLocation()));
}
}
}
IType type = methodParameter.getClientMethodParameter().getClientType();
IType wireType = methodParameter.getClientMethodParameter().getWireType();
node = ModelExampleUtil.parseNode(type, wireType, exampleValue);
} else if (isFlattenParameter(convenienceMethod, methodParameter)) {
// flatten, no grouping
ClientMethodParameter outputParameter = convenienceMethod.getMethodTransformationDetails().iterator().next().getOutParameter();
Map<String, Object> realParameterValue = getFlattenedBodyParameterExampleValue(proxyMethodExample, outputParameter);
return parameterValue == null ? null : (Map<String, Object>) parameterValue.getObjectValue();
IType type = methodParameter.getClientMethodParameter().getClientType();
IType wireType = methodParameter.getClientMethodParameter().getWireType();
ParameterMapping parameterMapping = convenienceMethod.getMethodTransformationDetails().iterator().next()
.getParameterMappings()
.stream()
.filter(mapping -> Objects.equals(mapping.getInputParameter().getName(), methodParameter.getClientMethodParameter().getName()))
.findFirst().orElse(null);
Object methodParameterValue = null;
if (realParameterValue != null && parameterMapping != null) {
methodParameterValue = realParameterValue.get(parameterMapping.getOutputParameterProperty().getSerializedName());
}
node = ModelExampleUtil.parseNode(type, wireType, methodParameterValue);
} else {
node = ModelExampleUtil.parseNodeFromParameter(proxyMethodExample, methodParameter);
}
return node;
}
@SuppressWarnings("unchecked")
private Map<String, Object> getFlattenedBodyParameterExampleValue(ProxyMethodExample example, ClientMethodParameter clientMethodParameter) {
String clientMethodParameterName = clientMethodParameter.getName();
Function<String, ProxyMethodExample.ParameterValue> getParameterValue = (parameterSerializedName) -> example.getParameters().entrySet()
.stream().filter(
p -> CodeNamer.getEscapedReservedClientMethodParameterName(p.getKey())
.equalsIgnoreCase(parameterSerializedName))
.map(Map.Entry::getValue)
.findFirst()
.orElse(null);
ProxyMethodExample.ParameterValue parameterValue = getParameterValue.apply(clientMethodParameterName);
if (parameterValue == null && clientMethodParameter.getRequestParameterLocation() == RequestParameterLocation.BODY && !"body".equalsIgnoreCase(clientMethodParameterName)) {
// fallback, "body" is commonly used in example JSON for request body
clientMethodParameterName = "body";
parameterValue = getParameterValue.apply(clientMethodParameterName);
}
private boolean isGroupingParameter(ClientMethod convenienceMethod, MethodParameter methodParameter) {
List<MethodTransformationDetail> details = convenienceMethod.getMethodTransformationDetails();
if (CoreUtils.isNullOrEmpty(details) || details.size() <= 1) {
return false;
}
return parameterValue == null ? null : (Map<String, Object>) parameterValue.getObjectValue();
}
return details.stream().allMatch(
detail ->
!CoreUtils.isNullOrEmpty(detail.getParameterMappings())
&& detail.getOutParameter() != null
&&
// same name
detail.getParameterMappings()
.stream()
.allMatch(mapping -> Objects.equals(
mapping.getInputParameter().getName(),
methodParameter.getClientMethodParameter().getName()))
);
private boolean isGroupingParameter(ClientMethod convenienceMethod, MethodParameter methodParameter) {
List<MethodTransformationDetail> details = convenienceMethod.getMethodTransformationDetails();
if (CoreUtils.isNullOrEmpty(details) || details.size() <= 1) {
return false;
}
private boolean isFlattenParameter(ClientMethod convenienceMethod, MethodParameter methodParameter) {
List<MethodTransformationDetail> details = convenienceMethod.getMethodTransformationDetails();
if (CoreUtils.isNullOrEmpty(details) || details.size() != 1) {
return false;
}
return details.stream().anyMatch(
detail ->
!CoreUtils.isNullOrEmpty(detail.getParameterMappings())
&& detail.getOutParameter() != null
&& detail.getParameterMappings().stream()
.allMatch(mapping -> mapping.getOutputParameterPropertyName() != null
&& mapping.getInputParameterProperty() == null)
&& detail.getParameterMappings()
.stream()
.anyMatch(mapping -> Objects.equals(methodParameter.getClientMethodParameter().getName(), mapping.getInputParameter().getName()))
);
}
return details.stream().allMatch(
detail ->
!CoreUtils.isNullOrEmpty(detail.getParameterMappings())
&& detail.getOutParameter() != null
&&
// same name
detail.getParameterMappings()
.stream()
.allMatch(mapping -> Objects.equals(
mapping.getInputParameter().getName(),
methodParameter.getClientMethodParameter().getName()))
);
}
public Set<String> getImports() {
return new HashSet<>(this.imports);
private boolean isFlattenParameter(ClientMethod convenienceMethod, MethodParameter methodParameter) {
List<MethodTransformationDetail> details = convenienceMethod.getMethodTransformationDetails();
if (CoreUtils.isNullOrEmpty(details) || details.size() != 1) {
return false;
}
return details.stream().anyMatch(
detail ->
!CoreUtils.isNullOrEmpty(detail.getParameterMappings())
&& detail.getOutParameter() != null
&& detail.getParameterMappings().stream()
.allMatch(mapping -> mapping.getOutputParameterPropertyName() != null
&& mapping.getInputParameterProperty() == null)
&& detail.getParameterMappings()
.stream()
.anyMatch(mapping -> Objects.equals(methodParameter.getClientMethodParameter().getName(), mapping.getInputParameter().getName()))
);
}
public void writeClientMethodInvocation(JavaBlock javaBlock, boolean isTestCode) {
methodBodyWriter.accept(javaBlock, isTestCode);
}
public Set<String> getImports() {
return new HashSet<>(this.imports);
}
public Set<ExampleHelperFeature> getHelperFeatures() {
return new HashSet<>(nodeVisitor.getHelperFeatures());
}
public void writeClientMethodInvocation(JavaBlock javaBlock, boolean isTestCode) {
methodBodyWriter.accept(javaBlock, isTestCode);
}
public void writeAssertion(JavaBlock methodBlock) {
responseAssertionWriter.accept(methodBlock);
}
public Set<ExampleHelperFeature> getHelperFeatures() {
return new HashSet<>(nodeVisitor.getHelperFeatures());
}
public void writeAssertion(JavaBlock methodBlock) {
responseAssertionWriter.accept(methodBlock);
}
}

Просмотреть файл

@ -46,284 +46,303 @@ import java.util.stream.Stream;
public class ModelExampleWriter {
private static final Logger LOGGER = new PluginLogger(Javagen.getPluginInstance(), ModelExampleWriter.class);
private static final Logger LOGGER = new PluginLogger(Javagen.getPluginInstance(), ModelExampleWriter.class);
private final Set<String> imports = new HashSet<>();
private final Consumer<JavaBlock> assertionWriter;
private final ExampleNodeModelInitializationVisitor modelInitializationVisitor =
new ExampleNodeModelInitializationVisitor();
private final String modelInitializationCode;
public ModelExampleWriter(ExampleNode exampleNode, String modelVariableName) {
this.imports.add("org.junit.jupiter.api.Assertions");
ExampleNodeAssertionVisitor assertionVisitor = new ExampleNodeAssertionVisitor();
assertionVisitor.accept(exampleNode, modelVariableName);
imports.addAll(assertionVisitor.imports);
this.assertionWriter = methodBlock -> {
assertionVisitor.assertions.forEach(methodBlock::line);
};
modelInitializationCode = modelInitializationVisitor.accept(exampleNode);
imports.addAll(modelInitializationVisitor.getImports());
}
public Set<String> getImports() {
return imports;
}
public Set<ExampleHelperFeature> getHelperFeatures() {
return modelInitializationVisitor.getHelperFeatures();
}
public void writeAssertion(JavaBlock methodBlock) {
assertionWriter.accept(methodBlock);
}
public String getModelInitializationCode() {
return modelInitializationCode;
}
public static void writeMapOfMethod(JavaClass classBlock) {
classBlock.lineComment("Use \"Map.of\" if available");
classBlock.annotation("SuppressWarnings(\"unchecked\")");
classBlock.method(JavaVisibility.Private, Collections.singletonList(JavaModifier.Static), "<T> Map<String, T> mapOf(Object... inputs)", methodBlock -> {
methodBlock.line("Map<String, T> map = new HashMap<>();");
methodBlock.line("for (int i = 0; i < inputs.length; i += 2) {");
methodBlock.indent(() -> {
methodBlock.line("String key = (String) inputs[i];");
methodBlock.line("T value = (T) inputs[i + 1];");
methodBlock.line("map.put(key, value);");
});
methodBlock.line("}");
methodBlock.line("return map;");
});
}
public static class ExampleNodeAssertionVisitor {
private final Set<String> imports = new HashSet<>();
private final Consumer<JavaBlock> assertionWriter;
private final ExampleNodeModelInitializationVisitor modelInitializationVisitor =
new ExampleNodeModelInitializationVisitor();
private final String modelInitializationCode;
private final List<String> assertions = new ArrayList<>();
public ModelExampleWriter(ExampleNode exampleNode, String modelVariableName) {
this.imports.add("org.junit.jupiter.api.Assertions");
private void addEqualsAssertion(String expected, String code) {
assertions.add(String.format("Assertions.assertEquals(%1$s, %2$s);", expected, code));
}
ExampleNodeAssertionVisitor assertionVisitor = new ExampleNodeAssertionVisitor();
assertionVisitor.accept(exampleNode, modelVariableName);
imports.addAll(assertionVisitor.imports);
public void accept(ExampleNode node, String getterCode) {
if (node instanceof LiteralNode) {
node.getClientType().addImportsTo(imports, false);
this.assertionWriter = methodBlock -> {
assertionVisitor.assertions.forEach(methodBlock::line);
};
addEqualsAssertion(
node.getClientType().defaultValueExpression(((LiteralNode) node).getLiteralsValue()),
getterCode);
} else if (node instanceof ObjectNode) {
// additionalProperties
} else if (node instanceof ListNode) {
if (!node.getChildNodes().isEmpty()) {
node = node.getChildNodes().get(0);
getterCode += ".get(0)";
accept(node, getterCode);
}
} else if (node instanceof MapNode) {
if (!node.getChildNodes().isEmpty()) {
String key = ((MapNode) node).getKeys().get(0);
node = node.getChildNodes().get(0);
getterCode += String.format(".get(%s)", ClassType.STRING.defaultValueExpression(key));
accept(node, getterCode);
}
} else if (node instanceof ClientModelNode) {
ClientModelNode clientModelNode = ((ClientModelNode) node);
modelInitializationCode = modelInitializationVisitor.accept(exampleNode);
imports.addAll(modelInitializationVisitor.getImports());
ClientModel model = clientModelNode.getClientModel();
imports.add(model.getFullName());
for (ExampleNode childNode : node.getChildNodes()) {
ModelProperty modelProperty = clientModelNode.getClientModelProperties().get(childNode);
String childGetterCode = getterCode + String.format(".%s()", modelProperty.getGetterName());
accept(childNode, childGetterCode);
}
}
}
public Set<String> getImports() {
return imports;
return imports;
}
public List<String> getAssertions() {
return assertions;
}
}
public static class ExampleNodeModelInitializationVisitor {
protected final Set<String> imports = new HashSet<>();
protected final Set<ExampleHelperFeature> helperFeatures = new HashSet<>();
/**
* Extension to write code for deserialize JSON String to Object.
* @param jsonStr the JSON String.
*/
protected String codeDeserializeJsonString(String jsonStr) {
imports.add(com.azure.core.util.serializer.JacksonAdapter.class.getName());
imports.add(com.azure.core.util.serializer.SerializerEncoding.class.getName());
return String.format("JacksonAdapter.createDefaultSerializerAdapter().deserialize(%s, Object.class, SerializerEncoding.JSON)",
ClassType.STRING.defaultValueExpression(jsonStr));
}
public Set<String> getImports() {
if (helperFeatures.contains(ExampleHelperFeature.ThrowsIOException)) {
imports.add(java.io.IOException.class.getName());
}
return imports;
}
public Set<ExampleHelperFeature> getHelperFeatures() {
return modelInitializationVisitor.getHelperFeatures();
return helperFeatures;
}
public void writeAssertion(JavaBlock methodBlock) {
assertionWriter.accept(methodBlock);
}
public String getModelInitializationCode() {
return modelInitializationCode;
}
public static void writeMapOfMethod(JavaClass classBlock) {
classBlock.lineComment("Use \"Map.of\" if available");
classBlock.annotation("SuppressWarnings(\"unchecked\")");
classBlock.method(JavaVisibility.Private, Collections.singletonList(JavaModifier.Static), "<T> Map<String, T> mapOf(Object... inputs)", methodBlock -> {
methodBlock.line("Map<String, T> map = new HashMap<>();");
methodBlock.line("for (int i = 0; i < inputs.length; i += 2) {");
methodBlock.indent(() -> {
methodBlock.line("String key = (String) inputs[i];");
methodBlock.line("T value = (T) inputs[i + 1];");
methodBlock.line("map.put(key, value);");
});
methodBlock.line("}");
methodBlock.line("return map;");
});
}
public static class ExampleNodeAssertionVisitor {
private final Set<String> imports = new HashSet<>();
private final List<String> assertions = new ArrayList<>();
private void addEqualsAssertion(String expected, String code) {
assertions.add(String.format("Assertions.assertEquals(%1$s, %2$s);", expected, code));
public String accept(ExampleNode node) {
if (node instanceof LiteralNode) {
if (node.getClientType() != ClassType.CONTEXT) {
node.getClientType().addImportsTo(imports, false);
}
public void accept(ExampleNode node, String getterCode) {
if (node instanceof LiteralNode) {
node.getClientType().addImportsTo(imports, false);
if (node.getClientType() == ClassType.URL) {
helperFeatures.add(ExampleHelperFeature.ThrowsIOException); // MalformedURLException from URL ctor
}
addEqualsAssertion(
node.getClientType().defaultValueExpression(((LiteralNode) node).getLiteralsValue()),
getterCode);
} else if (node instanceof ObjectNode) {
// additionalProperties
} else if (node instanceof ListNode) {
if (!node.getChildNodes().isEmpty()) {
node = node.getChildNodes().get(0);
getterCode += ".get(0)";
accept(node, getterCode);
}
} else if (node instanceof MapNode) {
if (!node.getChildNodes().isEmpty()) {
String key = ((MapNode) node).getKeys().get(0);
node = node.getChildNodes().get(0);
getterCode += String.format(".get(%s)", ClassType.STRING.defaultValueExpression(key));
accept(node, getterCode);
}
} else if (node instanceof ClientModelNode) {
ClientModelNode clientModelNode = ((ClientModelNode) node);
String literalValue = ((LiteralNode) node).getLiteralsValue();
if (literalValue == null) {
if (node.getClientType() instanceof PrimitiveType) {
return node.getClientType().defaultValueExpression();
} else {
return "null";
}
}
ClientModel model = clientModelNode.getClientModel();
return node.getClientType().defaultValueExpression(literalValue);
} else if (node instanceof ObjectNode) {
IType simpleType = null;
if (node.getObjectValue() instanceof Integer) {
simpleType = PrimitiveType.INT;
} else if (node.getObjectValue() instanceof Long) {
simpleType = PrimitiveType.LONG;
} else if (node.getObjectValue() instanceof Float) {
simpleType = PrimitiveType.FLOAT;
} else if (node.getObjectValue() instanceof Double) {
simpleType = PrimitiveType.DOUBLE;
} else if (node.getObjectValue() instanceof Boolean) {
simpleType = PrimitiveType.BOOLEAN;
} else if (node.getObjectValue() instanceof String) {
simpleType = ClassType.STRING;
}
imports.add(model.getFullName());
if (simpleType != null) {
return simpleType.defaultValueExpression(node.getObjectValue().toString());
} else {
helperFeatures.add(ExampleHelperFeature.ThrowsIOException);
for (ExampleNode childNode : node.getChildNodes()) {
ModelProperty modelProperty = clientModelNode.getClientModelProperties().get(childNode);
String childGetterCode = getterCode + String.format(".%s()", modelProperty.getGetterName());
accept(childNode, childGetterCode);
}
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) {
jsonWriter.writeUntyped(node.getObjectValue()).flush();
return codeDeserializeJsonString(outputStream.toString(StandardCharsets.UTF_8));
} catch (IOException e) {
LOGGER.error("Failed to write JSON {}", node.getObjectValue());
throw new IllegalStateException(e);
}
}
} else if (node instanceof ListNode) {
imports.add(java.util.Arrays.class.getName());
StringBuilder builder = new StringBuilder();
// Arrays.asList(...)
builder.append("Arrays.asList(")
.append(node.getChildNodes().stream().map(this::accept).collect(Collectors.joining(", ")))
.append(")");
return builder.toString();
} else if (node instanceof MapNode) {
imports.add(java.util.Map.class.getName());
imports.add(java.util.HashMap.class.getName());
helperFeatures.add(ExampleHelperFeature.MapOfMethod);
List<String> keys = ((MapNode) node).getKeys();
StringBuilder builder = new StringBuilder();
// mapOf(...)
// similar to Map.of in Java 9
builder.append("mapOf(");
for (int i = 0; i < keys.size(); ++i) {
if (i != 0) {
builder.append(", ");
}
String key = keys.get(i);
ExampleNode elementNode = node.getChildNodes().get(i);
builder.append(ClassType.STRING.defaultValueExpression(key))
.append(", ")
.append(this.accept(elementNode));
}
builder.append(")");
return builder.toString();
} else if (node instanceof ClientModelNode) {
ClientModelNode clientModelNode = ((ClientModelNode) node);
ClientModel model = clientModelNode.getClientModel();
imports.add(model.getFullName());
StringBuilder builder = new StringBuilder();
if (JavaSettings.getInstance().isRequiredFieldsAsConstructorArgs()) {
List<ClientModelProperty> requiredParentProperties = ClientModelUtil.getRequiredWritableParentProperties(model);
List<ClientModelProperty> requiredProperties = model.getProperties().stream()
.filter(ClientModelProperty::isRequired)
.filter(property -> !property.isConstant() && !property.isReadOnly())
.collect(Collectors.toList());
List<ModelProperty> properties = Stream.concat(
requiredParentProperties.stream(), requiredProperties.stream())
.map(ModelProperty::ofClientModelProperty)
.collect(Collectors.toList());
Map<ModelProperty, Integer> ctorPosition = new HashMap<>();
for (int i = 0; i < properties.size(); ++i) {
ctorPosition.put(properties.get(i), i);
}
List<String> initAtCtors = new ArrayList<>(Collections.nCopies(properties.size(), null));
List<String> initAtSetters = new ArrayList<>();
for (ExampleNode childNode : node.getChildNodes()) {
ModelProperty modelProperty = clientModelNode.getClientModelProperties().get(childNode);
if (ctorPosition.containsKey(modelProperty)) {
initAtCtors.set(ctorPosition.get(modelProperty), this.accept(childNode));
} else {
// .setProperty(...)
initAtSetters.add(String.format(".%1$s(%2$s)", modelProperty.getSetterName(), this.accept(childNode)));
}
}
public Set<String> getImports() {
return imports;
}
public List<String> getAssertions() {
return assertions;
}
}
public static class ExampleNodeModelInitializationVisitor {
protected final Set<String> imports = new HashSet<>();
protected final Set<ExampleHelperFeature> helperFeatures = new HashSet<>();
/**
* Extension to write code for deserialize JSON String to Object.
* @param jsonStr the JSON String.
*/
protected String codeDeserializeJsonString(String jsonStr) {
imports.add(com.azure.core.util.serializer.JacksonAdapter.class.getName());
imports.add(com.azure.core.util.serializer.SerializerEncoding.class.getName());
return String.format("JacksonAdapter.createDefaultSerializerAdapter().deserialize(%s, Object.class, SerializerEncoding.JSON)",
ClassType.STRING.defaultValueExpression(jsonStr));
}
public Set<String> getImports() {
if (helperFeatures.contains(ExampleHelperFeature.ThrowsIOException)) {
imports.add(java.io.IOException.class.getName());
}
for (int i = 0; i < properties.size(); ++i) {
String ctorParameterValue = initAtCtors.get(i);
if (ctorParameterValue == null) { // not present, due to missing required property
if (properties.get(i).getClientType() instanceof PrimitiveType) {
initAtCtors.set(i, properties.get(i).getClientType().defaultValueExpression());
} else {
initAtCtors.set(i, "null");
}
}
return imports;
}
public Set<ExampleHelperFeature> getHelperFeatures() {
return helperFeatures;
}
public String accept(ExampleNode node) {
if (node instanceof LiteralNode) {
if (node.getClientType() != ClassType.CONTEXT) {
node.getClientType().addImportsTo(imports, false);
}
if (node.getClientType() == ClassType.URL) {
helperFeatures.add(ExampleHelperFeature.ThrowsIOException); // MalformedURLException from URL ctor
}
return node.getClientType().defaultValueExpression(((LiteralNode) node).getLiteralsValue());
} else if (node instanceof ObjectNode) {
IType simpleType = null;
if (node.getObjectValue() instanceof Integer) {
simpleType = PrimitiveType.INT;
} else if (node.getObjectValue() instanceof Long) {
simpleType = PrimitiveType.LONG;
} else if (node.getObjectValue() instanceof Float) {
simpleType = PrimitiveType.FLOAT;
} else if (node.getObjectValue() instanceof Double) {
simpleType = PrimitiveType.DOUBLE;
} else if (node.getObjectValue() instanceof Boolean) {
simpleType = PrimitiveType.BOOLEAN;
} else if (node.getObjectValue() instanceof String) {
simpleType = ClassType.STRING;
}
if (simpleType != null) {
return simpleType.defaultValueExpression(node.getObjectValue().toString());
} else {
helperFeatures.add(ExampleHelperFeature.ThrowsIOException);
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) {
jsonWriter.writeUntyped(node.getObjectValue()).flush();
return codeDeserializeJsonString(outputStream.toString(StandardCharsets.UTF_8));
} catch (IOException e) {
LOGGER.error("Failed to write JSON {}", node.getObjectValue());
throw new IllegalStateException(e);
}
}
} else if (node instanceof ListNode) {
imports.add(java.util.Arrays.class.getName());
StringBuilder builder = new StringBuilder();
// Arrays.asList(...)
builder.append("Arrays.asList(")
.append(node.getChildNodes().stream().map(this::accept).collect(Collectors.joining(", ")))
.append(")");
return builder.toString();
} else if (node instanceof MapNode) {
imports.add(java.util.Map.class.getName());
imports.add(java.util.HashMap.class.getName());
helperFeatures.add(ExampleHelperFeature.MapOfMethod);
List<String> keys = ((MapNode) node).getKeys();
StringBuilder builder = new StringBuilder();
// mapOf(...)
// similar to Map.of in Java 9
builder.append("mapOf(");
for (int i = 0; i < keys.size(); ++i) {
if (i != 0) {
builder.append(", ");
}
String key = keys.get(i);
ExampleNode elementNode = node.getChildNodes().get(i);
builder.append(ClassType.STRING.defaultValueExpression(key))
.append(", ")
.append(this.accept(elementNode));
}
builder.append(")");
return builder.toString();
} else if (node instanceof ClientModelNode) {
ClientModelNode clientModelNode = ((ClientModelNode) node);
ClientModel model = clientModelNode.getClientModel();
imports.add(model.getFullName());
StringBuilder builder = new StringBuilder();
if (JavaSettings.getInstance().isRequiredFieldsAsConstructorArgs()) {
List<ClientModelProperty> requiredParentProperties = ClientModelUtil.getRequiredWritableParentProperties(model);
List<ClientModelProperty> requiredProperties = model.getProperties().stream()
.filter(ClientModelProperty::isRequired)
.filter(property -> !property.isConstant() && !property.isReadOnly())
.collect(Collectors.toList());
List<ModelProperty> properties = Stream.concat(
requiredParentProperties.stream(), requiredProperties.stream())
.map(ModelProperty::ofClientModelProperty)
.collect(Collectors.toList());
Map<ModelProperty, Integer> ctorPosition = new HashMap<>();
for (int i = 0; i < properties.size(); ++i) {
ctorPosition.put(properties.get(i), i);
}
List<String> initAtCtors = new ArrayList<>(Collections.nCopies(properties.size(), ""));
List<String> initAtSetters = new ArrayList<>();
for (ExampleNode childNode : node.getChildNodes()) {
ModelProperty modelProperty = clientModelNode.getClientModelProperties().get(childNode);
if (ctorPosition.containsKey(modelProperty)) {
initAtCtors.set(ctorPosition.get(modelProperty), this.accept(childNode));
} else {
// .setProperty(...)
initAtSetters.add(String.format(".%1$s(%2$s)", modelProperty.getSetterName(), this.accept(childNode)));
}
}
// model constructor
builder.append("new ").append(model.getName())
.append("(").append(String.join(", ", initAtCtors)).append(")");
// setters
initAtSetters.forEach(builder::append);
} else {
// model with setters
builder.append("new ").append(model.getName()).append("()");
for (ExampleNode childNode : node.getChildNodes()) {
ModelProperty modelProperty = clientModelNode.getClientModelProperties().get(childNode);
// .setProperty(...)
builder.append(".").append(modelProperty.getSetterName())
.append("(").append(this.accept(childNode)).append(")");
}
}
return builder.toString();
} else if (node instanceof BinaryDataNode) {
this.imports.add(com.azure.core.util.BinaryData.class.getName());
this.imports.add(java.nio.charset.StandardCharsets.class.getName());
return binaryDataNodeExpression((BinaryDataNode) node);
}
return null;
}
// model constructor
builder.append("new ").append(model.getName())
.append("(").append(String.join(", ", initAtCtors)).append(")");
// setters
initAtSetters.forEach(builder::append);
} else {
// model with setters
builder.append("new ").append(model.getName()).append("()");
for (ExampleNode childNode : node.getChildNodes()) {
ModelProperty modelProperty = clientModelNode.getClientModelProperties().get(childNode);
// .setProperty(...)
builder.append(".").append(modelProperty.getSetterName())
.append("(").append(this.accept(childNode)).append(")");
}
}
return builder.toString();
} else if (node instanceof BinaryDataNode) {
this.imports.add(com.azure.core.util.BinaryData.class.getName());
this.imports.add(java.nio.charset.StandardCharsets.class.getName());
return binaryDataNodeExpression((BinaryDataNode) node);
}
return null;
}
}
private static String binaryDataNodeExpression(BinaryDataNode binaryDataNode) {
return String.format("BinaryData.fromBytes(\"%s\".getBytes(StandardCharsets.UTF_8))", TemplateUtil.escapeString(binaryDataNode.getExampleValue()));
}
private static String binaryDataNodeExpression(BinaryDataNode binaryDataNode) {
return String.format("BinaryData.fromBytes(\"%s\".getBytes(StandardCharsets.UTF_8))", TemplateUtil.escapeString(binaryDataNode.getExampleValue()));
}
}

Просмотреть файл

@ -41,420 +41,420 @@ import java.util.stream.Collectors;
public class ModelExampleUtil {
private static final Logger LOGGER = new PluginLogger(Javagen.getPluginInstance(), ModelExampleUtil.class);
private static final Logger LOGGER = new PluginLogger(Javagen.getPluginInstance(), ModelExampleUtil.class);
/**
* Parse the type (client model or others) with JSON object to tree of ExampleNode.
*
* @param type the client type, wire type is assumed to be same
* @param objectValue the JSON object
* @return the tree of ExampleNode
*/
public static ExampleNode parseNode(IType type, Object objectValue) {
return parseNode(type, type, objectValue);
}
/**
* Parse the type (client model or others) with JSON object to tree of ExampleNode.
*
* @param type the client type, wire type is assumed to be same
* @param objectValue the JSON object
* @return the tree of ExampleNode
*/
public static ExampleNode parseNode(IType type, Object objectValue) {
return parseNode(type, type, objectValue);
}
/**
* Parse the type (client model or others) with JSON object to tree of ExampleNode.
*
* @param type the client type
* @param wireType the wire type (the related but different type used in JSON, e.g. DateTimeRfc1123 for OffsetDateTime)
* @param objectValue the JSON object
* @return the tree of ExampleNode
*/
@SuppressWarnings("unchecked")
public static ExampleNode parseNode(IType type, IType wireType, Object objectValue) {
ExampleNode node;
if (type instanceof ListType) {
IType elementType = ((ListType) type).getElementType();
if (objectValue instanceof List) {
ListNode listNode = new ListNode(elementType, objectValue);
node = listNode;
/**
* Parse the type (client model or others) with JSON object to tree of ExampleNode.
*
* @param type the client type
* @param wireType the wire type (the related but different type used in JSON, e.g. DateTimeRfc1123 for OffsetDateTime)
* @param objectValue the JSON object
* @return the tree of ExampleNode
*/
@SuppressWarnings("unchecked")
public static ExampleNode parseNode(IType type, IType wireType, Object objectValue) {
ExampleNode node;
if (type instanceof ListType) {
IType elementType = ((ListType) type).getElementType();
if (objectValue instanceof List) {
ListNode listNode = new ListNode(elementType, objectValue);
node = listNode;
List<Object> elements = (List<Object>) objectValue;
for (Object childObjectValue : elements) {
ExampleNode childNode = parseNode(elementType, childObjectValue);
node.getChildNodes().add(childNode);
}
List<Object> elements = (List<Object>) objectValue;
for (Object childObjectValue : elements) {
ExampleNode childNode = parseNode(elementType, childObjectValue);
node.getChildNodes().add(childNode);
}
} else {
LOGGER.error("Example value is not List type: {}", objectValue);
node = new ListNode(elementType, null);
}
} else if (type instanceof MapType) {
IType elementType = ((MapType) type).getValueType();
if (objectValue instanceof Map) {
MapNode mapNode = new MapNode(elementType, objectValue);
node = mapNode;
Map<String, Object> dict = (Map<String, Object>) objectValue;
for (Map.Entry<String, Object> entry : dict.entrySet()) {
Object value = entry.getValue();
// redact possible credential
if (elementType == ClassType.STRING && entry.getValue() instanceof String) {
value = ModelTestCaseUtil.redactStringValue(Collections.singletonList(entry.getKey()), (String) value);
}
ExampleNode childNode = parseNode(elementType, value);
node.getChildNodes().add(childNode);
mapNode.getKeys().add(entry.getKey());
}
} else {
LOGGER.error("Example value is not Map type: {}", objectValue);
node = new MapNode(elementType, null);
}
} else if (type == ClassType.OBJECT) {
node = new ObjectNode(type, objectValue);
} else if (type == ClassType.BINARY_DATA && objectValue != null) {
node = new BinaryDataNode(type, objectValue);
} else if (type instanceof ClassType && objectValue instanceof Map) {
ClientModel model = ClientModelUtil.getClientModel(((ClassType) type).getName());
if (model != null) {
if (model.isPolymorphic()) {
// polymorphic, need to get the correct subclass from discriminator
String serializedName = model.getPolymorphicDiscriminatorName();
List<String> jsonPropertyNames = Collections.singletonList(serializedName);
if (model.getNeedsFlatten()) {
jsonPropertyNames = ClientModelUtil.splitFlattenedSerializedName(serializedName);
}
Object childObjectValue = getChildObjectValue(jsonPropertyNames, objectValue);
if (childObjectValue instanceof String) {
String discriminatorValue = (String) childObjectValue;
ClientModel derivedModel = getDerivedModel(model, discriminatorValue);
if (derivedModel != null) {
// use the subclass
type = derivedModel.getType();
model = derivedModel;
} else {
LOGGER.error("Example value is not List type: {}", objectValue);
node = new ListNode(elementType, null);
LOGGER.warn("Failed to find the subclass with discriminator value '{}'", discriminatorValue);
}
} else if (type instanceof MapType) {
IType elementType = ((MapType) type).getValueType();
if (objectValue instanceof Map) {
MapNode mapNode = new MapNode(elementType, objectValue);
node = mapNode;
Map<String, Object> dict = (Map<String, Object>) objectValue;
for (Map.Entry<String, Object> entry : dict.entrySet()) {
Object value = entry.getValue();
// redact possible credential
if (elementType == ClassType.STRING && entry.getValue() instanceof String) {
value = ModelTestCaseUtil.redactStringValue(Collections.singletonList(entry.getKey()), (String) value);
}
ExampleNode childNode = parseNode(elementType, value);
node.getChildNodes().add(childNode);
mapNode.getKeys().add(entry.getKey());
}
} else {
LOGGER.error("Example value is not Map type: {}", objectValue);
node = new MapNode(elementType, null);
}
} else if (type == ClassType.OBJECT) {
node = new ObjectNode(type, objectValue);
} else if (type == ClassType.BINARY_DATA && objectValue != null) {
node = new BinaryDataNode(type, objectValue);
} else if (type instanceof ClassType && objectValue instanceof Map) {
ClientModel model = ClientModelUtil.getClientModel(((ClassType) type).getName());
if (model != null) {
if (model.isPolymorphic()) {
// polymorphic, need to get the correct subclass from discriminator
String serializedName = model.getPolymorphicDiscriminatorName();
List<String> jsonPropertyNames = Collections.singletonList(serializedName);
if (model.getNeedsFlatten()) {
jsonPropertyNames = ClientModelUtil.splitFlattenedSerializedName(serializedName);
}
Object childObjectValue = getChildObjectValue(jsonPropertyNames, objectValue);
if (childObjectValue instanceof String) {
String discriminatorValue = (String) childObjectValue;
ClientModel derivedModel = getDerivedModel(model, discriminatorValue);
if (derivedModel != null) {
// use the subclass
type = derivedModel.getType();
model = derivedModel;
} else {
LOGGER.warn("Failed to find the subclass with discriminator value '{}'", discriminatorValue);
}
} else {
LOGGER.warn("Failed to find the sample value for discriminator property '{}'", serializedName);
}
}
ClientModelNode clientModelNode = new ClientModelNode(type, objectValue).setClientModel(model);
node = clientModelNode;
List<ModelProperty> modelProperties = getWritablePropertiesIncludeSuperclass(model);
for (ModelProperty modelProperty : modelProperties) {
List<String> jsonPropertyNames = modelProperty.getSerializedNames();
Object childObjectValue = getChildObjectValue(jsonPropertyNames, objectValue);
if (childObjectValue != null) {
ExampleNode childNode = parseNode(modelProperty.getClientType(), modelProperty.getWireType(), childObjectValue);
node.getChildNodes().add(childNode);
clientModelNode.getClientModelProperties().put(childNode, modelProperty);
// redact possible credential
if (childNode instanceof LiteralNode && childObjectValue instanceof String) {
LiteralNode literalChildNode = (LiteralNode) childNode;
if (literalChildNode.getClientType() == ClassType.STRING
&& literalChildNode.getLiteralsValue() != null) {
literalChildNode.setLiteralsValue(ModelTestCaseUtil.redactStringValue(jsonPropertyNames, literalChildNode.getLiteralsValue()));
}
}
}
}
// additional properties
ModelProperty additionalPropertiesProperty = getAdditionalPropertiesProperty(model);
if (additionalPropertiesProperty != null) {
// properties already defined in model
Set<String> propertySerializedNames = modelProperties.stream()
.map(p -> p.getSerializedNames().iterator().next())
.collect(Collectors.toSet());
// the remaining properties in json
Map<String, Object> remainingValues = ((Map<String, Object>) objectValue).entrySet().stream()
.filter(e -> !propertySerializedNames.contains(e.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
ExampleNode childNode = parseNode(additionalPropertiesProperty.getClientType(), additionalPropertiesProperty.getWireType(), remainingValues);
node.getChildNodes().add(childNode);
clientModelNode.getClientModelProperties().put(childNode, additionalPropertiesProperty);
}
} else {
// e.g. do not throw exception, use defaultValueExpression
node = defaultNode(type, wireType, objectValue);
}
} else if (objectValue == null) {
node = null;
} else {
node = defaultNode(type, wireType, objectValue);
} else {
LOGGER.warn("Failed to find the sample value for discriminator property '{}'", serializedName);
}
}
return node;
ClientModelNode clientModelNode = new ClientModelNode(type, objectValue).setClientModel(model);
node = clientModelNode;
List<ModelProperty> modelProperties = getWritablePropertiesIncludeSuperclass(model);
for (ModelProperty modelProperty : modelProperties) {
List<String> jsonPropertyNames = modelProperty.getSerializedNames();
Object childObjectValue = getChildObjectValue(jsonPropertyNames, objectValue);
if (childObjectValue != null) {
ExampleNode childNode = parseNode(modelProperty.getClientType(), modelProperty.getWireType(), childObjectValue);
node.getChildNodes().add(childNode);
clientModelNode.getClientModelProperties().put(childNode, modelProperty);
// redact possible credential
if (childNode instanceof LiteralNode && childObjectValue instanceof String) {
LiteralNode literalChildNode = (LiteralNode) childNode;
if (literalChildNode.getClientType() == ClassType.STRING
&& literalChildNode.getLiteralsValue() != null) {
literalChildNode.setLiteralsValue(ModelTestCaseUtil.redactStringValue(jsonPropertyNames, literalChildNode.getLiteralsValue()));
}
}
}
}
// additional properties
ModelProperty additionalPropertiesProperty = getAdditionalPropertiesProperty(model);
if (additionalPropertiesProperty != null) {
// properties already defined in model
Set<String> propertySerializedNames = modelProperties.stream()
.map(p -> p.getSerializedNames().iterator().next())
.collect(Collectors.toSet());
// the remaining properties in json
Map<String, Object> remainingValues = ((Map<String, Object>) objectValue).entrySet().stream()
.filter(e -> !propertySerializedNames.contains(e.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
ExampleNode childNode = parseNode(additionalPropertiesProperty.getClientType(), additionalPropertiesProperty.getWireType(), remainingValues);
node.getChildNodes().add(childNode);
clientModelNode.getClientModelProperties().put(childNode, additionalPropertiesProperty);
}
} else {
// e.g. do not throw exception, use defaultValueExpression
node = defaultNode(type, wireType, objectValue);
}
} else {
// If client type is unrecognized, or the objectValue is null, we return default node (LiteralNode)
// In case of null objectValue, instead of directly returning null node, we let downstream to decide how to deal with it
node = defaultNode(type, wireType, objectValue);
}
return node;
}
/**
* Default String literal node.
* Generated example will be the type's defaultValueExpression.
*
* @param clientType the client type
* @param wireType the wire type
* @param exampleValue the example value
* @return string literal node
*/
private static ExampleNode defaultNode(IType clientType, IType wireType, Object exampleValue) {
ExampleNode node;
LiteralNode literalNode = new LiteralNode(clientType, exampleValue);
node = literalNode;
if (exampleValue != null) {
String literalValue = convertLiteralToClientValue(wireType, exampleValue.toString());
literalNode.setLiteralsValue(literalValue);
}
return node;
}
/**
* Convert literal value in wire type, to literal value in client type
* <p>
* date-time in RFC1123 to RFC3339
* date-time in Unix epoch to RFC3339
* bytes in base64URL to bytes in string
*
* @param wireType the wire type
* @param literalInWireType the literal value in wire type
* @return the literal value in client type
*/
public static String convertLiteralToClientValue(IType wireType, String literalInWireType) {
// see ClassType.convertToClientType and PrimitiveType.convertToClientType
String literalValue = literalInWireType;
if (wireType == ClassType.DATE_TIME_RFC_1123) {
literalValue = new DateTimeRfc1123(literalValue).getDateTime().toString();
} else if (wireType == ClassType.BASE_64_URL) {
literalValue = new Base64Url(literalValue).toString();
} else if (wireType == PrimitiveType.UNIX_TIME_LONG) {
literalValue = OffsetDateTime.from(Instant.ofEpochSecond(Long.parseLong(literalValue))).toString();
}
return literalValue;
}
@SuppressWarnings("unchecked")
public static Object getChildObjectValue(List<String> jsonPropertyNames, Object objectValue) {
boolean found = true;
Object childObjectValue = objectValue;
// walk the sequence of serialized names
for (String name : jsonPropertyNames) {
if (name.isEmpty()) {
found = false;
break;
}
if (childObjectValue instanceof Map) {
childObjectValue = ((Map<String, Object>) childObjectValue).get(name);
if (childObjectValue == null) {
found = false;
break;
}
} else {
found = false;
break;
}
}
return found ? childObjectValue : null;
}
/**
* Parse method parameter (client model or others) to example node.
* @param example proxy method example
* @param methodParameter method parameter
* @return example node
*/
public static ExampleNode parseNodeFromParameter(ProxyMethodExample example, MethodParameter methodParameter) {
String serializedName = methodParameter.getSerializedName();
if (serializedName == null && methodParameter.getProxyMethodParameter().getRequestParameterLocation() == RequestParameterLocation.BODY) {
serializedName = methodParameter.getProxyMethodParameter().getName();
}
/**
* Default String literal node.
* Generated example will be the type's defaultValueExpression.
*
* @param clientType the client type
* @param wireType the wire type
* @param exampleValue the example value
* @return string literal node
*/
private static ExampleNode defaultNode(IType clientType, IType wireType, Object exampleValue) {
ExampleNode node;
LiteralNode literalNode = new LiteralNode(clientType, exampleValue);
node = literalNode;
Object exampleValue = getParameterExampleValue(example, serializedName, methodParameter.getProxyMethodParameter().getRequestParameterLocation());
if (exampleValue != null) {
String literalValue = convertLiteralToClientValue(wireType, exampleValue.toString());
literalNode.setLiteralsValue(literalValue);
ExampleNode node;
if (exampleValue == null) {
if (ClassType.CONTEXT.equals(methodParameter.getClientMethodParameter().getClientType())) {
node = new LiteralNode(ClassType.CONTEXT, "").setLiteralsValue("");
} else {
node = new LiteralNode(methodParameter.getClientMethodParameter().getClientType(), null);
}
} else {
node = parseNodeFromMethodParameter(methodParameter, exampleValue);
}
return node;
}
/**
* Get the example value for the parameter.
*
* @param example proxy method example
* @param serializedName parameter serialized name
* @param requestParameterLocation parameter location
* @return the example value for the parameter, null if not found
*/
public static Object getParameterExampleValue(ProxyMethodExample example, String serializedName, RequestParameterLocation requestParameterLocation) {
ProxyMethodExample.ParameterValue parameterValue = findParameter(example, serializedName);
if (parameterValue == null && requestParameterLocation == RequestParameterLocation.BODY) {
// special handling for body, as it does not have serializedName
String paramSuffix = "Param";
if (serializedName.endsWith(paramSuffix)) {
// hack, remove Param, as it likely added by codegen to avoid naming conflict
serializedName = serializedName.substring(0, serializedName.length() - paramSuffix.length());
if (!serializedName.isEmpty()) {
parameterValue = findParameter(example, serializedName);
}
return node;
}
// fallback, "body" is commonly used in example JSON for request body
if (parameterValue == null && !"body".equalsIgnoreCase(serializedName)) {
serializedName = "body";
parameterValue = findParameter(example, serializedName);
}
}
/**
* Convert literal value in wire type, to literal value in client type
* <p>
* date-time in RFC1123 to RFC3339
* date-time in Unix epoch to RFC3339
* bytes in base64URL to bytes in string
*
* @param wireType the wire type
* @param literalInWireType the literal value in wire type
* @return the literal value in client type
*/
public static String convertLiteralToClientValue(IType wireType, String literalInWireType) {
// see ClassType.convertToClientType and PrimitiveType.convertToClientType
String literalValue = literalInWireType;
if (wireType == ClassType.DATE_TIME_RFC_1123) {
literalValue = new DateTimeRfc1123(literalValue).getDateTime().toString();
} else if (wireType == ClassType.BASE_64_URL) {
literalValue = new Base64Url(literalValue).toString();
} else if (wireType == PrimitiveType.UNIX_TIME_LONG) {
literalValue = OffsetDateTime.from(Instant.ofEpochSecond(Long.parseLong(literalValue))).toString();
}
return literalValue;
Object exampleValue = parameterValue;
if (parameterValue != null) {
exampleValue = requestParameterLocation == RequestParameterLocation.QUERY
? parameterValue.getUnescapedQueryValue()
: parameterValue.getObjectValue();
}
@SuppressWarnings("unchecked")
public static Object getChildObjectValue(List<String> jsonPropertyNames, Object objectValue) {
boolean found = true;
Object childObjectValue = objectValue;
// walk the sequence of serialized names
for (String name : jsonPropertyNames) {
if (name.isEmpty()) {
found = false;
break;
}
return exampleValue;
}
if (childObjectValue instanceof Map) {
childObjectValue = ((Map<String, Object>) childObjectValue).get(name);
if (childObjectValue == null) {
found = false;
break;
}
} else {
found = false;
break;
}
}
return found ? childObjectValue : null;
/**
* Find parameter example value from proxy method example by serialized parameter name.
* @param example proxy method example
* @param serializedName parameter serialized name
* @return example value for this parameter
*/
public static ProxyMethodExample.ParameterValue findParameter(ProxyMethodExample example, String serializedName) {
return example.getParameters().entrySet()
.stream().filter(p -> p.getKey().equalsIgnoreCase(serializedName))
.map(Map.Entry::getValue)
.findFirst().orElse(null);
}
private static ExampleNode parseNodeFromMethodParameter(MethodParameter methodParameter, Object objectValue) {
IType type = methodParameter.getClientMethodParameter().getClientType();
IType wireType = methodParameter.getClientMethodParameter().getWireType();
if (methodParameter.getProxyMethodParameter().getCollectionFormat() != null && type instanceof ListType && objectValue instanceof String) {
// handle parameter style
IType elementType = ((ListType) type).getElementType();
ListNode listNode = new ListNode(elementType, objectValue);
String value = (String) objectValue;
CollectionFormat collectionFormat = methodParameter.getProxyMethodParameter().getCollectionFormat();
String[] elements;
switch (collectionFormat) {
case CSV:
elements = value.split(",", -1);
break;
case SSV:
elements = value.split(" ", -1);
break;
case PIPES:
elements = value.split("\\|", -1);
break;
case TSV:
elements = value.split("\t", -1);
break;
default:
// TODO (weidxu): CollectionFormat.MULTI
elements = value.split(",", -1);
LOGGER.error("Parameter style '{}' is not supported, fallback to CSV", collectionFormat);
break;
}
for (String childObjectValue : elements) {
ExampleNode childNode = ModelExampleUtil.parseNode(elementType, childObjectValue);
listNode.getChildNodes().add(childNode);
}
return listNode;
} else {
return ModelExampleUtil.parseNode(type, wireType, objectValue);
}
}
private static ModelProperty getAdditionalPropertiesProperty(ClientModel model) {
ModelProperty modelProperty = null;
ClientModelProperty property = model.getProperties().stream()
.filter(ClientModelProperty::isAdditionalProperties)
.findFirst().orElse(null);
if (property != null && property.getClientType() instanceof MapType) {
modelProperty = ModelProperty.ofClientModelProperty(property);
}
return modelProperty;
}
private static List<ModelProperty> getWritablePropertiesIncludeSuperclass(ClientModel model) {
Map<String, ModelProperty> propertiesMap = new LinkedHashMap<>();
List<ModelProperty> properties = new ArrayList<>();
List<ClientModel> parentModels = new ArrayList<>();
String parentModelName = model.getParentModelName();
while (!CoreUtils.isNullOrEmpty(parentModelName)) {
ClientModel parentModel = ClientModelUtil.getClientModel(parentModelName);
if (parentModel != null) {
parentModels.add(parentModel);
}
parentModelName = parentModel == null ? null : parentModel.getParentModelName();
}
/**
* Parse method parameter (client model or others) to example node.
* @param example proxy method example
* @param methodParameter method parameter
* @return example node
*/
public static ExampleNode parseNodeFromParameter(ProxyMethodExample example, MethodParameter methodParameter) {
String serializedName = methodParameter.getSerializedName();
if (serializedName == null && methodParameter.getProxyMethodParameter().getRequestParameterLocation() == RequestParameterLocation.BODY) {
serializedName = methodParameter.getProxyMethodParameter().getName();
}
List<List<ModelProperty>> propertiesFromTypeAndParents = new ArrayList<>();
propertiesFromTypeAndParents.add(new ArrayList<>());
model.getAccessibleProperties().forEach(p -> {
ModelProperty modelProperty = ModelProperty.ofClientModelProperty(p);
if (propertiesMap.putIfAbsent(modelProperty.getName(), modelProperty) == null) {
propertiesFromTypeAndParents.get(propertiesFromTypeAndParents.size() - 1).add(modelProperty);
}
});
Object exampleValue = getParameterExampleValue(example, serializedName, methodParameter.getProxyMethodParameter().getRequestParameterLocation());
for (ClientModel parent : parentModels) {
propertiesFromTypeAndParents.add(new ArrayList<>());
ExampleNode node;
if (exampleValue == null) {
if (ClassType.CONTEXT.equals(methodParameter.getClientMethodParameter().getClientType())) {
node = new LiteralNode(ClassType.CONTEXT, "").setLiteralsValue("");
} else {
node = new LiteralNode(methodParameter.getClientMethodParameter().getClientType(), null);
}
} else {
node = parseNodeFromMethodParameter(methodParameter, exampleValue);
parent.getAccessibleProperties().forEach(p -> {
ModelProperty modelProperty = ModelProperty.ofClientModelProperty(p);
if (propertiesMap.putIfAbsent(modelProperty.getName(), modelProperty) == null) {
propertiesFromTypeAndParents.get(propertiesFromTypeAndParents.size() - 1).add(modelProperty);
}
return node;
});
}
/**
* Get the example value for the parameter.
*
* @param example proxy method example
* @param serializedName parameter serialized name
* @param requestParameterLocation parameter location
* @return the example value for the parameter, null if not found
*/
public static Object getParameterExampleValue(ProxyMethodExample example, String serializedName, RequestParameterLocation requestParameterLocation) {
ProxyMethodExample.ParameterValue parameterValue = findParameter(example, serializedName);
if (parameterValue == null && requestParameterLocation == RequestParameterLocation.BODY) {
// special handling for body, as it does not have serializedName
String paramSuffix = "Param";
if (serializedName.endsWith(paramSuffix)) {
// hack, remove Param, as it likely added by codegen to avoid naming conflict
serializedName = serializedName.substring(0, serializedName.length() - paramSuffix.length());
if (!serializedName.isEmpty()) {
parameterValue = findParameter(example, serializedName);
}
}
// fallback, "body" is commonly used in example JSON for request body
if (parameterValue == null && !"body".equalsIgnoreCase(serializedName)) {
serializedName = "body";
parameterValue = findParameter(example, serializedName);
}
}
Object exampleValue = parameterValue;
if (parameterValue != null) {
exampleValue = requestParameterLocation == RequestParameterLocation.QUERY
? parameterValue.getUnescapedQueryValue()
: parameterValue.getObjectValue();
}
return exampleValue;
Collections.reverse(propertiesFromTypeAndParents);
for (List<ModelProperty> properties1 : propertiesFromTypeAndParents) {
properties.addAll(properties1);
}
/**
* Find parameter example value from proxy method example by serialized parameter name.
* @param example proxy method example
* @param serializedName parameter serialized name
* @return example value for this parameter
*/
public static ProxyMethodExample.ParameterValue findParameter(ProxyMethodExample example, String serializedName) {
return example.getParameters().entrySet()
.stream().filter(p -> p.getKey().equalsIgnoreCase(serializedName))
.map(Map.Entry::getValue)
.findFirst().orElse(null);
return properties.stream()
.filter(p -> !p.isReadOnly() && !p.isConstant())
.collect(Collectors.toList());
}
private static ClientModel getDerivedModel(ClientModel model, String discriminatorValue) {
if (discriminatorValue.equals(model.getSerializedName())) {
return model;
}
private static ExampleNode parseNodeFromMethodParameter(MethodParameter methodParameter, Object objectValue) {
IType type = methodParameter.getClientMethodParameter().getClientType();
IType wireType = methodParameter.getClientMethodParameter().getWireType();
if (methodParameter.getProxyMethodParameter().getCollectionFormat() != null && type instanceof ListType && objectValue instanceof String) {
// handle parameter style
IType elementType = ((ListType) type).getElementType();
ListNode listNode = new ListNode(elementType, objectValue);
String value = (String) objectValue;
CollectionFormat collectionFormat = methodParameter.getProxyMethodParameter().getCollectionFormat();
String[] elements;
switch (collectionFormat) {
case CSV:
elements = value.split(",", -1);
break;
case SSV:
elements = value.split(" ", -1);
break;
case PIPES:
elements = value.split("\\|", -1);
break;
case TSV:
elements = value.split("\t", -1);
break;
default:
// TODO (weidxu): CollectionFormat.MULTI
elements = value.split(",", -1);
LOGGER.error("Parameter style '{}' is not supported, fallback to CSV", collectionFormat);
break;
}
for (String childObjectValue : elements) {
ExampleNode childNode = ModelExampleUtil.parseNode(elementType, childObjectValue);
listNode.getChildNodes().add(childNode);
}
return listNode;
} else {
return ModelExampleUtil.parseNode(type, wireType, objectValue);
// depth first search
if (model.getDerivedModels() != null) {
for (ClientModel childModel : model.getDerivedModels()) {
if (discriminatorValue.equalsIgnoreCase(childModel.getSerializedName())) {
// found
return childModel;
} else if (childModel.getDerivedModels() != null) {
// recursive
ClientModel childModel2 = getDerivedModel(childModel, discriminatorValue);
if (childModel2 != null) {
return childModel2;
}
}
}
}
private static ModelProperty getAdditionalPropertiesProperty(ClientModel model) {
ModelProperty modelProperty = null;
ClientModelProperty property = model.getProperties().stream()
.filter(ClientModelProperty::isAdditionalProperties)
.findFirst().orElse(null);
if (property != null && property.getClientType() instanceof MapType) {
modelProperty = ModelProperty.ofClientModelProperty(property);
}
return modelProperty;
}
private static List<ModelProperty> getWritablePropertiesIncludeSuperclass(ClientModel model) {
Map<String, ModelProperty> propertiesMap = new LinkedHashMap<>();
List<ModelProperty> properties = new ArrayList<>();
List<ClientModel> parentModels = new ArrayList<>();
String parentModelName = model.getParentModelName();
while (!CoreUtils.isNullOrEmpty(parentModelName)) {
ClientModel parentModel = ClientModelUtil.getClientModel(parentModelName);
if (parentModel != null) {
parentModels.add(parentModel);
}
parentModelName = parentModel == null ? null : parentModel.getParentModelName();
}
List<List<ModelProperty>> propertiesFromTypeAndParents = new ArrayList<>();
propertiesFromTypeAndParents.add(new ArrayList<>());
model.getAccessibleProperties().forEach(p -> {
ModelProperty modelProperty = ModelProperty.ofClientModelProperty(p);
if (propertiesMap.putIfAbsent(modelProperty.getName(), modelProperty) == null) {
propertiesFromTypeAndParents.get(propertiesFromTypeAndParents.size() - 1).add(modelProperty);
}
});
for (ClientModel parent : parentModels) {
propertiesFromTypeAndParents.add(new ArrayList<>());
parent.getAccessibleProperties().forEach(p -> {
ModelProperty modelProperty = ModelProperty.ofClientModelProperty(p);
if (propertiesMap.putIfAbsent(modelProperty.getName(), modelProperty) == null) {
propertiesFromTypeAndParents.get(propertiesFromTypeAndParents.size() - 1).add(modelProperty);
}
});
}
Collections.reverse(propertiesFromTypeAndParents);
for (List<ModelProperty> properties1 : propertiesFromTypeAndParents) {
properties.addAll(properties1);
}
return properties.stream()
.filter(p -> !p.isReadOnly() && !p.isConstant())
.collect(Collectors.toList());
}
private static ClientModel getDerivedModel(ClientModel model, String discriminatorValue) {
if (discriminatorValue.equals(model.getSerializedName())) {
return model;
}
// depth first search
if (model.getDerivedModels() != null) {
for (ClientModel childModel : model.getDerivedModels()) {
if (discriminatorValue.equalsIgnoreCase(childModel.getSerializedName())) {
// found
return childModel;
} else if (childModel.getDerivedModels() != null) {
// recursive
ClientModel childModel2 = getDerivedModel(childModel, discriminatorValue);
if (childModel2 != null) {
return childModel2;
}
}
}
}
// not found
return null;
}
// not found
return null;
}
}

Просмотреть файл

@ -0,0 +1,13 @@
# Release History
## {{artifact-version}} ({{date-utc}})
- Azure {{service-name}} client library for Java. {{service-description}}
### Features Added
### Breaking Changes
### Bugs Fixed
### Other Changes

Просмотреть файл

@ -0,0 +1,214 @@
import io.clientcore.core.http.models.HttpHeaderName;
import io.clientcore.core.http.models.RequestOptions;
import io.clientcore.core.util.binarydata.BinaryData;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;
// DO NOT modify this helper class
public final class MultipartFormDataHelper {
/**
* Line separator for the multipart HTTP request.
*/
private static final String CRLF = "\r\n";
private static final String APPLICATION_OCTET_STREAM = "application/octet-stream";
/**
* Value to be used as part of the divider for the multipart requests.
*/
private final String boundary;
/**
* The actual part separator in the request. This is obtained by prepending "--" to the "boundary".
*/
private final String partSeparator;
/**
* The marker for the ending of a multipart request. This is obtained by post-pending "--" to the "partSeparator".
*/
private final String endMarker;
/**
* Charset used for encoding the multipart HTTP request.
*/
private final Charset encoderCharset = StandardCharsets.UTF_8;
private InputStream requestDataStream = new ByteArrayInputStream(new byte[0]);
private long requestLength = 0;
private RequestOptions requestOptions;
private BinaryData requestBody;
/**
* Default constructor used in the code. The boundary is a random value.
*
* @param requestOptions the RequestOptions to update
*/
public MultipartFormDataHelper(RequestOptions requestOptions) {
this(requestOptions, UUID.randomUUID().toString().substring(0, 16));
}
private MultipartFormDataHelper(RequestOptions requestOptions, String boundary) {
this.requestOptions = requestOptions;
this.boundary = boundary;
this.partSeparator = "--" + boundary;
this.endMarker = this.partSeparator + "--";
}
/**
* Gets the multipart HTTP request body.
*
* @return the BinaryData of the multipart HTTP request body
*/
public BinaryData getRequestBody() {
return requestBody;
}
// text/plain
/**
* Formats a text/plain field for a multipart HTTP request.
*
* @param fieldName the field name
* @param value the value of the text/plain field
* @return the MultipartFormDataHelper instance
*/
public MultipartFormDataHelper serializeTextField(String fieldName, String value) {
if (value != null) {
String serialized = partSeparator
+ CRLF + "Content-Disposition: form-data; name=\"" + escapeName(fieldName) + "\""
+ CRLF + CRLF
+ value
+ CRLF;
byte[] data = serialized.getBytes(encoderCharset);
appendBytes(data);
}
return this;
}
// application/json
/**
* Formats a application/json field for a multipart HTTP request.
*
* @param fieldName the field name
* @param jsonObject the object of the application/json field
* @return the MultipartFormDataHelper instance
*/
public MultipartFormDataHelper serializeJsonField(String fieldName, Object jsonObject) {
if (jsonObject != null) {
String serialized = partSeparator + CRLF
+ "Content-Disposition: form-data; name=\"" + escapeName(fieldName) + "\""
+ CRLF + "Content-Type: application/json"
+ CRLF + CRLF + BinaryData.fromObject(jsonObject) + CRLF;
byte[] data = serialized.getBytes(encoderCharset);
appendBytes(data);
}
return this;
}
/**
* Formats a file field for a multipart HTTP request.
*
* @param fieldName the field name
* @param file the BinaryData of the file
* @param contentType the content-type of the file
* @param filename the filename
* @return the MultipartFormDataHelper instance
*/
public MultipartFormDataHelper serializeFileField(
String fieldName,
BinaryData file,
String contentType,
String filename) {
if (file != null) {
if (contentType != null && !contentType.isEmpty()) {
contentType = APPLICATION_OCTET_STREAM;
}
writeFileField(fieldName, file, contentType, filename);
}
return this;
}
/**
* Formats a file field (potentially multiple files) for a multipart HTTP request.
*
* @param fieldName the field name
* @param files the List of BinaryData of the files
* @param contentTypes the List of content-type of the files
* @param filenames the List of filenames
* @return the MultipartFormDataHelper instance
*/
public MultipartFormDataHelper serializeFileFields(
String fieldName,
List<BinaryData> files,
List<String> contentTypes,
List<String> filenames) {
if (files != null) {
for (int i = 0; i < files.size(); ++i) {
BinaryData file = files.get(i);
String contentType = contentTypes.get(i);
if (contentType != null && !contentType.isEmpty()) {
contentType = APPLICATION_OCTET_STREAM;
}
String filename = filenames.get(i);
writeFileField(fieldName, file, contentType, filename);
}
}
return this;
}
/**
* Ends the serialization of the multipart HTTP request.
*
* @return the MultipartFormDataHelper instance
*/
public MultipartFormDataHelper end() {
byte[] data = endMarker.getBytes(encoderCharset);
appendBytes(data);
requestBody = BinaryData.fromStream(requestDataStream, requestLength);
requestOptions
.setHeader(HttpHeaderName.CONTENT_TYPE, "multipart/form-data; boundary=" + this.boundary)
.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(requestLength));
return this;
}
private void writeFileField(String fieldName, BinaryData file, String contentType, String filename) {
String contentDispositionFilename = "";
if (filename != null && !filename.isEmpty()) {
contentDispositionFilename = "; filename=\"" + escapeName(filename) + "\"";
}
// Multipart preamble
String fileFieldPreamble = partSeparator
+ CRLF + "Content-Disposition: form-data; name=\"" + escapeName(fieldName) + "\"" + contentDispositionFilename
+ CRLF + "Content-Type: " + contentType + CRLF + CRLF;
byte[] data = fileFieldPreamble.getBytes(encoderCharset);
appendBytes(data);
// Writing the file into the request as a byte stream
requestLength += file.getLength();
requestDataStream = new SequenceInputStream(requestDataStream, file.toStream());
// CRLF
data = CRLF.getBytes(encoderCharset);
appendBytes(data);
}
private void appendBytes(byte[] bytes) {
requestLength += bytes.length;
requestDataStream = new SequenceInputStream(requestDataStream, new ByteArrayInputStream(bytes));
}
private static String escapeName(String name) {
return name.replace("\n", "%0A").replace("\r", "%0D").replace("\"", "%22");
}
}

Просмотреть файл

@ -0,0 +1,215 @@
import com.azure.core.http.HttpHeaderName;
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.util.BinaryData;
import com.azure.core.util.CoreUtils;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;
// DO NOT modify this helper class
public final class MultipartFormDataHelper {
/**
* Line separator for the multipart HTTP request.
*/
private static final String CRLF = "\r\n";
private static final String APPLICATION_OCTET_STREAM = "application/octet-stream";
/**
* Value to be used as part of the divider for the multipart requests.
*/
private final String boundary;
/**
* The actual part separator in the request. This is obtained by prepending "--" to the "boundary".
*/
private final String partSeparator;
/**
* The marker for the ending of a multipart request. This is obtained by post-pending "--" to the "partSeparator".
*/
private final String endMarker;
/**
* Charset used for encoding the multipart HTTP request.
*/
private final Charset encoderCharset = StandardCharsets.UTF_8;
private InputStream requestDataStream = new ByteArrayInputStream(new byte[0]);
private long requestLength = 0;
private RequestOptions requestOptions;
private BinaryData requestBody;
/**
* Default constructor used in the code. The boundary is a random value.
*
* @param requestOptions the RequestOptions to update
*/
public MultipartFormDataHelper(RequestOptions requestOptions) {
this(requestOptions, UUID.randomUUID().toString().substring(0, 16));
}
private MultipartFormDataHelper(RequestOptions requestOptions, String boundary) {
this.requestOptions = requestOptions;
this.boundary = boundary;
this.partSeparator = "--" + boundary;
this.endMarker = this.partSeparator + "--";
}
/**
* Gets the multipart HTTP request body.
*
* @return the BinaryData of the multipart HTTP request body
*/
public BinaryData getRequestBody() {
return requestBody;
}
// text/plain
/**
* Formats a text/plain field for a multipart HTTP request.
*
* @param fieldName the field name
* @param value the value of the text/plain field
* @return the MultipartFormDataHelper instance
*/
public MultipartFormDataHelper serializeTextField(String fieldName, String value) {
if (value != null) {
String serialized = partSeparator
+ CRLF + "Content-Disposition: form-data; name=\"" + escapeName(fieldName) + "\""
+ CRLF + CRLF
+ value
+ CRLF;
byte[] data = serialized.getBytes(encoderCharset);
appendBytes(data);
}
return this;
}
// application/json
/**
* Formats a application/json field for a multipart HTTP request.
*
* @param fieldName the field name
* @param jsonObject the object of the application/json field
* @return the MultipartFormDataHelper instance
*/
public MultipartFormDataHelper serializeJsonField(String fieldName, Object jsonObject) {
if (jsonObject != null) {
String serialized = partSeparator + CRLF
+ "Content-Disposition: form-data; name=\"" + escapeName(fieldName) + "\""
+ CRLF + "Content-Type: application/json"
+ CRLF + CRLF + BinaryData.fromObject(jsonObject) + CRLF;
byte[] data = serialized.getBytes(encoderCharset);
appendBytes(data);
}
return this;
}
/**
* Formats a file field for a multipart HTTP request.
*
* @param fieldName the field name
* @param file the BinaryData of the file
* @param contentType the content-type of the file
* @param filename the filename
* @return the MultipartFormDataHelper instance
*/
public MultipartFormDataHelper serializeFileField(
String fieldName,
BinaryData file,
String contentType,
String filename) {
if (file != null) {
if (CoreUtils.isNullOrEmpty(contentType)) {
contentType = APPLICATION_OCTET_STREAM;
}
writeFileField(fieldName, file, contentType, filename);
}
return this;
}
/**
* Formats a file field (potentially multiple files) for a multipart HTTP request.
*
* @param fieldName the field name
* @param files the List of BinaryData of the files
* @param contentTypes the List of content-type of the files
* @param filenames the List of filenames
* @return the MultipartFormDataHelper instance
*/
public MultipartFormDataHelper serializeFileFields(
String fieldName,
List<BinaryData> files,
List<String> contentTypes,
List<String> filenames) {
if (files != null) {
for (int i = 0; i < files.size(); ++i) {
BinaryData file = files.get(i);
String contentType = contentTypes.get(i);
if (CoreUtils.isNullOrEmpty(contentType)) {
contentType = APPLICATION_OCTET_STREAM;
}
String filename = filenames.get(i);
writeFileField(fieldName, file, contentType, filename);
}
}
return this;
}
/**
* Ends the serialization of the multipart HTTP request.
*
* @return the MultipartFormDataHelper instance
*/
public MultipartFormDataHelper end() {
byte[] data = endMarker.getBytes(encoderCharset);
appendBytes(data);
requestBody = BinaryData.fromStream(requestDataStream, requestLength);
requestOptions
.setHeader(HttpHeaderName.CONTENT_TYPE, "multipart/form-data; boundary=" + this.boundary)
.setHeader(HttpHeaderName.CONTENT_LENGTH, String.valueOf(requestLength));
return this;
}
private void writeFileField(String fieldName, BinaryData file, String contentType, String filename) {
String contentDispositionFilename = "";
if (!CoreUtils.isNullOrEmpty(filename)) {
contentDispositionFilename = "; filename=\"" + escapeName(filename) + "\"";
}
// Multipart preamble
String fileFieldPreamble = partSeparator
+ CRLF + "Content-Disposition: form-data; name=\"" + escapeName(fieldName) + "\"" + contentDispositionFilename
+ CRLF + "Content-Type: " + contentType + CRLF + CRLF;
byte[] data = fileFieldPreamble.getBytes(encoderCharset);
appendBytes(data);
// Writing the file into the request as a byte stream
requestLength += file.getLength();
requestDataStream = new SequenceInputStream(requestDataStream, file.toStream());
// CRLF
data = CRLF.getBytes(encoderCharset);
appendBytes(data);
}
private void appendBytes(byte[] bytes) {
requestLength += bytes.length;
requestDataStream = new SequenceInputStream(requestDataStream, new ByteArrayInputStream(bytes));
}
private static String escapeName(String name) {
return name.replace("\n", "%0A").replace("\r", "%0D").replace("\"", "%22");
}
}

Просмотреть файл

@ -0,0 +1,129 @@
import com.azure.core.exception.AzureException;
import com.azure.core.http.HttpHeader;
import com.azure.core.http.rest.Response;
import com.azure.core.util.BinaryData;
import com.azure.core.util.logging.ClientLogger;
import com.azure.core.util.polling.LongRunningOperationStatus;
import com.azure.core.util.polling.OperationResourcePollingStrategy;
import com.azure.core.util.polling.PollResponse;
import com.azure.core.util.polling.PollingContext;
import com.azure.core.util.polling.PollingStrategyOptions;
import com.azure.core.util.serializer.JsonSerializerProviders;
import com.azure.core.util.serializer.ObjectSerializer;
import com.azure.core.util.serializer.TypeReference;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.time.OffsetDateTime;
// DO NOT modify this helper class
/**
* Implements an operation location polling strategy, from Operation-Location.
*
* @param <T> the type of the response type from a polling call, or BinaryData if raw response body should be kept
* @param <U> the type of the final result object to deserialize into, or BinaryData if raw response body should be
* kept
*/
public final class OperationLocationPollingStrategy<T, U> extends OperationResourcePollingStrategy<T, U> {
private static final ClientLogger LOGGER = new ClientLogger(OperationLocationPollingStrategy.class);
private final ObjectSerializer serializer;
private final String endpoint;
private final String propertyName;
/**
* Creates an instance of the operation resource polling strategy.
*
* @param pollingStrategyOptions options to configure this polling strategy.
* @throws NullPointerException if {@code pollingStrategyOptions} is null.
*/
public OperationLocationPollingStrategy(PollingStrategyOptions pollingStrategyOptions) {
this(pollingStrategyOptions, null);
}
/**
* Creates an instance of the operation resource polling strategy.
*
* @param pollingStrategyOptions options to configure this polling strategy.
* @param propertyName the name of the property to extract final result.
* @throws NullPointerException if {@code pollingStrategyOptions} is null.
*/
public OperationLocationPollingStrategy(PollingStrategyOptions pollingStrategyOptions, String propertyName) {
super(PollingUtils.OPERATION_LOCATION_HEADER, pollingStrategyOptions);
this.propertyName = propertyName;
this.endpoint = pollingStrategyOptions.getEndpoint();
this.serializer = pollingStrategyOptions.getSerializer() != null
? pollingStrategyOptions.getSerializer()
: JsonSerializerProviders.createInstance(true);
}
/**
* {@inheritDoc}
*/
@Override
public Mono<PollResponse<T>> onInitialResponse(Response<?> response, PollingContext<T> pollingContext,
TypeReference<T> pollResponseType) {
// Response<?> is Response<BinaryData>
HttpHeader operationLocationHeader = response.getHeaders().get(PollingUtils.OPERATION_LOCATION_HEADER);
if (operationLocationHeader != null) {
pollingContext.setData(PollingUtils.OPERATION_LOCATION_HEADER.getCaseSensitiveName(),
PollingUtils.getAbsolutePath(operationLocationHeader.getValue(), endpoint, LOGGER));
}
final String httpMethod = response.getRequest().getHttpMethod().name();
pollingContext.setData(PollingUtils.HTTP_METHOD, httpMethod);
pollingContext.setData(PollingUtils.REQUEST_URL, response.getRequest().getUrl().toString());
if (response.getStatusCode() == 200
|| response.getStatusCode() == 201
|| response.getStatusCode() == 202
|| response.getStatusCode() == 204) {
final Duration retryAfter = PollingUtils.getRetryAfterFromHeaders(response.getHeaders(), OffsetDateTime::now);
final Mono<PollResponse<T>> pollResponseMono = PollingUtils.deserializeResponse((BinaryData) response.getValue(), serializer, pollResponseType)
.onErrorResume(exception -> {
LOGGER.info("Failed to parse initial response.");
return Mono.empty();
})
.map(value -> new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, value, retryAfter));
return pollResponseMono.switchIfEmpty(
Mono.fromSupplier(() -> new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, null, retryAfter)));
} else {
return Mono.error(new AzureException(String.format(
"Operation failed or cancelled with status code %d," + ", '%s' header: %s, and response body: %s",
response.getStatusCode(), PollingUtils.OPERATION_LOCATION_HEADER, operationLocationHeader,
response.getValue())));
}
}
/**
* {@inheritDoc}
*/
@Override
public Mono<U> getResult(PollingContext<T> pollingContext, TypeReference<U> resultType) {
if (pollingContext.getLatestResponse().getStatus() == LongRunningOperationStatus.FAILED) {
return Mono.error(new AzureException("Long running operation failed."));
} else if (pollingContext.getLatestResponse().getStatus() == LongRunningOperationStatus.USER_CANCELLED) {
return Mono.error(new AzureException("Long running operation cancelled."));
}
if (propertyName != null) {
// take the last poll response body from PollingContext,
// and de-serialize the <propertyName> property as final result
BinaryData latestResponseBody
= BinaryData.fromString(pollingContext.getData(PollingUtils.POLL_RESPONSE_BODY));
return PollingUtils.deserializeResponse(latestResponseBody, serializer, PollingUtils.POST_POLL_RESULT_TYPE_REFERENCE)
.flatMap(value -> {
if (value.get(propertyName) != null) {
return BinaryData.fromObjectAsync(value.get(propertyName))
.flatMap(result -> PollingUtils.deserializeResponse(result, serializer, resultType));
} else {
return Mono.error(new AzureException("Cannot get final result"));
}
})
.switchIfEmpty(Mono.error(new AzureException("Cannot get final result")));
} else {
return super.getResult(pollingContext, resultType);
}
}
}

Просмотреть файл

@ -0,0 +1,138 @@
import com.azure.core.http.HttpHeaderName;
import com.azure.core.http.HttpHeaders;
import com.azure.core.util.BinaryData;
import com.azure.core.util.CoreUtils;
import com.azure.core.util.DateTimeRfc1123;
import com.azure.core.util.logging.ClientLogger;
import com.azure.core.util.serializer.ObjectSerializer;
import com.azure.core.util.serializer.TypeReference;
import reactor.core.publisher.Mono;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.DateTimeException;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
// DO NOT modify this helper class
final class PollingUtils {
public static final TypeReference<Map<String, Object>> POST_POLL_RESULT_TYPE_REFERENCE
= new TypeReference<Map<String, Object>>() { };
public static final HttpHeaderName OPERATION_LOCATION_HEADER
= HttpHeaderName.fromString("Operation-Location");
public static final String HTTP_METHOD = "httpMethod";
public static final String REQUEST_URL = "requestURL";
public static final String POLL_RESPONSE_BODY = "pollResponseBody";
private static final String FORWARD_SLASH = "/";
public static String getAbsolutePath(String path, String endpoint, ClientLogger logger) {
try {
URI uri = new URI(path);
if (!uri.isAbsolute()) {
if (CoreUtils.isNullOrEmpty(endpoint)) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Relative path requires endpoint to be non-null and non-empty to create an absolute path."));
}
if (endpoint.endsWith(FORWARD_SLASH) && path.startsWith(FORWARD_SLASH)) {
return endpoint + path.substring(1);
} else if (!endpoint.endsWith(FORWARD_SLASH) && !path.startsWith(FORWARD_SLASH)) {
return endpoint + FORWARD_SLASH + path;
} else {
return endpoint + path;
}
}
} catch (URISyntaxException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'path' must be a valid URI.", ex));
}
return path;
}
public static <T> T deserializeResponseSync(BinaryData binaryData, ObjectSerializer serializer, TypeReference<T> typeReference) {
T value;
if (binaryData == null) {
value = null;
} else if (typeReference.getJavaClass().isAssignableFrom(BinaryData.class)) {
// T is BinaryData
value = typeReference.getJavaClass().cast(binaryData.toReplayableBinaryData());
} else {
value = binaryData.toObject(typeReference, serializer);
}
return value;
}
@SuppressWarnings("unchecked")
public static <T> Mono<T> deserializeResponse(BinaryData binaryData, ObjectSerializer serializer, TypeReference<T> typeReference) {
Mono<T> value;
if (binaryData == null) {
value = Mono.empty();
} else if (typeReference.getJavaClass().isAssignableFrom(BinaryData.class)) {
// T is BinaryData
value = (Mono<T>) binaryData.toReplayableBinaryDataAsync();
} else {
value = binaryData.toObjectAsync(typeReference, serializer);
}
return value;
}
private static final HttpHeaderName RETRY_AFTER_MS_HEADER = HttpHeaderName.fromString("retry-after-ms");
private static final HttpHeaderName X_MS_RETRY_AFTER_MS_HEADER = HttpHeaderName.fromString("x-ms-retry-after-ms");
public static Duration getRetryAfterFromHeaders(HttpHeaders headers, Supplier<OffsetDateTime> nowSupplier) {
// Found 'x-ms-retry-after-ms' header, use a Duration of milliseconds based on the value.
Duration retryDelay = tryGetRetryDelay(headers, X_MS_RETRY_AFTER_MS_HEADER, s -> tryGetDelayMillis(s));
if (retryDelay != null) {
return retryDelay;
}
// Found 'retry-after-ms' header, use a Duration of milliseconds based on the value.
retryDelay = tryGetRetryDelay(headers, RETRY_AFTER_MS_HEADER, s -> tryGetDelayMillis(s));
if (retryDelay != null) {
return retryDelay;
}
// Found 'Retry-After' header. First, attempt to resolve it as a Duration of seconds. If that fails, then
// attempt to resolve it as an HTTP date (RFC1123).
retryDelay = tryGetRetryDelay(headers, HttpHeaderName.RETRY_AFTER,
headerValue -> tryParseLongOrDateTime(headerValue, nowSupplier));
// Either the retry delay will have been found or it'll be null, null indicates no retry after.
return retryDelay;
}
private static Duration tryGetRetryDelay(HttpHeaders headers, HttpHeaderName headerName,
Function<String, Duration> delayParser) {
String headerValue = headers.getValue(headerName);
return CoreUtils.isNullOrEmpty(headerValue) ? null : delayParser.apply(headerValue);
}
private static Duration tryParseLongOrDateTime(String value, Supplier<OffsetDateTime> nowSupplier) {
long delaySeconds;
try {
OffsetDateTime retryAfter = new DateTimeRfc1123(value).getDateTime();
delaySeconds = nowSupplier.get().until(retryAfter, ChronoUnit.SECONDS);
} catch (DateTimeException ex) {
delaySeconds = tryParseLong(value);
}
return (delaySeconds >= 0) ? Duration.ofSeconds(delaySeconds) : null;
}
private static long tryParseLong(String value) {
try {
return Long.parseLong(value);
} catch (NumberFormatException ex) {
return -1;
}
}
private static Duration tryGetDelayMillis(String value) {
long delayMillis = tryParseLong(value);
return (delayMillis >= 0) ? Duration.ofMillis(delayMillis) : null;
}
}

Просмотреть файл

@ -0,0 +1,80 @@
# Azure {{service-name}} client library for Java
Azure {{service-name}} client library for Java.
{{service-description}}
## Documentation
Various documentation is available to help you get started
- [API reference documentation][docs]
- [Product documentation][product_documentation]
## Getting started
### Prerequisites
- [Java Development Kit (JDK)][jdk] with version 8 or above
- [Azure Subscription][azure_subscription]
### Adding the package to your product
[//]: # ({x-version-update-start;{{group-id}}:{{artifact-id}};current})
```xml
<dependency>
<groupId>{{group-id}}</groupId>
<artifactId>{{artifact-id}}</artifactId>
<version>{{artifact-version}}</version>
</dependency>
```
[//]: # ({x-version-update-end})
### Authentication
[Azure Identity][azure_identity] package provides the default implementation for authenticating the client.
## Key concepts
## Examples
```java {{package-name}}.readme
```
### Service API versions
The client library targets the latest service API version by default.
The service client builder accepts an optional service API version parameter to specify which API version to communicate.
#### Select a service API version
You have the flexibility to explicitly select a supported service API version when initializing a service client via the service client builder.
This ensures that the client can communicate with services using the specified API version.
When selecting an API version, it is important to verify that there are no breaking changes compared to the latest API version.
If there are significant differences, API calls may fail due to incompatibility.
Always ensure that the chosen API version is fully supported and operational for your specific use case and that it aligns with the service's versioning policy.
## Troubleshooting
## Next steps
## Contributing
For details on contributing to this repository, see the [contributing guide](https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.md).
1. Fork it
1. Create your feature branch (`git checkout -b my-new-feature`)
1. Commit your changes (`git commit -am 'Add some feature'`)
1. Push to the branch (`git push origin my-new-feature`)
1. Create new Pull Request
<!-- LINKS -->
[product_documentation]: https://azure.microsoft.com/services/
[docs]: https://azure.github.io/azure-sdk-for-java/
[jdk]: https://learn.microsoft.com/azure/developer/java/fundamentals/
[azure_subscription]: https://azure.microsoft.com/free/
[azure_identity]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity
{{impression-pixel}}

Просмотреть файл

@ -0,0 +1,124 @@
import com.azure.core.exception.AzureException;
import com.azure.core.http.HttpHeader;
import com.azure.core.http.rest.Response;
import com.azure.core.util.BinaryData;
import com.azure.core.util.logging.ClientLogger;
import com.azure.core.util.polling.LongRunningOperationStatus;
import com.azure.core.util.polling.PollResponse;
import com.azure.core.util.polling.PollingContext;
import com.azure.core.util.polling.PollingStrategyOptions;
import com.azure.core.util.polling.SyncOperationResourcePollingStrategy;
import com.azure.core.util.serializer.JsonSerializerProviders;
import com.azure.core.util.serializer.ObjectSerializer;
import com.azure.core.util.serializer.TypeReference;
import java.io.UncheckedIOException;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.util.Map;
// DO NOT modify this helper class
/**
* Implements a synchronous operation location polling strategy, from Operation-Location.
*
* @param <T> the type of the response type from a polling call, or BinaryData if raw response body should be kept
* @param <U> the type of the final result object to deserialize into, or BinaryData if raw response body should be
* kept
*/
public final class SyncOperationLocationPollingStrategy<T, U> extends SyncOperationResourcePollingStrategy<T, U> {
private static final ClientLogger LOGGER = new ClientLogger(SyncOperationLocationPollingStrategy.class);
private final ObjectSerializer serializer;
private final String endpoint;
private final String propertyName;
/**
* Creates an instance of the operation resource polling strategy.
*
* @param pollingStrategyOptions options to configure this polling strategy.
* @throws NullPointerException if {@code pollingStrategyOptions} is null.
*/
public SyncOperationLocationPollingStrategy(PollingStrategyOptions pollingStrategyOptions) {
this(pollingStrategyOptions, null);
}
/**
* Creates an instance of the operation resource polling strategy.
*
* @param pollingStrategyOptions options to configure this polling strategy.
* @param propertyName the name of the property to extract final result.
* @throws NullPointerException if {@code pollingStrategyOptions} is null.
*/
public SyncOperationLocationPollingStrategy(PollingStrategyOptions pollingStrategyOptions, String propertyName) {
super(PollingUtils.OPERATION_LOCATION_HEADER, pollingStrategyOptions);
this.propertyName = propertyName;
this.endpoint = pollingStrategyOptions.getEndpoint();
this.serializer = pollingStrategyOptions.getSerializer() != null
? pollingStrategyOptions.getSerializer() : JsonSerializerProviders.createInstance(true);
}
/**
* {@inheritDoc}
*/
@Override
public PollResponse<T> onInitialResponse(Response<?> response, PollingContext<T> pollingContext,
TypeReference<T> pollResponseType) {
// Response<?> is Response<BinaryData>
HttpHeader operationLocationHeader = response.getHeaders().get(PollingUtils.OPERATION_LOCATION_HEADER);
if (operationLocationHeader != null) {
pollingContext.setData(PollingUtils.OPERATION_LOCATION_HEADER.getCaseSensitiveName(),
PollingUtils.getAbsolutePath(operationLocationHeader.getValue(), endpoint, LOGGER));
}
final String httpMethod = response.getRequest().getHttpMethod().name();
pollingContext.setData(PollingUtils.HTTP_METHOD, httpMethod);
pollingContext.setData(PollingUtils.REQUEST_URL, response.getRequest().getUrl().toString());
if (response.getStatusCode() == 200
|| response.getStatusCode() == 201
|| response.getStatusCode() == 202
|| response.getStatusCode() == 204) {
final Duration retryAfter = PollingUtils.getRetryAfterFromHeaders(response.getHeaders(), OffsetDateTime::now);
T initialResponseType = null;
try {
initialResponseType = PollingUtils.deserializeResponseSync((BinaryData) response.getValue(), serializer, pollResponseType);
} catch (UncheckedIOException e) {
LOGGER.info("Failed to parse initial response.");
}
return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, initialResponseType, retryAfter);
}
throw LOGGER.logExceptionAsError(new AzureException(String.format(
"Operation failed or cancelled with status code %d, '%s' header: %s, and response body: %s",
response.getStatusCode(), PollingUtils.OPERATION_LOCATION_HEADER, operationLocationHeader,
response.getValue())));
}
/**
* {@inheritDoc}
*/
public U getResult(PollingContext<T> pollingContext, TypeReference<U> resultType) {
if (pollingContext.getLatestResponse().getStatus() == LongRunningOperationStatus.FAILED) {
throw LOGGER.logExceptionAsError(new AzureException("Long running operation failed."));
} else if (pollingContext.getLatestResponse().getStatus() == LongRunningOperationStatus.USER_CANCELLED) {
throw LOGGER.logExceptionAsError(new AzureException("Long running operation cancelled."));
}
if (propertyName != null) {
// take the last poll response body from PollingContext,
// and de-serialize the <propertyName> property as final result
BinaryData latestResponseBody =
BinaryData.fromString(pollingContext.getData(PollingUtils.POLL_RESPONSE_BODY));
Map<String, Object> pollResult =
PollingUtils.deserializeResponseSync(latestResponseBody, serializer, PollingUtils.POST_POLL_RESULT_TYPE_REFERENCE);
if (pollResult != null && pollResult.get(propertyName) != null) {
return PollingUtils.deserializeResponseSync(BinaryData.fromObject(pollResult.get(propertyName)), serializer, resultType);
} else {
throw LOGGER.logExceptionAsError(new AzureException("Cannot get final result"));
}
} else {
return super.getResult(pollingContext, resultType);
}
}
}

Просмотреть файл

@ -0,0 +1,23 @@
#### data-plane
```yaml
azure-arm: false
license-header: MICROSOFT_MIT_SMALL
generate-client-interfaces: false
generate-client-as-impl: true
generate-sync-async-clients: true
generate-builder-per-client: true
sync-methods: all
enable-sync-stack: true
required-fields-as-ctor-args: true
enable-page-size: true
use-key-credential: true
use-default-http-status-code-to-exception-type-mapping: true
polling: {}
models-subpackage: implementation.models
client-logger: true
```

Просмотреть файл

@ -0,0 +1,80 @@
<!-- Copyright (c) Microsoft Corporation. All rights reserved. -->
<!-- Licensed under the MIT License. -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.azure</groupId>
<artifactId>autorest-generated-client</artifactId>
<version>1.0.0-beta.1</version>
<name>Microsoft Azure client library</name>
<description>This package contains the generated client library.</description>
<url>https://github.com/Azure/azure-sdk-for-java</url>
<distributionManagement>
<site>
<id>azure-java-build-docs</id>
<url>${site.url}/site/${project.artifactId}</url>
</site>
</distributionManagement>
<scm>
<url>scm:git:https://github.com/Azure/azure-sdk-for-java</url>
<connection>scm:git:git@github.com:Azure/azure-sdk-for-java.git</connection>
<tag>HEAD</tag>
</scm>
<dependencies>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-json</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-xml</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-core</artifactId>
<version>1.51.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-core-http-netty</artifactId>
<version>1.15.3</version>
</dependency>
<!-- Test Dependencies -->
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-core-test</artifactId>
<version>1.26.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

Просмотреть файл

@ -0,0 +1,190 @@
# Use case:
#
# The purpose of this script is to compact the steps required to regenerate TypeSpec into a single script.
#
# If 'com.azure.autorest.customization' tests fails, re-install 'customization-base'.
#
# Before running this script the 'tsp' profile must be built, 'mvn install -P local,tsp'.
param (
[int] $Parallelization = [Environment]::ProcessorCount
)
$ExitCode = 0
if ($Parallelization -lt 1) {
$Parallelization = 1
}
Write-Host "Parallelization: $Parallelization"
$generateScript = {
$tspFile = $_
$tspClientFile = $tspFile -replace 'main.tsp', 'client.tsp'
if (($tspClientFile -match 'client.tsp$') -and (Test-Path $tspClientFile)) {
$tspFile = $tspClientFile
}
# With TypeSpec code generation being parallelized, we need to make sure that the output directory is unique
# for each test run. We do this by appending a random number to the output directory.
# Without this, we could have multiple runs trying to write to the same directory which introduces race conditions.
$tspOptions = "--option ""@typespec/http-client-java.emitter-output-dir={project-root}/tsp-output/$(Get-Random)"""
if ($tspFile -match "type[\\/]enum[\\/]extensible[\\/]") {
# override namespace for reserved keyword "enum"
$tspOptions += " --option ""@typespec/http-client-java.namespace=com.type.enums.extensible"""
} elseif ($tspFile -match "type[\\/]enum[\\/]fixed[\\/]") {
# override namespace for reserved keyword "enum"
$tspOptions += " --option ""@typespec/http-client-java.namespace=com.type.enums.fixed"""
} elseif ($tspFile -match "azure[\\/]example[\\/]basic[\\/]") {
# override examples-directory
$tspOptions += " --option ""@typespec/http-client-java.examples-directory={project-root}/http/azure/example/basic/examples"""
} elseif ($tspFile -match "resiliency[\\/]srv-driven[\\/]old\.tsp") {
# override namespace for "resiliency/srv-driven/old.tsp" (make it different to that from "main.tsp")
$tspOptions += " --option ""@typespec/http-client-java.namespace=com.resiliency.servicedriven.v1"""
# enable advanced versioning for resiliency test
$tspOptions += " --option ""@typespec/http-client-java.advanced-versioning=true"""
$tspOptions += " --option ""@typespec/http-client-java.api-version=all"""
} elseif ($tspFile -match "resiliency[\\/]srv-driven[\\/]main\.tsp") {
# enable advanced versioning for resiliency test
$tspOptions += " --option ""@typespec/http-client-java.advanced-versioning=true"""
$tspOptions += " --option ""@typespec/http-client-java.api-version=all"""
} elseif ($tspFile -match "azure[\\/]resource-manager[\\/].*[\\/]main\.tsp") {
# for mgmt, do not generate tests due to random mock values
$tspOptions += " --option ""@typespec/http-client-java.generate-tests=false"""
# also generate with group-etag-headers=false since mgmt doesn't support etag grouping yet
$tspOptions += " --option ""@typespec/http-client-java.group-etag-headers=false"""
} elseif ($tspFile -match "tsp[\\/]versioning.tsp") {
# test generating from specific api-version
$tspOptions += " --option ""@typespec/http-client-java.api-version=2022-09-01"""
# exclude preview from service versions
$tspOptions += " --option ""@typespec/http-client-java.service-version-exclude-preview=true"""
} elseif ($tspFile -match "arm.tsp") {
# for mgmt, do not generate tests due to random mock values
$tspOptions += " --option ""@typespec/http-client-java.generate-tests=false"""
# also don't generate with stream-style-serialization as azure-core-management hasn't migrated to azure-json yet
$tspOptions += " --option ""@typespec/http-client-java.stream-style-serialization=false"""
# also generate with group-etag-headers=false since mgmt doesn't support etag grouping yet
$tspOptions += " --option ""@typespec/http-client-java.group-etag-headers=false"""
# also test generating from specific api-version
$tspOptions += " --option ""@typespec/http-client-java.api-version=2023-11-01"""
# exclude preview from service versions
$tspOptions += " --option ""@typespec/http-client-java.service-version-exclude-preview=true"""
} elseif ($tspFile -match "arm-stream-style-serialization.tsp") {
$tspOptions += " --option ""@typespec/http-client-java.stream-style-serialization=true"""
# for mgmt, do not generate tests due to random mock values
$tspOptions += " --option ""@typespec/http-client-java.generate-tests=false"""
# also generate with group-etag-headers=false since mgmt doesn't support etag grouping yet
$tspOptions += " --option ""@typespec/http-client-java.group-etag-headers=false"""
}
# Test customization for one of the TypeSpec definitions - naming.tsp
if ($tspFile -match "tsp[\\/]naming.tsp$") {
# Add the customization-class option for Java emitter
$tspOptions += " --option ""@typespec/http-client-java.customization-class=../../customization/src/main/java/CustomizationTest.java"""
}
$tspTrace = "--trace import-resolution --trace projection --trace http-client-java"
$tspCommand = "npx tsp compile $tspFile $tspOptions $tspTrace"
$timer = [Diagnostics.Stopwatch]::StartNew()
$generateOutput = Invoke-Expression $tspCommand
$timer.Stop()
$global:ExitCode = $global:ExitCode -bor $LASTEXITCODE
if ($LASTEXITCODE -ne 0) {
Write-Host "
========================
$tspCommand
========================
FAILED (Time elapsed: $($timer.ToString()))
$([String]::Join("`n", $generateOutput))
"
} else {
Write-Host "
========================
$tspCommand
========================
SUCCEEDED (Time elapsed: $($timer.ToString()))
"
}
if ($global:ExitCode -ne 0) {
exit $global:ExitCode
}
}
Set-Location ../../
npm install
npm run build
npm pack
Set-Location ./generator/http-client-generator-test
if (Test-Path node_modules) {
Remove-Item node_modules -Recurse -Force
}
if (Test-Path package-lock.json) {
Remove-Item package-lock.json
}
# delete output
if (Test-Path tsp-output) {
Remove-Item tsp-output -Recurse -Force
}
npm install
New-Item -Path ./existingcode/src/main/java/com/cadl/ -ItemType Directory -Force | Out-Null
if (Test-Path ./src/main/java/com/cadl/partialupdate) {
Copy-Item -Path ./src/main/java/com/cadl/partialupdate -Destination ./existingcode/src/main/java/com/cadl/partialupdate -Recurse -Force
}
if (Test-Path ./src/main) {
Remove-Item ./src/main -Recurse -Force
}
if (Test-Path ./src/samples) {
Remove-Item ./src/samples -Recurse -Force
}
if (Test-Path ./tsp-output) {
Remove-Item ./tsp-output -Recurse -Force
}
# run other local tests except partial update
$job = Get-Item ./tsp/* -Filter "*.tsp" -Exclude "*partialupdate*" | ForEach-Object -Parallel $generateScript -ThrottleLimit $Parallelization -AsJob
$job | Wait-Job -Timeout 600
$job | Receive-Job
# partial update test
npx tsp compile ./tsp/partialupdate.tsp --option="@typespec/http-client-java.emitter-output-dir={project-root}/existingcode"
Copy-Item -Path ./existingcode/src/main/java/com/cadl/partialupdate -Destination ./src/main/java/com/cadl/partialupdate -Recurse -Force
Remove-Item ./existingcode -Recurse -Force
# run cadl ranch tests sources
Copy-Item -Path node_modules/@azure-tools/cadl-ranch-specs/http -Destination ./ -Recurse -Force
# remove xml tests, emitter has not supported xml model
Remove-Item ./http/payload/xml -Recurse -Force
$job = (Get-ChildItem ./http -Include "main.tsp","old.tsp" -File -Recurse) | ForEach-Object -Parallel $generateScript -ThrottleLimit $Parallelization -AsJob
$job | Wait-Job -Timeout 1200
$job | Receive-Job
Remove-Item ./http -Recurse -Force
Copy-Item -Path ./tsp-output/*/src -Destination ./ -Recurse -Force -Exclude @("ReadmeSamples.java", "module-info.java")
Remove-Item ./tsp-output -Recurse -Force
if (Test-Path ./src/main/resources/META-INF/client-structure-service_apiview_properties.json) {
# client structure is generated from multiple client.tsp files and the last one to execute overwrites
# the api view properties file. Because the tests run in parallel, the order is not guaranteed. This
# causes git diff check to fail as the checked in file is not the same as the generated one.
Remove-Item ./src/main/resources/META-INF/client-structure-service_apiview_properties.json -Force
}

Просмотреть файл

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<name>Microsoft Autorest TypeSpec Tests code customization</name>
<description>This package contains code for Microsoft Autorest TypeSpec Tests code customization</description>
<groupId>com.microsoft.typespec</groupId>
<artifactId>http-client-generator-customization-test</artifactId>
<version>1.0.0-beta.1</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.microsoft.typespec</groupId>
<artifactId>http-client-generator-core</artifactId>
<version>1.0.0-beta.1</version> <!-- {x-version-update;com.azure.tools:azure-autorest-customization;external_dependency} -->
</dependency>
</dependencies>
</project>

Просмотреть файл

@ -0,0 +1,23 @@
import com.microsoft.typespec.http.client.generator.core.customization.ClassCustomization;
import com.microsoft.typespec.http.client.generator.core.customization.Customization;
import com.microsoft.typespec.http.client.generator.core.customization.LibraryCustomization;
import com.microsoft.typespec.http.client.generator.core.customization.PackageCustomization;
import org.slf4j.Logger;
import java.util.Arrays;
/**
* This class contains the customization code to customize the AutoRest generated code for App Configuration.
*/
public class CustomizationTest extends Customization {
@Override
public void customize(LibraryCustomization customization, Logger logger) {
logger.info("Customizing the NamingClient javadoc");
PackageCustomization packageCustomization = customization.getPackage("com.cadl.naming");
ClassCustomization classCustomization = packageCustomization.getClass("NamingClient");
classCustomization.getMethod("postWithResponse")
.getJavadoc()
.setDescription("Protocol method for POST operation.");
}
}

Просмотреть файл

@ -0,0 +1,29 @@
{
"name": "@typespec/http-client-java-tests",
"version": "0.1.0",
"type": "module",
"scripts": {
"format": "npm run -s prettier -- --write",
"check-format": "npm run prettier -- --check",
"prettier": "prettier --config ./.prettierrc.yaml **/*.tsp",
"testserver-run": "npx cadl-ranch serve ./node_modules/@azure-tools/cadl-ranch-specs/http --coverageFile ./cadl-ranch-coverage-java.json"
},
"dependencies": {
"@azure-tools/cadl-ranch-specs": "0.35.2",
"@typespec/http-client-java": "file:/../../typespec-http-client-java-0.1.0.tgz",
"@typespec/http-client-java-tests": "file:"
},
"overrides": {
"@typespec/compiler": "~0.59.0",
"@typespec/http": "~0.59.0",
"@typespec/rest": "~0.59.0",
"@typespec/versioning": "~0.59.0",
"@typespec/openapi": "~0.59.0",
"@typespec/xml": "~0.59.0",
"@azure-tools/typespec-azure-core": "~0.45.0",
"@azure-tools/typespec-client-generator-core": "~0.45.0",
"@azure-tools/typespec-azure-resource-manager": "~0.45.0",
"@azure-tools/typespec-autorest": "~0.45.0"
},
"private": true
}

Просмотреть файл

@ -0,0 +1,97 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.microsoft.typespec</groupId>
<artifactId>typespec-java-generator</artifactId>
<version>1.0.0-beta.1</version>
</parent>
<groupId>com.microsoft.typespec</groupId>
<artifactId>http-client-generator-test</artifactId>
<packaging>jar</packaging>
<name>http-client-generator-test</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-core</artifactId>
<version>1.51.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-json</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-xml</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-core-test</artifactId>
<version>1.26.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.13.2</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-core-management</artifactId>
<version>1.15.2</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-core-http-netty</artifactId>
<version>1.15.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.9.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<version>3.4.38</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.11.0</version>
<scope>test</scope>
</dependency>
<!-- bytebuddy dependencies are required for mockito 4.11.0 to work with Java 21. Mockito 4.11.0 is the last release -->
<!-- of Mockito supporting Java 8 as a baseline. -->
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>1.14.12</version> <!-- {x-version-update;testdep_net.bytebuddy:byte-buddy;external_dependency} -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy-agent</artifactId>
<version>1.14.12</version> <!-- {x-version-update;testdep_net.bytebuddy:byte-buddy-agent;external_dependency} -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.36</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

Просмотреть файл

@ -0,0 +1,357 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access;
import com._specs_.azure.clientgenerator.core.access.implementation.AccessClientImpl;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.ServiceClientBuilder;
import com.azure.core.client.traits.ConfigurationTrait;
import com.azure.core.client.traits.EndpointTrait;
import com.azure.core.client.traits.HttpTrait;
import com.azure.core.http.HttpClient;
import com.azure.core.http.HttpHeaders;
import com.azure.core.http.HttpPipeline;
import com.azure.core.http.HttpPipelineBuilder;
import com.azure.core.http.HttpPipelinePosition;
import com.azure.core.http.policy.AddDatePolicy;
import com.azure.core.http.policy.AddHeadersFromContextPolicy;
import com.azure.core.http.policy.AddHeadersPolicy;
import com.azure.core.http.policy.HttpLoggingPolicy;
import com.azure.core.http.policy.HttpLogOptions;
import com.azure.core.http.policy.HttpPipelinePolicy;
import com.azure.core.http.policy.HttpPolicyProviders;
import com.azure.core.http.policy.RequestIdPolicy;
import com.azure.core.http.policy.RetryOptions;
import com.azure.core.http.policy.RetryPolicy;
import com.azure.core.http.policy.UserAgentPolicy;
import com.azure.core.util.ClientOptions;
import com.azure.core.util.Configuration;
import com.azure.core.util.CoreUtils;
import com.azure.core.util.builder.ClientBuilderUtil;
import com.azure.core.util.logging.ClientLogger;
import com.azure.core.util.serializer.JacksonAdapter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* A builder for creating a new instance of the AccessClient type.
*/
@ServiceClientBuilder(
serviceClients = {
PublicOperationClient.class,
InternalOperationClient.class,
SharedModelInOperationClient.class,
RelativeModelInOperationClient.class,
PublicOperationAsyncClient.class,
InternalOperationAsyncClient.class,
SharedModelInOperationAsyncClient.class,
RelativeModelInOperationAsyncClient.class })
public final class AccessClientBuilder implements HttpTrait<AccessClientBuilder>,
ConfigurationTrait<AccessClientBuilder>, EndpointTrait<AccessClientBuilder> {
@Generated
private static final String SDK_NAME = "name";
@Generated
private static final String SDK_VERSION = "version";
@Generated
private static final Map<String, String> PROPERTIES
= CoreUtils.getProperties("_specs_-azure-clientgenerator-core-access.properties");
@Generated
private final List<HttpPipelinePolicy> pipelinePolicies;
/**
* Create an instance of the AccessClientBuilder.
*/
@Generated
public AccessClientBuilder() {
this.pipelinePolicies = new ArrayList<>();
}
/*
* The HTTP pipeline to send requests through.
*/
@Generated
private HttpPipeline pipeline;
/**
* {@inheritDoc}.
*/
@Generated
@Override
public AccessClientBuilder pipeline(HttpPipeline pipeline) {
if (this.pipeline != null && pipeline == null) {
LOGGER.atInfo().log("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.pipeline = pipeline;
return this;
}
/*
* The HTTP client used to send the request.
*/
@Generated
private HttpClient httpClient;
/**
* {@inheritDoc}.
*/
@Generated
@Override
public AccessClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/*
* The logging configuration for HTTP requests and responses.
*/
@Generated
private HttpLogOptions httpLogOptions;
/**
* {@inheritDoc}.
*/
@Generated
@Override
public AccessClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/*
* The client options such as application ID and custom headers to set on a request.
*/
@Generated
private ClientOptions clientOptions;
/**
* {@inheritDoc}.
*/
@Generated
@Override
public AccessClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/*
* The retry options to configure retry policy for failed requests.
*/
@Generated
private RetryOptions retryOptions;
/**
* {@inheritDoc}.
*/
@Generated
@Override
public AccessClientBuilder retryOptions(RetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* {@inheritDoc}.
*/
@Generated
@Override
public AccessClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.");
pipelinePolicies.add(customPolicy);
return this;
}
/*
* The configuration store that is used during construction of the service client.
*/
@Generated
private Configuration configuration;
/**
* {@inheritDoc}.
*/
@Generated
@Override
public AccessClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/*
* The service endpoint
*/
@Generated
private String endpoint;
/**
* {@inheritDoc}.
*/
@Generated
@Override
public AccessClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/*
* The retry policy that will attempt to retry failed requests, if applicable.
*/
@Generated
private RetryPolicy retryPolicy;
/**
* Sets The retry policy that will attempt to retry failed requests, if applicable.
*
* @param retryPolicy the retryPolicy value.
* @return the AccessClientBuilder.
*/
@Generated
public AccessClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Builds an instance of AccessClientImpl with the provided parameters.
*
* @return an instance of AccessClientImpl.
*/
@Generated
private AccessClientImpl buildInnerClient() {
this.validateClient();
HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline();
String localEndpoint = (endpoint != null) ? endpoint : "http://localhost:3000";
AccessClientImpl client
= new AccessClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), localEndpoint);
return client;
}
@Generated
private void validateClient() {
// This method is invoked from 'buildInnerClient'/'buildClient' method.
// Developer can customize this method, to validate that the necessary conditions are met for the new client.
}
@Generated
private HttpPipeline createHttpPipeline() {
Configuration buildConfiguration
= (configuration == null) ? Configuration.getGlobalConfiguration() : configuration;
HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions;
ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions;
List<HttpPipelinePolicy> policies = new ArrayList<>();
String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion");
String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions);
policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration));
policies.add(new RequestIdPolicy());
policies.add(new AddHeadersFromContextPolicy());
HttpHeaders headers = CoreUtils.createHttpHeadersFromClientOptions(localClientOptions);
if (headers != null) {
policies.add(new AddHeadersPolicy(headers));
}
this.pipelinePolicies.stream()
.filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL)
.forEach(p -> policies.add(p));
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy()));
policies.add(new AddDatePolicy());
this.pipelinePolicies.stream()
.filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY)
.forEach(p -> policies.add(p));
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(localHttpLogOptions));
HttpPipeline httpPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.clientOptions(localClientOptions)
.build();
return httpPipeline;
}
/**
* Builds an instance of PublicOperationAsyncClient class.
*
* @return an instance of PublicOperationAsyncClient.
*/
@Generated
public PublicOperationAsyncClient buildPublicOperationAsyncClient() {
return new PublicOperationAsyncClient(buildInnerClient().getPublicOperations());
}
/**
* Builds an instance of InternalOperationAsyncClient class.
*
* @return an instance of InternalOperationAsyncClient.
*/
@Generated
public InternalOperationAsyncClient buildInternalOperationAsyncClient() {
return new InternalOperationAsyncClient(buildInnerClient().getInternalOperations());
}
/**
* Builds an instance of SharedModelInOperationAsyncClient class.
*
* @return an instance of SharedModelInOperationAsyncClient.
*/
@Generated
public SharedModelInOperationAsyncClient buildSharedModelInOperationAsyncClient() {
return new SharedModelInOperationAsyncClient(buildInnerClient().getSharedModelInOperations());
}
/**
* Builds an instance of RelativeModelInOperationAsyncClient class.
*
* @return an instance of RelativeModelInOperationAsyncClient.
*/
@Generated
public RelativeModelInOperationAsyncClient buildRelativeModelInOperationAsyncClient() {
return new RelativeModelInOperationAsyncClient(buildInnerClient().getRelativeModelInOperations());
}
/**
* Builds an instance of PublicOperationClient class.
*
* @return an instance of PublicOperationClient.
*/
@Generated
public PublicOperationClient buildPublicOperationClient() {
return new PublicOperationClient(buildInnerClient().getPublicOperations());
}
/**
* Builds an instance of InternalOperationClient class.
*
* @return an instance of InternalOperationClient.
*/
@Generated
public InternalOperationClient buildInternalOperationClient() {
return new InternalOperationClient(buildInnerClient().getInternalOperations());
}
/**
* Builds an instance of SharedModelInOperationClient class.
*
* @return an instance of SharedModelInOperationClient.
*/
@Generated
public SharedModelInOperationClient buildSharedModelInOperationClient() {
return new SharedModelInOperationClient(buildInnerClient().getSharedModelInOperations());
}
/**
* Builds an instance of RelativeModelInOperationClient class.
*
* @return an instance of RelativeModelInOperationClient.
*/
@Generated
public RelativeModelInOperationClient buildRelativeModelInOperationClient() {
return new RelativeModelInOperationClient(buildInnerClient().getRelativeModelInOperations());
}
private static final ClientLogger LOGGER = new ClientLogger(AccessClientBuilder.class);
}

Просмотреть файл

@ -0,0 +1,183 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access;
import com._specs_.azure.clientgenerator.core.access.implementation.InternalOperationsImpl;
import com._specs_.azure.clientgenerator.core.access.implementation.models.InternalDecoratorModelInInternal;
import com._specs_.azure.clientgenerator.core.access.implementation.models.NoDecoratorModelInInternal;
import com._specs_.azure.clientgenerator.core.access.models.PublicDecoratorModelInInternal;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.exception.ClientAuthenticationException;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.util.BinaryData;
import com.azure.core.util.FluxUtil;
import reactor.core.publisher.Mono;
/**
* Initializes a new instance of the asynchronous AccessClient type.
*/
@ServiceClient(builder = AccessClientBuilder.class, isAsync = true)
public final class InternalOperationAsyncClient {
@Generated
private final InternalOperationsImpl serviceClient;
/**
* Initializes an instance of InternalOperationAsyncClient class.
*
* @param serviceClient the service client implementation.
*/
@Generated
InternalOperationAsyncClient(InternalOperationsImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* The noDecoratorInInternal operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in an internal operation, should be generated but not exported along with {@link Response} on
* successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<BinaryData>> noDecoratorInInternalWithResponse(String name, RequestOptions requestOptions) {
return this.serviceClient.noDecoratorInInternalWithResponseAsync(name, requestOptions);
}
/**
* The internalDecoratorInInternal operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in an internal operation, should be generated but not exported along with {@link Response} on
* successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<BinaryData>> internalDecoratorInInternalWithResponse(String name, RequestOptions requestOptions) {
return this.serviceClient.internalDecoratorInInternalWithResponseAsync(name, requestOptions);
}
/**
* The publicDecoratorInInternal operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in an internal operation but with public decorator, should be generated and exported along with
* {@link Response} on successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<BinaryData>> publicDecoratorInInternalWithResponse(String name, RequestOptions requestOptions) {
return this.serviceClient.publicDecoratorInInternalWithResponseAsync(name, requestOptions);
}
/**
* The noDecoratorInInternal operation.
*
* @param name The name parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return used in an internal operation, should be generated but not exported on successful completion of
* {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<NoDecoratorModelInInternal> noDecoratorInInternal(String name) {
// Generated convenience method for noDecoratorInInternalWithResponse
RequestOptions requestOptions = new RequestOptions();
return noDecoratorInInternalWithResponse(name, requestOptions).flatMap(FluxUtil::toMono)
.map(protocolMethodData -> protocolMethodData.toObject(NoDecoratorModelInInternal.class));
}
/**
* The internalDecoratorInInternal operation.
*
* @param name The name parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return used in an internal operation, should be generated but not exported on successful completion of
* {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<InternalDecoratorModelInInternal> internalDecoratorInInternal(String name) {
// Generated convenience method for internalDecoratorInInternalWithResponse
RequestOptions requestOptions = new RequestOptions();
return internalDecoratorInInternalWithResponse(name, requestOptions).flatMap(FluxUtil::toMono)
.map(protocolMethodData -> protocolMethodData.toObject(InternalDecoratorModelInInternal.class));
}
/**
* The publicDecoratorInInternal operation.
*
* @param name The name parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return used in an internal operation but with public decorator, should be generated and exported on successful
* completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<PublicDecoratorModelInInternal> publicDecoratorInInternal(String name) {
// Generated convenience method for publicDecoratorInInternalWithResponse
RequestOptions requestOptions = new RequestOptions();
return publicDecoratorInInternalWithResponse(name, requestOptions).flatMap(FluxUtil::toMono)
.map(protocolMethodData -> protocolMethodData.toObject(PublicDecoratorModelInInternal.class));
}
}

Просмотреть файл

@ -0,0 +1,176 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access;
import com._specs_.azure.clientgenerator.core.access.implementation.InternalOperationsImpl;
import com._specs_.azure.clientgenerator.core.access.implementation.models.InternalDecoratorModelInInternal;
import com._specs_.azure.clientgenerator.core.access.implementation.models.NoDecoratorModelInInternal;
import com._specs_.azure.clientgenerator.core.access.models.PublicDecoratorModelInInternal;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.exception.ClientAuthenticationException;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.util.BinaryData;
/**
* Initializes a new instance of the synchronous AccessClient type.
*/
@ServiceClient(builder = AccessClientBuilder.class)
public final class InternalOperationClient {
@Generated
private final InternalOperationsImpl serviceClient;
/**
* Initializes an instance of InternalOperationClient class.
*
* @param serviceClient the service client implementation.
*/
@Generated
InternalOperationClient(InternalOperationsImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* The noDecoratorInInternal operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in an internal operation, should be generated but not exported along with {@link Response}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
Response<BinaryData> noDecoratorInInternalWithResponse(String name, RequestOptions requestOptions) {
return this.serviceClient.noDecoratorInInternalWithResponse(name, requestOptions);
}
/**
* The internalDecoratorInInternal operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in an internal operation, should be generated but not exported along with {@link Response}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
Response<BinaryData> internalDecoratorInInternalWithResponse(String name, RequestOptions requestOptions) {
return this.serviceClient.internalDecoratorInInternalWithResponse(name, requestOptions);
}
/**
* The publicDecoratorInInternal operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in an internal operation but with public decorator, should be generated and exported along with
* {@link Response}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
Response<BinaryData> publicDecoratorInInternalWithResponse(String name, RequestOptions requestOptions) {
return this.serviceClient.publicDecoratorInInternalWithResponse(name, requestOptions);
}
/**
* The noDecoratorInInternal operation.
*
* @param name The name parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return used in an internal operation, should be generated but not exported.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
NoDecoratorModelInInternal noDecoratorInInternal(String name) {
// Generated convenience method for noDecoratorInInternalWithResponse
RequestOptions requestOptions = new RequestOptions();
return noDecoratorInInternalWithResponse(name, requestOptions).getValue()
.toObject(NoDecoratorModelInInternal.class);
}
/**
* The internalDecoratorInInternal operation.
*
* @param name The name parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return used in an internal operation, should be generated but not exported.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
InternalDecoratorModelInInternal internalDecoratorInInternal(String name) {
// Generated convenience method for internalDecoratorInInternalWithResponse
RequestOptions requestOptions = new RequestOptions();
return internalDecoratorInInternalWithResponse(name, requestOptions).getValue()
.toObject(InternalDecoratorModelInInternal.class);
}
/**
* The publicDecoratorInInternal operation.
*
* @param name The name parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return used in an internal operation but with public decorator, should be generated and exported.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
PublicDecoratorModelInInternal publicDecoratorInInternal(String name) {
// Generated convenience method for publicDecoratorInInternalWithResponse
RequestOptions requestOptions = new RequestOptions();
return publicDecoratorInInternalWithResponse(name, requestOptions).getValue()
.toObject(PublicDecoratorModelInInternal.class);
}
}

Просмотреть файл

@ -0,0 +1,133 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access;
import com._specs_.azure.clientgenerator.core.access.implementation.PublicOperationsImpl;
import com._specs_.azure.clientgenerator.core.access.models.NoDecoratorModelInPublic;
import com._specs_.azure.clientgenerator.core.access.models.PublicDecoratorModelInPublic;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.exception.ClientAuthenticationException;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.util.BinaryData;
import com.azure.core.util.FluxUtil;
import reactor.core.publisher.Mono;
/**
* Initializes a new instance of the asynchronous AccessClient type.
*/
@ServiceClient(builder = AccessClientBuilder.class, isAsync = true)
public final class PublicOperationAsyncClient {
@Generated
private final PublicOperationsImpl serviceClient;
/**
* Initializes an instance of PublicOperationAsyncClient class.
*
* @param serviceClient the service client implementation.
*/
@Generated
PublicOperationAsyncClient(PublicOperationsImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* The noDecoratorInPublic operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in a public operation, should be generated and exported along with {@link Response} on successful
* completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BinaryData>> noDecoratorInPublicWithResponse(String name, RequestOptions requestOptions) {
return this.serviceClient.noDecoratorInPublicWithResponseAsync(name, requestOptions);
}
/**
* The publicDecoratorInPublic operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in a public operation, should be generated and exported along with {@link Response} on successful
* completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BinaryData>> publicDecoratorInPublicWithResponse(String name, RequestOptions requestOptions) {
return this.serviceClient.publicDecoratorInPublicWithResponseAsync(name, requestOptions);
}
/**
* The noDecoratorInPublic operation.
*
* @param name The name parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return used in a public operation, should be generated and exported on successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NoDecoratorModelInPublic> noDecoratorInPublic(String name) {
// Generated convenience method for noDecoratorInPublicWithResponse
RequestOptions requestOptions = new RequestOptions();
return noDecoratorInPublicWithResponse(name, requestOptions).flatMap(FluxUtil::toMono)
.map(protocolMethodData -> protocolMethodData.toObject(NoDecoratorModelInPublic.class));
}
/**
* The publicDecoratorInPublic operation.
*
* @param name The name parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return used in a public operation, should be generated and exported on successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<PublicDecoratorModelInPublic> publicDecoratorInPublic(String name) {
// Generated convenience method for publicDecoratorInPublicWithResponse
RequestOptions requestOptions = new RequestOptions();
return publicDecoratorInPublicWithResponse(name, requestOptions).flatMap(FluxUtil::toMono)
.map(protocolMethodData -> protocolMethodData.toObject(PublicDecoratorModelInPublic.class));
}
}

Просмотреть файл

@ -0,0 +1,129 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access;
import com._specs_.azure.clientgenerator.core.access.implementation.PublicOperationsImpl;
import com._specs_.azure.clientgenerator.core.access.models.NoDecoratorModelInPublic;
import com._specs_.azure.clientgenerator.core.access.models.PublicDecoratorModelInPublic;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.exception.ClientAuthenticationException;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.util.BinaryData;
/**
* Initializes a new instance of the synchronous AccessClient type.
*/
@ServiceClient(builder = AccessClientBuilder.class)
public final class PublicOperationClient {
@Generated
private final PublicOperationsImpl serviceClient;
/**
* Initializes an instance of PublicOperationClient class.
*
* @param serviceClient the service client implementation.
*/
@Generated
PublicOperationClient(PublicOperationsImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* The noDecoratorInPublic operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in a public operation, should be generated and exported along with {@link Response}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BinaryData> noDecoratorInPublicWithResponse(String name, RequestOptions requestOptions) {
return this.serviceClient.noDecoratorInPublicWithResponse(name, requestOptions);
}
/**
* The publicDecoratorInPublic operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in a public operation, should be generated and exported along with {@link Response}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BinaryData> publicDecoratorInPublicWithResponse(String name, RequestOptions requestOptions) {
return this.serviceClient.publicDecoratorInPublicWithResponse(name, requestOptions);
}
/**
* The noDecoratorInPublic operation.
*
* @param name The name parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return used in a public operation, should be generated and exported.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public NoDecoratorModelInPublic noDecoratorInPublic(String name) {
// Generated convenience method for noDecoratorInPublicWithResponse
RequestOptions requestOptions = new RequestOptions();
return noDecoratorInPublicWithResponse(name, requestOptions).getValue()
.toObject(NoDecoratorModelInPublic.class);
}
/**
* The publicDecoratorInPublic operation.
*
* @param name The name parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return used in a public operation, should be generated and exported.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public PublicDecoratorModelInPublic publicDecoratorInPublic(String name) {
// Generated convenience method for publicDecoratorInPublicWithResponse
RequestOptions requestOptions = new RequestOptions();
return publicDecoratorInPublicWithResponse(name, requestOptions).getValue()
.toObject(PublicDecoratorModelInPublic.class);
}
}

Просмотреть файл

@ -0,0 +1,173 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access;
import com._specs_.azure.clientgenerator.core.access.implementation.RelativeModelInOperationsImpl;
import com._specs_.azure.clientgenerator.core.access.implementation.models.AbstractModel;
import com._specs_.azure.clientgenerator.core.access.implementation.models.OuterModel;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.exception.ClientAuthenticationException;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.util.BinaryData;
import com.azure.core.util.FluxUtil;
import reactor.core.publisher.Mono;
/**
* Initializes a new instance of the asynchronous AccessClient type.
*/
@ServiceClient(builder = AccessClientBuilder.class, isAsync = true)
public final class RelativeModelInOperationAsyncClient {
@Generated
private final RelativeModelInOperationsImpl serviceClient;
/**
* Initializes an instance of RelativeModelInOperationAsyncClient class.
*
* @param serviceClient the service client implementation.
*/
@Generated
RelativeModelInOperationAsyncClient(RelativeModelInOperationsImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* Expected query parameter: name=&lt;any string&gt;
* Expected response body:
* ```json
* {
* "name": &lt;any string&gt;,
* "inner":
* {
* "name": &lt;any string&gt;
* }
* }
* ```.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* inner (Required): {
* name: String (Required)
* }
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in internal operations, should be generated but not exported along with {@link Response} on
* successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<BinaryData>> operationWithResponse(String name, RequestOptions requestOptions) {
return this.serviceClient.operationWithResponseAsync(name, requestOptions);
}
/**
* Expected query parameter: kind=&lt;any string&gt;
* Expected response body:
* ```json
* {
* "name": &lt;any string&gt;,
* "kind": "real"
* }
* ```.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* kind: String (Required)
* name: String (Required)
* }
* }</pre>
*
* @param kind The kind parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in internal operations, should be generated but not exported along with {@link Response} on
* successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<BinaryData>> discriminatorWithResponse(String kind, RequestOptions requestOptions) {
return this.serviceClient.discriminatorWithResponseAsync(kind, requestOptions);
}
/**
* Expected query parameter: name=&lt;any string&gt;
* Expected response body:
* ```json
* {
* "name": &lt;any string&gt;,
* "inner":
* {
* "name": &lt;any string&gt;
* }
* }
* ```.
*
* @param name The name parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return used in internal operations, should be generated but not exported on successful completion of
* {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<OuterModel> operation(String name) {
// Generated convenience method for operationWithResponse
RequestOptions requestOptions = new RequestOptions();
return operationWithResponse(name, requestOptions).flatMap(FluxUtil::toMono)
.map(protocolMethodData -> protocolMethodData.toObject(OuterModel.class));
}
/**
* Expected query parameter: kind=&lt;any string&gt;
* Expected response body:
* ```json
* {
* "name": &lt;any string&gt;,
* "kind": "real"
* }
* ```.
*
* @param kind The kind parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return used in internal operations, should be generated but not exported on successful completion of
* {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<AbstractModel> discriminator(String kind) {
// Generated convenience method for discriminatorWithResponse
RequestOptions requestOptions = new RequestOptions();
return discriminatorWithResponse(kind, requestOptions).flatMap(FluxUtil::toMono)
.map(protocolMethodData -> protocolMethodData.toObject(AbstractModel.class));
}
}

Просмотреть файл

@ -0,0 +1,165 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access;
import com._specs_.azure.clientgenerator.core.access.implementation.RelativeModelInOperationsImpl;
import com._specs_.azure.clientgenerator.core.access.implementation.models.AbstractModel;
import com._specs_.azure.clientgenerator.core.access.implementation.models.OuterModel;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.exception.ClientAuthenticationException;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.util.BinaryData;
/**
* Initializes a new instance of the synchronous AccessClient type.
*/
@ServiceClient(builder = AccessClientBuilder.class)
public final class RelativeModelInOperationClient {
@Generated
private final RelativeModelInOperationsImpl serviceClient;
/**
* Initializes an instance of RelativeModelInOperationClient class.
*
* @param serviceClient the service client implementation.
*/
@Generated
RelativeModelInOperationClient(RelativeModelInOperationsImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* Expected query parameter: name=&lt;any string&gt;
* Expected response body:
* ```json
* {
* "name": &lt;any string&gt;,
* "inner":
* {
* "name": &lt;any string&gt;
* }
* }
* ```.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* inner (Required): {
* name: String (Required)
* }
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in internal operations, should be generated but not exported along with {@link Response}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
Response<BinaryData> operationWithResponse(String name, RequestOptions requestOptions) {
return this.serviceClient.operationWithResponse(name, requestOptions);
}
/**
* Expected query parameter: kind=&lt;any string&gt;
* Expected response body:
* ```json
* {
* "name": &lt;any string&gt;,
* "kind": "real"
* }
* ```.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* kind: String (Required)
* name: String (Required)
* }
* }</pre>
*
* @param kind The kind parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in internal operations, should be generated but not exported along with {@link Response}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
Response<BinaryData> discriminatorWithResponse(String kind, RequestOptions requestOptions) {
return this.serviceClient.discriminatorWithResponse(kind, requestOptions);
}
/**
* Expected query parameter: name=&lt;any string&gt;
* Expected response body:
* ```json
* {
* "name": &lt;any string&gt;,
* "inner":
* {
* "name": &lt;any string&gt;
* }
* }
* ```.
*
* @param name The name parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return used in internal operations, should be generated but not exported.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
OuterModel operation(String name) {
// Generated convenience method for operationWithResponse
RequestOptions requestOptions = new RequestOptions();
return operationWithResponse(name, requestOptions).getValue().toObject(OuterModel.class);
}
/**
* Expected query parameter: kind=&lt;any string&gt;
* Expected response body:
* ```json
* {
* "name": &lt;any string&gt;,
* "kind": "real"
* }
* ```.
*
* @param kind The kind parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return used in internal operations, should be generated but not exported.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
AbstractModel discriminator(String kind) {
// Generated convenience method for discriminatorWithResponse
RequestOptions requestOptions = new RequestOptions();
return discriminatorWithResponse(kind, requestOptions).getValue().toObject(AbstractModel.class);
}
}

Просмотреть файл

@ -0,0 +1,132 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access;
import com._specs_.azure.clientgenerator.core.access.implementation.SharedModelInOperationsImpl;
import com._specs_.azure.clientgenerator.core.access.models.SharedModel;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.exception.ClientAuthenticationException;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.util.BinaryData;
import com.azure.core.util.FluxUtil;
import reactor.core.publisher.Mono;
/**
* Initializes a new instance of the asynchronous AccessClient type.
*/
@ServiceClient(builder = AccessClientBuilder.class, isAsync = true)
public final class SharedModelInOperationAsyncClient {
@Generated
private final SharedModelInOperationsImpl serviceClient;
/**
* Initializes an instance of SharedModelInOperationAsyncClient class.
*
* @param serviceClient the service client implementation.
*/
@Generated
SharedModelInOperationAsyncClient(SharedModelInOperationsImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* The publicMethod operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used by both public and internal operation along with {@link Response} on successful completion of
* {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BinaryData>> publicMethodWithResponse(String name, RequestOptions requestOptions) {
return this.serviceClient.publicMethodWithResponseAsync(name, requestOptions);
}
/**
* The internal operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used by both public and internal operation along with {@link Response} on successful completion of
* {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<BinaryData>> internalWithResponse(String name, RequestOptions requestOptions) {
return this.serviceClient.internalWithResponseAsync(name, requestOptions);
}
/**
* The publicMethod operation.
*
* @param name The name parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return used by both public and internal operation on successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SharedModel> publicMethod(String name) {
// Generated convenience method for publicMethodWithResponse
RequestOptions requestOptions = new RequestOptions();
return publicMethodWithResponse(name, requestOptions).flatMap(FluxUtil::toMono)
.map(protocolMethodData -> protocolMethodData.toObject(SharedModel.class));
}
/**
* The internal operation.
*
* @param name The name parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return used by both public and internal operation on successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<SharedModel> internal(String name) {
// Generated convenience method for internalWithResponse
RequestOptions requestOptions = new RequestOptions();
return internalWithResponse(name, requestOptions).flatMap(FluxUtil::toMono)
.map(protocolMethodData -> protocolMethodData.toObject(SharedModel.class));
}
}

Просмотреть файл

@ -0,0 +1,126 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access;
import com._specs_.azure.clientgenerator.core.access.implementation.SharedModelInOperationsImpl;
import com._specs_.azure.clientgenerator.core.access.models.SharedModel;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.exception.ClientAuthenticationException;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.util.BinaryData;
/**
* Initializes a new instance of the synchronous AccessClient type.
*/
@ServiceClient(builder = AccessClientBuilder.class)
public final class SharedModelInOperationClient {
@Generated
private final SharedModelInOperationsImpl serviceClient;
/**
* Initializes an instance of SharedModelInOperationClient class.
*
* @param serviceClient the service client implementation.
*/
@Generated
SharedModelInOperationClient(SharedModelInOperationsImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* The publicMethod operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used by both public and internal operation along with {@link Response}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BinaryData> publicMethodWithResponse(String name, RequestOptions requestOptions) {
return this.serviceClient.publicMethodWithResponse(name, requestOptions);
}
/**
* The internal operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used by both public and internal operation along with {@link Response}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
Response<BinaryData> internalWithResponse(String name, RequestOptions requestOptions) {
return this.serviceClient.internalWithResponse(name, requestOptions);
}
/**
* The publicMethod operation.
*
* @param name The name parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return used by both public and internal operation.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public SharedModel publicMethod(String name) {
// Generated convenience method for publicMethodWithResponse
RequestOptions requestOptions = new RequestOptions();
return publicMethodWithResponse(name, requestOptions).getValue().toObject(SharedModel.class);
}
/**
* The internal operation.
*
* @param name The name parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return used by both public and internal operation.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
SharedModel internal(String name) {
// Generated convenience method for internalWithResponse
RequestOptions requestOptions = new RequestOptions();
return internalWithResponse(name, requestOptions).getValue().toObject(SharedModel.class);
}
}

Просмотреть файл

@ -0,0 +1,152 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access.implementation;
import com.azure.core.http.HttpPipeline;
import com.azure.core.http.HttpPipelineBuilder;
import com.azure.core.http.policy.RetryPolicy;
import com.azure.core.http.policy.UserAgentPolicy;
import com.azure.core.util.serializer.JacksonAdapter;
import com.azure.core.util.serializer.SerializerAdapter;
/**
* Initializes a new instance of the AccessClient type.
*/
public final class AccessClientImpl {
/**
* Service host.
*/
private final String endpoint;
/**
* Gets Service host.
*
* @return the endpoint value.
*/
public String getEndpoint() {
return this.endpoint;
}
/**
* The HTTP pipeline to send requests through.
*/
private final HttpPipeline httpPipeline;
/**
* Gets The HTTP pipeline to send requests through.
*
* @return the httpPipeline value.
*/
public HttpPipeline getHttpPipeline() {
return this.httpPipeline;
}
/**
* The serializer to serialize an object into a string.
*/
private final SerializerAdapter serializerAdapter;
/**
* Gets The serializer to serialize an object into a string.
*
* @return the serializerAdapter value.
*/
public SerializerAdapter getSerializerAdapter() {
return this.serializerAdapter;
}
/**
* The PublicOperationsImpl object to access its operations.
*/
private final PublicOperationsImpl publicOperations;
/**
* Gets the PublicOperationsImpl object to access its operations.
*
* @return the PublicOperationsImpl object.
*/
public PublicOperationsImpl getPublicOperations() {
return this.publicOperations;
}
/**
* The InternalOperationsImpl object to access its operations.
*/
private final InternalOperationsImpl internalOperations;
/**
* Gets the InternalOperationsImpl object to access its operations.
*
* @return the InternalOperationsImpl object.
*/
public InternalOperationsImpl getInternalOperations() {
return this.internalOperations;
}
/**
* The SharedModelInOperationsImpl object to access its operations.
*/
private final SharedModelInOperationsImpl sharedModelInOperations;
/**
* Gets the SharedModelInOperationsImpl object to access its operations.
*
* @return the SharedModelInOperationsImpl object.
*/
public SharedModelInOperationsImpl getSharedModelInOperations() {
return this.sharedModelInOperations;
}
/**
* The RelativeModelInOperationsImpl object to access its operations.
*/
private final RelativeModelInOperationsImpl relativeModelInOperations;
/**
* Gets the RelativeModelInOperationsImpl object to access its operations.
*
* @return the RelativeModelInOperationsImpl object.
*/
public RelativeModelInOperationsImpl getRelativeModelInOperations() {
return this.relativeModelInOperations;
}
/**
* Initializes an instance of AccessClient client.
*
* @param endpoint Service host.
*/
public AccessClientImpl(String endpoint) {
this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(),
JacksonAdapter.createDefaultSerializerAdapter(), endpoint);
}
/**
* Initializes an instance of AccessClient client.
*
* @param httpPipeline The HTTP pipeline to send requests through.
* @param endpoint Service host.
*/
public AccessClientImpl(HttpPipeline httpPipeline, String endpoint) {
this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), endpoint);
}
/**
* Initializes an instance of AccessClient client.
*
* @param httpPipeline The HTTP pipeline to send requests through.
* @param serializerAdapter The serializer to serialize an object into a string.
* @param endpoint Service host.
*/
public AccessClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint) {
this.httpPipeline = httpPipeline;
this.serializerAdapter = serializerAdapter;
this.endpoint = endpoint;
this.publicOperations = new PublicOperationsImpl(this);
this.internalOperations = new InternalOperationsImpl(this);
this.sharedModelInOperations = new SharedModelInOperationsImpl(this);
this.relativeModelInOperations = new RelativeModelInOperationsImpl(this);
}
}

Просмотреть файл

@ -0,0 +1,277 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access.implementation;
import com.azure.core.annotation.ExpectedResponses;
import com.azure.core.annotation.Get;
import com.azure.core.annotation.HeaderParam;
import com.azure.core.annotation.Host;
import com.azure.core.annotation.HostParam;
import com.azure.core.annotation.QueryParam;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceInterface;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.annotation.UnexpectedResponseExceptionType;
import com.azure.core.exception.ClientAuthenticationException;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.RestProxy;
import com.azure.core.util.BinaryData;
import com.azure.core.util.Context;
import com.azure.core.util.FluxUtil;
import reactor.core.publisher.Mono;
/**
* An instance of this class provides access to all the operations defined in InternalOperations.
*/
public final class InternalOperationsImpl {
/**
* The proxy service used to perform REST calls.
*/
private final InternalOperationsService service;
/**
* The service client containing this operation class.
*/
private final AccessClientImpl client;
/**
* Initializes an instance of InternalOperationsImpl.
*
* @param client the instance of the service client containing this operation class.
*/
InternalOperationsImpl(AccessClientImpl client) {
this.service = RestProxy.create(InternalOperationsService.class, client.getHttpPipeline(),
client.getSerializerAdapter());
this.client = client;
}
/**
* The interface defining all the services for AccessClientInternalOperations to be used by the proxy service to
* perform REST calls.
*/
@Host("{endpoint}")
@ServiceInterface(name = "AccessClientInternal")
public interface InternalOperationsService {
@Get("/azure/client-generator-core/access/internalOperation/noDecoratorInInternal")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Mono<Response<BinaryData>> noDecoratorInInternal(@HostParam("endpoint") String endpoint,
@QueryParam("name") String name, @HeaderParam("Accept") String accept, RequestOptions requestOptions,
Context context);
@Get("/azure/client-generator-core/access/internalOperation/noDecoratorInInternal")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Response<BinaryData> noDecoratorInInternalSync(@HostParam("endpoint") String endpoint,
@QueryParam("name") String name, @HeaderParam("Accept") String accept, RequestOptions requestOptions,
Context context);
@Get("/azure/client-generator-core/access/internalOperation/internalDecoratorInInternal")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Mono<Response<BinaryData>> internalDecoratorInInternal(@HostParam("endpoint") String endpoint,
@QueryParam("name") String name, @HeaderParam("Accept") String accept, RequestOptions requestOptions,
Context context);
@Get("/azure/client-generator-core/access/internalOperation/internalDecoratorInInternal")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Response<BinaryData> internalDecoratorInInternalSync(@HostParam("endpoint") String endpoint,
@QueryParam("name") String name, @HeaderParam("Accept") String accept, RequestOptions requestOptions,
Context context);
@Get("/azure/client-generator-core/access/internalOperation/publicDecoratorInInternal")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Mono<Response<BinaryData>> publicDecoratorInInternal(@HostParam("endpoint") String endpoint,
@QueryParam("name") String name, @HeaderParam("Accept") String accept, RequestOptions requestOptions,
Context context);
@Get("/azure/client-generator-core/access/internalOperation/publicDecoratorInInternal")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Response<BinaryData> publicDecoratorInInternalSync(@HostParam("endpoint") String endpoint,
@QueryParam("name") String name, @HeaderParam("Accept") String accept, RequestOptions requestOptions,
Context context);
}
/**
* The noDecoratorInInternal operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in an internal operation, should be generated but not exported along with {@link Response} on
* successful completion of {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BinaryData>> noDecoratorInInternalWithResponseAsync(String name,
RequestOptions requestOptions) {
final String accept = "application/json";
return FluxUtil.withContext(
context -> service.noDecoratorInInternal(this.client.getEndpoint(), name, accept, requestOptions, context));
}
/**
* The noDecoratorInInternal operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in an internal operation, should be generated but not exported along with {@link Response}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BinaryData> noDecoratorInInternalWithResponse(String name, RequestOptions requestOptions) {
final String accept = "application/json";
return service.noDecoratorInInternalSync(this.client.getEndpoint(), name, accept, requestOptions, Context.NONE);
}
/**
* The internalDecoratorInInternal operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in an internal operation, should be generated but not exported along with {@link Response} on
* successful completion of {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BinaryData>> internalDecoratorInInternalWithResponseAsync(String name,
RequestOptions requestOptions) {
final String accept = "application/json";
return FluxUtil.withContext(context -> service.internalDecoratorInInternal(this.client.getEndpoint(), name,
accept, requestOptions, context));
}
/**
* The internalDecoratorInInternal operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in an internal operation, should be generated but not exported along with {@link Response}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BinaryData> internalDecoratorInInternalWithResponse(String name, RequestOptions requestOptions) {
final String accept = "application/json";
return service.internalDecoratorInInternalSync(this.client.getEndpoint(), name, accept, requestOptions,
Context.NONE);
}
/**
* The publicDecoratorInInternal operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in an internal operation but with public decorator, should be generated and exported along with
* {@link Response} on successful completion of {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BinaryData>> publicDecoratorInInternalWithResponseAsync(String name,
RequestOptions requestOptions) {
final String accept = "application/json";
return FluxUtil.withContext(context -> service.publicDecoratorInInternal(this.client.getEndpoint(), name,
accept, requestOptions, context));
}
/**
* The publicDecoratorInInternal operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in an internal operation but with public decorator, should be generated and exported along with
* {@link Response}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BinaryData> publicDecoratorInInternalWithResponse(String name, RequestOptions requestOptions) {
final String accept = "application/json";
return service.publicDecoratorInInternalSync(this.client.getEndpoint(), name, accept, requestOptions,
Context.NONE);
}
}

Просмотреть файл

@ -0,0 +1,203 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access.implementation;
import com.azure.core.annotation.ExpectedResponses;
import com.azure.core.annotation.Get;
import com.azure.core.annotation.HeaderParam;
import com.azure.core.annotation.Host;
import com.azure.core.annotation.HostParam;
import com.azure.core.annotation.QueryParam;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceInterface;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.annotation.UnexpectedResponseExceptionType;
import com.azure.core.exception.ClientAuthenticationException;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.RestProxy;
import com.azure.core.util.BinaryData;
import com.azure.core.util.Context;
import com.azure.core.util.FluxUtil;
import reactor.core.publisher.Mono;
/**
* An instance of this class provides access to all the operations defined in PublicOperations.
*/
public final class PublicOperationsImpl {
/**
* The proxy service used to perform REST calls.
*/
private final PublicOperationsService service;
/**
* The service client containing this operation class.
*/
private final AccessClientImpl client;
/**
* Initializes an instance of PublicOperationsImpl.
*
* @param client the instance of the service client containing this operation class.
*/
PublicOperationsImpl(AccessClientImpl client) {
this.service
= RestProxy.create(PublicOperationsService.class, client.getHttpPipeline(), client.getSerializerAdapter());
this.client = client;
}
/**
* The interface defining all the services for AccessClientPublicOperations to be used by the proxy service to
* perform REST calls.
*/
@Host("{endpoint}")
@ServiceInterface(name = "AccessClientPublicOp")
public interface PublicOperationsService {
@Get("/azure/client-generator-core/access/publicOperation/noDecoratorInPublic")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Mono<Response<BinaryData>> noDecoratorInPublic(@HostParam("endpoint") String endpoint,
@QueryParam("name") String name, @HeaderParam("Accept") String accept, RequestOptions requestOptions,
Context context);
@Get("/azure/client-generator-core/access/publicOperation/noDecoratorInPublic")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Response<BinaryData> noDecoratorInPublicSync(@HostParam("endpoint") String endpoint,
@QueryParam("name") String name, @HeaderParam("Accept") String accept, RequestOptions requestOptions,
Context context);
@Get("/azure/client-generator-core/access/publicOperation/publicDecoratorInPublic")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Mono<Response<BinaryData>> publicDecoratorInPublic(@HostParam("endpoint") String endpoint,
@QueryParam("name") String name, @HeaderParam("Accept") String accept, RequestOptions requestOptions,
Context context);
@Get("/azure/client-generator-core/access/publicOperation/publicDecoratorInPublic")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Response<BinaryData> publicDecoratorInPublicSync(@HostParam("endpoint") String endpoint,
@QueryParam("name") String name, @HeaderParam("Accept") String accept, RequestOptions requestOptions,
Context context);
}
/**
* The noDecoratorInPublic operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in a public operation, should be generated and exported along with {@link Response} on successful
* completion of {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BinaryData>> noDecoratorInPublicWithResponseAsync(String name, RequestOptions requestOptions) {
final String accept = "application/json";
return FluxUtil.withContext(
context -> service.noDecoratorInPublic(this.client.getEndpoint(), name, accept, requestOptions, context));
}
/**
* The noDecoratorInPublic operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in a public operation, should be generated and exported along with {@link Response}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BinaryData> noDecoratorInPublicWithResponse(String name, RequestOptions requestOptions) {
final String accept = "application/json";
return service.noDecoratorInPublicSync(this.client.getEndpoint(), name, accept, requestOptions, Context.NONE);
}
/**
* The publicDecoratorInPublic operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in a public operation, should be generated and exported along with {@link Response} on successful
* completion of {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BinaryData>> publicDecoratorInPublicWithResponseAsync(String name,
RequestOptions requestOptions) {
final String accept = "application/json";
return FluxUtil.withContext(context -> service.publicDecoratorInPublic(this.client.getEndpoint(), name, accept,
requestOptions, context));
}
/**
* The publicDecoratorInPublic operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in a public operation, should be generated and exported along with {@link Response}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BinaryData> publicDecoratorInPublicWithResponse(String name, RequestOptions requestOptions) {
final String accept = "application/json";
return service.publicDecoratorInPublicSync(this.client.getEndpoint(), name, accept, requestOptions,
Context.NONE);
}
}

Просмотреть файл

@ -0,0 +1,240 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access.implementation;
import com.azure.core.annotation.ExpectedResponses;
import com.azure.core.annotation.Get;
import com.azure.core.annotation.HeaderParam;
import com.azure.core.annotation.Host;
import com.azure.core.annotation.HostParam;
import com.azure.core.annotation.QueryParam;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceInterface;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.annotation.UnexpectedResponseExceptionType;
import com.azure.core.exception.ClientAuthenticationException;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.RestProxy;
import com.azure.core.util.BinaryData;
import com.azure.core.util.Context;
import com.azure.core.util.FluxUtil;
import reactor.core.publisher.Mono;
/**
* An instance of this class provides access to all the operations defined in RelativeModelInOperations.
*/
public final class RelativeModelInOperationsImpl {
/**
* The proxy service used to perform REST calls.
*/
private final RelativeModelInOperationsService service;
/**
* The service client containing this operation class.
*/
private final AccessClientImpl client;
/**
* Initializes an instance of RelativeModelInOperationsImpl.
*
* @param client the instance of the service client containing this operation class.
*/
RelativeModelInOperationsImpl(AccessClientImpl client) {
this.service = RestProxy.create(RelativeModelInOperationsService.class, client.getHttpPipeline(),
client.getSerializerAdapter());
this.client = client;
}
/**
* The interface defining all the services for AccessClientRelativeModelInOperations to be used by the proxy service
* to perform REST calls.
*/
@Host("{endpoint}")
@ServiceInterface(name = "AccessClientRelative")
public interface RelativeModelInOperationsService {
@Get("/azure/client-generator-core/access/relativeModelInOperation/operation")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Mono<Response<BinaryData>> operation(@HostParam("endpoint") String endpoint, @QueryParam("name") String name,
@HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context);
@Get("/azure/client-generator-core/access/relativeModelInOperation/operation")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Response<BinaryData> operationSync(@HostParam("endpoint") String endpoint, @QueryParam("name") String name,
@HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context);
@Get("/azure/client-generator-core/access/relativeModelInOperation/discriminator")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Mono<Response<BinaryData>> discriminator(@HostParam("endpoint") String endpoint,
@QueryParam("kind") String kind, @HeaderParam("Accept") String accept, RequestOptions requestOptions,
Context context);
@Get("/azure/client-generator-core/access/relativeModelInOperation/discriminator")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Response<BinaryData> discriminatorSync(@HostParam("endpoint") String endpoint, @QueryParam("kind") String kind,
@HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context);
}
/**
* Expected query parameter: name=&lt;any string&gt;
* Expected response body:
* ```json
* {
* "name": &lt;any string&gt;,
* "inner":
* {
* "name": &lt;any string&gt;
* }
* }
* ```.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* inner (Required): {
* name: String (Required)
* }
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in internal operations, should be generated but not exported along with {@link Response} on
* successful completion of {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BinaryData>> operationWithResponseAsync(String name, RequestOptions requestOptions) {
final String accept = "application/json";
return FluxUtil.withContext(
context -> service.operation(this.client.getEndpoint(), name, accept, requestOptions, context));
}
/**
* Expected query parameter: name=&lt;any string&gt;
* Expected response body:
* ```json
* {
* "name": &lt;any string&gt;,
* "inner":
* {
* "name": &lt;any string&gt;
* }
* }
* ```.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* inner (Required): {
* name: String (Required)
* }
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in internal operations, should be generated but not exported along with {@link Response}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BinaryData> operationWithResponse(String name, RequestOptions requestOptions) {
final String accept = "application/json";
return service.operationSync(this.client.getEndpoint(), name, accept, requestOptions, Context.NONE);
}
/**
* Expected query parameter: kind=&lt;any string&gt;
* Expected response body:
* ```json
* {
* "name": &lt;any string&gt;,
* "kind": "real"
* }
* ```.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* kind: String (Required)
* name: String (Required)
* }
* }</pre>
*
* @param kind The kind parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in internal operations, should be generated but not exported along with {@link Response} on
* successful completion of {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BinaryData>> discriminatorWithResponseAsync(String kind, RequestOptions requestOptions) {
final String accept = "application/json";
return FluxUtil.withContext(
context -> service.discriminator(this.client.getEndpoint(), kind, accept, requestOptions, context));
}
/**
* Expected query parameter: kind=&lt;any string&gt;
* Expected response body:
* ```json
* {
* "name": &lt;any string&gt;,
* "kind": "real"
* }
* ```.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* kind: String (Required)
* name: String (Required)
* }
* }</pre>
*
* @param kind The kind parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used in internal operations, should be generated but not exported along with {@link Response}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BinaryData> discriminatorWithResponse(String kind, RequestOptions requestOptions) {
final String accept = "application/json";
return service.discriminatorSync(this.client.getEndpoint(), kind, accept, requestOptions, Context.NONE);
}
}

Просмотреть файл

@ -0,0 +1,197 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access.implementation;
import com.azure.core.annotation.ExpectedResponses;
import com.azure.core.annotation.Get;
import com.azure.core.annotation.HeaderParam;
import com.azure.core.annotation.Host;
import com.azure.core.annotation.HostParam;
import com.azure.core.annotation.QueryParam;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceInterface;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.annotation.UnexpectedResponseExceptionType;
import com.azure.core.exception.ClientAuthenticationException;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.RestProxy;
import com.azure.core.util.BinaryData;
import com.azure.core.util.Context;
import com.azure.core.util.FluxUtil;
import reactor.core.publisher.Mono;
/**
* An instance of this class provides access to all the operations defined in SharedModelInOperations.
*/
public final class SharedModelInOperationsImpl {
/**
* The proxy service used to perform REST calls.
*/
private final SharedModelInOperationsService service;
/**
* The service client containing this operation class.
*/
private final AccessClientImpl client;
/**
* Initializes an instance of SharedModelInOperationsImpl.
*
* @param client the instance of the service client containing this operation class.
*/
SharedModelInOperationsImpl(AccessClientImpl client) {
this.service = RestProxy.create(SharedModelInOperationsService.class, client.getHttpPipeline(),
client.getSerializerAdapter());
this.client = client;
}
/**
* The interface defining all the services for AccessClientSharedModelInOperations to be used by the proxy service
* to perform REST calls.
*/
@Host("{endpoint}")
@ServiceInterface(name = "AccessClientSharedMo")
public interface SharedModelInOperationsService {
@Get("/azure/client-generator-core/access/sharedModelInOperation/public")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Mono<Response<BinaryData>> publicMethod(@HostParam("endpoint") String endpoint, @QueryParam("name") String name,
@HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context);
@Get("/azure/client-generator-core/access/sharedModelInOperation/public")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Response<BinaryData> publicMethodSync(@HostParam("endpoint") String endpoint, @QueryParam("name") String name,
@HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context);
@Get("/azure/client-generator-core/access/sharedModelInOperation/internal")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Mono<Response<BinaryData>> internal(@HostParam("endpoint") String endpoint, @QueryParam("name") String name,
@HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context);
@Get("/azure/client-generator-core/access/sharedModelInOperation/internal")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Response<BinaryData> internalSync(@HostParam("endpoint") String endpoint, @QueryParam("name") String name,
@HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context);
}
/**
* The publicMethod operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used by both public and internal operation along with {@link Response} on successful completion of
* {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BinaryData>> publicMethodWithResponseAsync(String name, RequestOptions requestOptions) {
final String accept = "application/json";
return FluxUtil.withContext(
context -> service.publicMethod(this.client.getEndpoint(), name, accept, requestOptions, context));
}
/**
* The publicMethod operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used by both public and internal operation along with {@link Response}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BinaryData> publicMethodWithResponse(String name, RequestOptions requestOptions) {
final String accept = "application/json";
return service.publicMethodSync(this.client.getEndpoint(), name, accept, requestOptions, Context.NONE);
}
/**
* The internal operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used by both public and internal operation along with {@link Response} on successful completion of
* {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BinaryData>> internalWithResponseAsync(String name, RequestOptions requestOptions) {
final String accept = "application/json";
return FluxUtil
.withContext(context -> service.internal(this.client.getEndpoint(), name, accept, requestOptions, context));
}
/**
* The internal operation.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param name The name parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return used by both public and internal operation along with {@link Response}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BinaryData> internalWithResponse(String name, RequestOptions requestOptions) {
final String accept = "application/json";
return service.internalSync(this.client.getEndpoint(), name, accept, requestOptions, Context.NONE);
}
}

Просмотреть файл

@ -0,0 +1,137 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access.implementation.models;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.Immutable;
import com.azure.json.JsonReader;
import com.azure.json.JsonSerializable;
import com.azure.json.JsonToken;
import com.azure.json.JsonWriter;
import java.io.IOException;
/**
* Used in internal operations, should be generated but not exported.
*/
@Immutable
public class AbstractModel implements JsonSerializable<AbstractModel> {
/*
* Discriminator property for AbstractModel.
*/
@Generated
String kind;
/*
* The name property.
*/
@Generated
private final String name;
/**
* Creates an instance of AbstractModel class.
*
* @param name the name value to set.
*/
@Generated
protected AbstractModel(String name) {
this.name = name;
this.kind = "AbstractModel";
}
/**
* Get the kind property: Discriminator property for AbstractModel.
*
* @return the kind value.
*/
@Generated
public String getKind() {
return this.kind;
}
/**
* Get the name property: The name property.
*
* @return the name value.
*/
@Generated
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Generated
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStartObject();
toJsonShared(jsonWriter);
return jsonWriter.writeEndObject();
}
void toJsonShared(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStringField("name", this.name);
jsonWriter.writeStringField("kind", this.kind);
}
/**
* Reads an instance of AbstractModel from the JsonReader.
*
* @param jsonReader The JsonReader being read.
* @return An instance of AbstractModel if the JsonReader was pointing to an instance of it, or null if it was
* pointing to JSON null.
* @throws IllegalStateException If the deserialized JSON object was missing any required properties.
* @throws IOException If an error occurs while reading the AbstractModel.
*/
@Generated
public static AbstractModel fromJson(JsonReader jsonReader) throws IOException {
return jsonReader.readObject(reader -> {
String discriminatorValue = null;
try (JsonReader readerToUse = reader.bufferObject()) {
readerToUse.nextToken(); // Prepare for reading
while (readerToUse.nextToken() != JsonToken.END_OBJECT) {
String fieldName = readerToUse.getFieldName();
readerToUse.nextToken();
if ("kind".equals(fieldName)) {
discriminatorValue = readerToUse.getString();
break;
} else {
readerToUse.skipChildren();
}
}
// Use the discriminator value to determine which subtype should be deserialized.
if ("real".equals(discriminatorValue)) {
return RealModel.fromJson(readerToUse.reset());
} else {
return fromJsonKnownDiscriminator(readerToUse.reset());
}
}
});
}
@Generated
static AbstractModel fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException {
return jsonReader.readObject(reader -> {
String name = null;
String kind = null;
while (reader.nextToken() != JsonToken.END_OBJECT) {
String fieldName = reader.getFieldName();
reader.nextToken();
if ("name".equals(fieldName)) {
name = reader.getString();
} else if ("kind".equals(fieldName)) {
kind = reader.getString();
} else {
reader.skipChildren();
}
}
AbstractModel deserializedAbstractModel = new AbstractModel(name);
deserializedAbstractModel.kind = kind;
return deserializedAbstractModel;
});
}
}

Просмотреть файл

@ -0,0 +1,83 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access.implementation.models;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.Immutable;
import com.azure.json.JsonReader;
import com.azure.json.JsonSerializable;
import com.azure.json.JsonToken;
import com.azure.json.JsonWriter;
import java.io.IOException;
/**
* Used in internal operations, should be generated but not exported.
*/
@Immutable
public class BaseModel implements JsonSerializable<BaseModel> {
/*
* The name property.
*/
@Generated
private final String name;
/**
* Creates an instance of BaseModel class.
*
* @param name the name value to set.
*/
@Generated
protected BaseModel(String name) {
this.name = name;
}
/**
* Get the name property: The name property.
*
* @return the name value.
*/
@Generated
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Generated
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStartObject();
jsonWriter.writeStringField("name", this.name);
return jsonWriter.writeEndObject();
}
/**
* Reads an instance of BaseModel from the JsonReader.
*
* @param jsonReader The JsonReader being read.
* @return An instance of BaseModel if the JsonReader was pointing to an instance of it, or null if it was pointing
* to JSON null.
* @throws IllegalStateException If the deserialized JSON object was missing any required properties.
* @throws IOException If an error occurs while reading the BaseModel.
*/
@Generated
public static BaseModel fromJson(JsonReader jsonReader) throws IOException {
return jsonReader.readObject(reader -> {
String name = null;
while (reader.nextToken() != JsonToken.END_OBJECT) {
String fieldName = reader.getFieldName();
reader.nextToken();
if ("name".equals(fieldName)) {
name = reader.getString();
} else {
reader.skipChildren();
}
}
return new BaseModel(name);
});
}
}

Просмотреть файл

@ -0,0 +1,83 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access.implementation.models;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.Immutable;
import com.azure.json.JsonReader;
import com.azure.json.JsonSerializable;
import com.azure.json.JsonToken;
import com.azure.json.JsonWriter;
import java.io.IOException;
/**
* Used in internal operations, should be generated but not exported.
*/
@Immutable
public final class InnerModel implements JsonSerializable<InnerModel> {
/*
* The name property.
*/
@Generated
private final String name;
/**
* Creates an instance of InnerModel class.
*
* @param name the name value to set.
*/
@Generated
private InnerModel(String name) {
this.name = name;
}
/**
* Get the name property: The name property.
*
* @return the name value.
*/
@Generated
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Generated
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStartObject();
jsonWriter.writeStringField("name", this.name);
return jsonWriter.writeEndObject();
}
/**
* Reads an instance of InnerModel from the JsonReader.
*
* @param jsonReader The JsonReader being read.
* @return An instance of InnerModel if the JsonReader was pointing to an instance of it, or null if it was pointing
* to JSON null.
* @throws IllegalStateException If the deserialized JSON object was missing any required properties.
* @throws IOException If an error occurs while reading the InnerModel.
*/
@Generated
public static InnerModel fromJson(JsonReader jsonReader) throws IOException {
return jsonReader.readObject(reader -> {
String name = null;
while (reader.nextToken() != JsonToken.END_OBJECT) {
String fieldName = reader.getFieldName();
reader.nextToken();
if ("name".equals(fieldName)) {
name = reader.getString();
} else {
reader.skipChildren();
}
}
return new InnerModel(name);
});
}
}

Просмотреть файл

@ -0,0 +1,83 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access.implementation.models;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.Immutable;
import com.azure.json.JsonReader;
import com.azure.json.JsonSerializable;
import com.azure.json.JsonToken;
import com.azure.json.JsonWriter;
import java.io.IOException;
/**
* Used in an internal operation, should be generated but not exported.
*/
@Immutable
public final class InternalDecoratorModelInInternal implements JsonSerializable<InternalDecoratorModelInInternal> {
/*
* The name property.
*/
@Generated
private final String name;
/**
* Creates an instance of InternalDecoratorModelInInternal class.
*
* @param name the name value to set.
*/
@Generated
private InternalDecoratorModelInInternal(String name) {
this.name = name;
}
/**
* Get the name property: The name property.
*
* @return the name value.
*/
@Generated
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Generated
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStartObject();
jsonWriter.writeStringField("name", this.name);
return jsonWriter.writeEndObject();
}
/**
* Reads an instance of InternalDecoratorModelInInternal from the JsonReader.
*
* @param jsonReader The JsonReader being read.
* @return An instance of InternalDecoratorModelInInternal if the JsonReader was pointing to an instance of it, or
* null if it was pointing to JSON null.
* @throws IllegalStateException If the deserialized JSON object was missing any required properties.
* @throws IOException If an error occurs while reading the InternalDecoratorModelInInternal.
*/
@Generated
public static InternalDecoratorModelInInternal fromJson(JsonReader jsonReader) throws IOException {
return jsonReader.readObject(reader -> {
String name = null;
while (reader.nextToken() != JsonToken.END_OBJECT) {
String fieldName = reader.getFieldName();
reader.nextToken();
if ("name".equals(fieldName)) {
name = reader.getString();
} else {
reader.skipChildren();
}
}
return new InternalDecoratorModelInInternal(name);
});
}
}

Просмотреть файл

@ -0,0 +1,83 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access.implementation.models;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.Immutable;
import com.azure.json.JsonReader;
import com.azure.json.JsonSerializable;
import com.azure.json.JsonToken;
import com.azure.json.JsonWriter;
import java.io.IOException;
/**
* Used in an internal operation, should be generated but not exported.
*/
@Immutable
public final class NoDecoratorModelInInternal implements JsonSerializable<NoDecoratorModelInInternal> {
/*
* The name property.
*/
@Generated
private final String name;
/**
* Creates an instance of NoDecoratorModelInInternal class.
*
* @param name the name value to set.
*/
@Generated
private NoDecoratorModelInInternal(String name) {
this.name = name;
}
/**
* Get the name property: The name property.
*
* @return the name value.
*/
@Generated
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Generated
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStartObject();
jsonWriter.writeStringField("name", this.name);
return jsonWriter.writeEndObject();
}
/**
* Reads an instance of NoDecoratorModelInInternal from the JsonReader.
*
* @param jsonReader The JsonReader being read.
* @return An instance of NoDecoratorModelInInternal if the JsonReader was pointing to an instance of it, or null if
* it was pointing to JSON null.
* @throws IllegalStateException If the deserialized JSON object was missing any required properties.
* @throws IOException If an error occurs while reading the NoDecoratorModelInInternal.
*/
@Generated
public static NoDecoratorModelInInternal fromJson(JsonReader jsonReader) throws IOException {
return jsonReader.readObject(reader -> {
String name = null;
while (reader.nextToken() != JsonToken.END_OBJECT) {
String fieldName = reader.getFieldName();
reader.nextToken();
if ("name".equals(fieldName)) {
name = reader.getString();
} else {
reader.skipChildren();
}
}
return new NoDecoratorModelInInternal(name);
});
}
}

Просмотреть файл

@ -0,0 +1,88 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access.implementation.models;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.Immutable;
import com.azure.json.JsonReader;
import com.azure.json.JsonToken;
import com.azure.json.JsonWriter;
import java.io.IOException;
/**
* Used in internal operations, should be generated but not exported.
*/
@Immutable
public final class OuterModel extends BaseModel {
/*
* The inner property.
*/
@Generated
private final InnerModel inner;
/**
* Creates an instance of OuterModel class.
*
* @param name the name value to set.
* @param inner the inner value to set.
*/
@Generated
private OuterModel(String name, InnerModel inner) {
super(name);
this.inner = inner;
}
/**
* Get the inner property: The inner property.
*
* @return the inner value.
*/
@Generated
public InnerModel getInner() {
return this.inner;
}
/**
* {@inheritDoc}
*/
@Generated
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStartObject();
jsonWriter.writeStringField("name", getName());
jsonWriter.writeJsonField("inner", this.inner);
return jsonWriter.writeEndObject();
}
/**
* Reads an instance of OuterModel from the JsonReader.
*
* @param jsonReader The JsonReader being read.
* @return An instance of OuterModel if the JsonReader was pointing to an instance of it, or null if it was pointing
* to JSON null.
* @throws IllegalStateException If the deserialized JSON object was missing any required properties.
* @throws IOException If an error occurs while reading the OuterModel.
*/
@Generated
public static OuterModel fromJson(JsonReader jsonReader) throws IOException {
return jsonReader.readObject(reader -> {
String name = null;
InnerModel inner = null;
while (reader.nextToken() != JsonToken.END_OBJECT) {
String fieldName = reader.getFieldName();
reader.nextToken();
if ("name".equals(fieldName)) {
name = reader.getString();
} else if ("inner".equals(fieldName)) {
inner = InnerModel.fromJson(reader);
} else {
reader.skipChildren();
}
}
return new OuterModel(name, inner);
});
}
}

Просмотреть файл

@ -0,0 +1,73 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access.implementation.models;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.Immutable;
import com.azure.json.JsonReader;
import com.azure.json.JsonToken;
import com.azure.json.JsonWriter;
import java.io.IOException;
/**
* Used in internal operations, should be generated but not exported.
*/
@Immutable
public final class RealModel extends AbstractModel {
/**
* Creates an instance of RealModel class.
*
* @param name the name value to set.
*/
@Generated
private RealModel(String name) {
super(name);
this.kind = "real";
}
/**
* {@inheritDoc}
*/
@Generated
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStartObject();
toJsonShared(jsonWriter);
return jsonWriter.writeEndObject();
}
/**
* Reads an instance of RealModel from the JsonReader.
*
* @param jsonReader The JsonReader being read.
* @return An instance of RealModel if the JsonReader was pointing to an instance of it, or null if it was pointing
* to JSON null.
* @throws IllegalStateException If the deserialized JSON object was missing any required properties.
* @throws IOException If an error occurs while reading the RealModel.
*/
@Generated
public static RealModel fromJson(JsonReader jsonReader) throws IOException {
return jsonReader.readObject(reader -> {
String name = null;
String kind = "real";
while (reader.nextToken() != JsonToken.END_OBJECT) {
String fieldName = reader.getFieldName();
reader.nextToken();
if ("name".equals(fieldName)) {
name = reader.getString();
} else if ("kind".equals(fieldName)) {
kind = reader.getString();
} else {
reader.skipChildren();
}
}
RealModel deserializedRealModel = new RealModel(name);
deserializedRealModel.kind = kind;
return deserializedRealModel;
});
}
}

Просмотреть файл

@ -0,0 +1,11 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
/**
* <!-- start generated doc -->
* Package containing the data models for Access.
* Test for internal decorator.
* <!-- end generated doc -->
*/
package com._specs_.azure.clientgenerator.core.access.implementation.models;

Просмотреть файл

@ -0,0 +1,11 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
/**
* <!-- start generated doc -->
* Package containing the implementations for Access.
* Test for internal decorator.
* <!-- end generated doc -->
*/
package com._specs_.azure.clientgenerator.core.access.implementation;

Просмотреть файл

@ -0,0 +1,83 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access.models;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.Immutable;
import com.azure.json.JsonReader;
import com.azure.json.JsonSerializable;
import com.azure.json.JsonToken;
import com.azure.json.JsonWriter;
import java.io.IOException;
/**
* Used in a public operation, should be generated and exported.
*/
@Immutable
public final class NoDecoratorModelInPublic implements JsonSerializable<NoDecoratorModelInPublic> {
/*
* The name property.
*/
@Generated
private final String name;
/**
* Creates an instance of NoDecoratorModelInPublic class.
*
* @param name the name value to set.
*/
@Generated
private NoDecoratorModelInPublic(String name) {
this.name = name;
}
/**
* Get the name property: The name property.
*
* @return the name value.
*/
@Generated
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Generated
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStartObject();
jsonWriter.writeStringField("name", this.name);
return jsonWriter.writeEndObject();
}
/**
* Reads an instance of NoDecoratorModelInPublic from the JsonReader.
*
* @param jsonReader The JsonReader being read.
* @return An instance of NoDecoratorModelInPublic if the JsonReader was pointing to an instance of it, or null if
* it was pointing to JSON null.
* @throws IllegalStateException If the deserialized JSON object was missing any required properties.
* @throws IOException If an error occurs while reading the NoDecoratorModelInPublic.
*/
@Generated
public static NoDecoratorModelInPublic fromJson(JsonReader jsonReader) throws IOException {
return jsonReader.readObject(reader -> {
String name = null;
while (reader.nextToken() != JsonToken.END_OBJECT) {
String fieldName = reader.getFieldName();
reader.nextToken();
if ("name".equals(fieldName)) {
name = reader.getString();
} else {
reader.skipChildren();
}
}
return new NoDecoratorModelInPublic(name);
});
}
}

Просмотреть файл

@ -0,0 +1,83 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access.models;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.Immutable;
import com.azure.json.JsonReader;
import com.azure.json.JsonSerializable;
import com.azure.json.JsonToken;
import com.azure.json.JsonWriter;
import java.io.IOException;
/**
* Used in an internal operation but with public decorator, should be generated and exported.
*/
@Immutable
public final class PublicDecoratorModelInInternal implements JsonSerializable<PublicDecoratorModelInInternal> {
/*
* The name property.
*/
@Generated
private final String name;
/**
* Creates an instance of PublicDecoratorModelInInternal class.
*
* @param name the name value to set.
*/
@Generated
private PublicDecoratorModelInInternal(String name) {
this.name = name;
}
/**
* Get the name property: The name property.
*
* @return the name value.
*/
@Generated
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Generated
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStartObject();
jsonWriter.writeStringField("name", this.name);
return jsonWriter.writeEndObject();
}
/**
* Reads an instance of PublicDecoratorModelInInternal from the JsonReader.
*
* @param jsonReader The JsonReader being read.
* @return An instance of PublicDecoratorModelInInternal if the JsonReader was pointing to an instance of it, or
* null if it was pointing to JSON null.
* @throws IllegalStateException If the deserialized JSON object was missing any required properties.
* @throws IOException If an error occurs while reading the PublicDecoratorModelInInternal.
*/
@Generated
public static PublicDecoratorModelInInternal fromJson(JsonReader jsonReader) throws IOException {
return jsonReader.readObject(reader -> {
String name = null;
while (reader.nextToken() != JsonToken.END_OBJECT) {
String fieldName = reader.getFieldName();
reader.nextToken();
if ("name".equals(fieldName)) {
name = reader.getString();
} else {
reader.skipChildren();
}
}
return new PublicDecoratorModelInInternal(name);
});
}
}

Просмотреть файл

@ -0,0 +1,83 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access.models;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.Immutable;
import com.azure.json.JsonReader;
import com.azure.json.JsonSerializable;
import com.azure.json.JsonToken;
import com.azure.json.JsonWriter;
import java.io.IOException;
/**
* Used in a public operation, should be generated and exported.
*/
@Immutable
public final class PublicDecoratorModelInPublic implements JsonSerializable<PublicDecoratorModelInPublic> {
/*
* The name property.
*/
@Generated
private final String name;
/**
* Creates an instance of PublicDecoratorModelInPublic class.
*
* @param name the name value to set.
*/
@Generated
private PublicDecoratorModelInPublic(String name) {
this.name = name;
}
/**
* Get the name property: The name property.
*
* @return the name value.
*/
@Generated
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Generated
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStartObject();
jsonWriter.writeStringField("name", this.name);
return jsonWriter.writeEndObject();
}
/**
* Reads an instance of PublicDecoratorModelInPublic from the JsonReader.
*
* @param jsonReader The JsonReader being read.
* @return An instance of PublicDecoratorModelInPublic if the JsonReader was pointing to an instance of it, or null
* if it was pointing to JSON null.
* @throws IllegalStateException If the deserialized JSON object was missing any required properties.
* @throws IOException If an error occurs while reading the PublicDecoratorModelInPublic.
*/
@Generated
public static PublicDecoratorModelInPublic fromJson(JsonReader jsonReader) throws IOException {
return jsonReader.readObject(reader -> {
String name = null;
while (reader.nextToken() != JsonToken.END_OBJECT) {
String fieldName = reader.getFieldName();
reader.nextToken();
if ("name".equals(fieldName)) {
name = reader.getString();
} else {
reader.skipChildren();
}
}
return new PublicDecoratorModelInPublic(name);
});
}
}

Просмотреть файл

@ -0,0 +1,83 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.access.models;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.Immutable;
import com.azure.json.JsonReader;
import com.azure.json.JsonSerializable;
import com.azure.json.JsonToken;
import com.azure.json.JsonWriter;
import java.io.IOException;
/**
* Used by both public and internal operation. It should be generated and exported.
*/
@Immutable
public final class SharedModel implements JsonSerializable<SharedModel> {
/*
* The name property.
*/
@Generated
private final String name;
/**
* Creates an instance of SharedModel class.
*
* @param name the name value to set.
*/
@Generated
private SharedModel(String name) {
this.name = name;
}
/**
* Get the name property: The name property.
*
* @return the name value.
*/
@Generated
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Generated
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStartObject();
jsonWriter.writeStringField("name", this.name);
return jsonWriter.writeEndObject();
}
/**
* Reads an instance of SharedModel from the JsonReader.
*
* @param jsonReader The JsonReader being read.
* @return An instance of SharedModel if the JsonReader was pointing to an instance of it, or null if it was
* pointing to JSON null.
* @throws IllegalStateException If the deserialized JSON object was missing any required properties.
* @throws IOException If an error occurs while reading the SharedModel.
*/
@Generated
public static SharedModel fromJson(JsonReader jsonReader) throws IOException {
return jsonReader.readObject(reader -> {
String name = null;
while (reader.nextToken() != JsonToken.END_OBJECT) {
String fieldName = reader.getFieldName();
reader.nextToken();
if ("name".equals(fieldName)) {
name = reader.getString();
} else {
reader.skipChildren();
}
}
return new SharedModel(name);
});
}
}

Просмотреть файл

@ -0,0 +1,11 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
/**
* <!-- start generated doc -->
* Package containing the data models for Access.
* Test for internal decorator.
* <!-- end generated doc -->
*/
package com._specs_.azure.clientgenerator.core.access.models;

Просмотреть файл

@ -0,0 +1,11 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
/**
* <!-- start generated doc -->
* Package containing the classes for Access.
* Test for internal decorator.
* <!-- end generated doc -->
*/
package com._specs_.azure.clientgenerator.core.access;

Просмотреть файл

@ -0,0 +1,237 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.usage;
import com._specs_.azure.clientgenerator.core.usage.implementation.ModelInOperationsImpl;
import com._specs_.azure.clientgenerator.core.usage.models.InputModel;
import com._specs_.azure.clientgenerator.core.usage.models.OutputModel;
import com._specs_.azure.clientgenerator.core.usage.models.RoundTripModel;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.exception.ClientAuthenticationException;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.util.BinaryData;
import com.azure.core.util.FluxUtil;
import reactor.core.publisher.Mono;
/**
* Initializes a new instance of the asynchronous UsageClient type.
*/
@ServiceClient(builder = UsageClientBuilder.class, isAsync = true)
public final class UsageAsyncClient {
@Generated
private final ModelInOperationsImpl serviceClient;
/**
* Initializes an instance of UsageAsyncClient class.
*
* @param serviceClient the service client implementation.
*/
@Generated
UsageAsyncClient(ModelInOperationsImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* Expected body parameter:
* ```json
* {
* "name": &lt;any string&gt;
* }
* ```.
* <p><strong>Request Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param body The body parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return the {@link Response} on successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> inputToInputOutputWithResponse(BinaryData body, RequestOptions requestOptions) {
return this.serviceClient.inputToInputOutputWithResponseAsync(body, requestOptions);
}
/**
* Expected response body:
* ```json
* {
* "name": &lt;any string&gt;
* }
* ```.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return usage override to roundtrip along with {@link Response} on successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BinaryData>> outputToInputOutputWithResponse(RequestOptions requestOptions) {
return this.serviceClient.outputToInputOutputWithResponseAsync(requestOptions);
}
/**
* "ResultModel" should be usage=output, as it is read-only and does not exist in request body.
*
* Expected body parameter:
* ```json
* {
* }
* ```
*
* Expected response body:
* ```json
* {
* "result": {
* "name": &lt;any string&gt;
* }
* }
* ```.
* <p><strong>Request Body Schema</strong></p>
*
* <pre>{@code
* {
* result (Required): {
* name: String (Required)
* }
* }
* }</pre>
*
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* result (Required): {
* name: String (Required)
* }
* }
* }</pre>
*
* @param body The body parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return the response body along with {@link Response} on successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BinaryData>> modelInReadOnlyPropertyWithResponse(BinaryData body,
RequestOptions requestOptions) {
return this.serviceClient.modelInReadOnlyPropertyWithResponseAsync(body, requestOptions);
}
/**
* Expected body parameter:
* ```json
* {
* "name": &lt;any string&gt;
* }
* ```.
*
* @param body The body parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return A {@link Mono} that completes when a successful response is received.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> inputToInputOutput(InputModel body) {
// Generated convenience method for inputToInputOutputWithResponse
RequestOptions requestOptions = new RequestOptions();
return inputToInputOutputWithResponse(BinaryData.fromObject(body), requestOptions).flatMap(FluxUtil::toMono);
}
/**
* Expected response body:
* ```json
* {
* "name": &lt;any string&gt;
* }
* ```.
*
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return usage override to roundtrip on successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<OutputModel> outputToInputOutput() {
// Generated convenience method for outputToInputOutputWithResponse
RequestOptions requestOptions = new RequestOptions();
return outputToInputOutputWithResponse(requestOptions).flatMap(FluxUtil::toMono)
.map(protocolMethodData -> protocolMethodData.toObject(OutputModel.class));
}
/**
* "ResultModel" should be usage=output, as it is read-only and does not exist in request body.
*
* Expected body parameter:
* ```json
* {
* }
* ```
*
* Expected response body:
* ```json
* {
* "result": {
* "name": &lt;any string&gt;
* }
* }
* ```.
*
* @param body The body parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the response body on successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RoundTripModel> modelInReadOnlyProperty(RoundTripModel body) {
// Generated convenience method for modelInReadOnlyPropertyWithResponse
RequestOptions requestOptions = new RequestOptions();
return modelInReadOnlyPropertyWithResponse(BinaryData.fromObject(body), requestOptions)
.flatMap(FluxUtil::toMono)
.map(protocolMethodData -> protocolMethodData.toObject(RoundTripModel.class));
}
}

Просмотреть файл

@ -0,0 +1,231 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.usage;
import com._specs_.azure.clientgenerator.core.usage.implementation.ModelInOperationsImpl;
import com._specs_.azure.clientgenerator.core.usage.models.InputModel;
import com._specs_.azure.clientgenerator.core.usage.models.OutputModel;
import com._specs_.azure.clientgenerator.core.usage.models.RoundTripModel;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.exception.ClientAuthenticationException;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.util.BinaryData;
/**
* Initializes a new instance of the synchronous UsageClient type.
*/
@ServiceClient(builder = UsageClientBuilder.class)
public final class UsageClient {
@Generated
private final ModelInOperationsImpl serviceClient;
/**
* Initializes an instance of UsageClient class.
*
* @param serviceClient the service client implementation.
*/
@Generated
UsageClient(ModelInOperationsImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* Expected body parameter:
* ```json
* {
* "name": &lt;any string&gt;
* }
* ```.
* <p><strong>Request Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param body The body parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return the {@link Response}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> inputToInputOutputWithResponse(BinaryData body, RequestOptions requestOptions) {
return this.serviceClient.inputToInputOutputWithResponse(body, requestOptions);
}
/**
* Expected response body:
* ```json
* {
* "name": &lt;any string&gt;
* }
* ```.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return usage override to roundtrip along with {@link Response}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BinaryData> outputToInputOutputWithResponse(RequestOptions requestOptions) {
return this.serviceClient.outputToInputOutputWithResponse(requestOptions);
}
/**
* "ResultModel" should be usage=output, as it is read-only and does not exist in request body.
*
* Expected body parameter:
* ```json
* {
* }
* ```
*
* Expected response body:
* ```json
* {
* "result": {
* "name": &lt;any string&gt;
* }
* }
* ```.
* <p><strong>Request Body Schema</strong></p>
*
* <pre>{@code
* {
* result (Required): {
* name: String (Required)
* }
* }
* }</pre>
*
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* result (Required): {
* name: String (Required)
* }
* }
* }</pre>
*
* @param body The body parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return the response body along with {@link Response}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BinaryData> modelInReadOnlyPropertyWithResponse(BinaryData body, RequestOptions requestOptions) {
return this.serviceClient.modelInReadOnlyPropertyWithResponse(body, requestOptions);
}
/**
* Expected body parameter:
* ```json
* {
* "name": &lt;any string&gt;
* }
* ```.
*
* @param body The body parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public void inputToInputOutput(InputModel body) {
// Generated convenience method for inputToInputOutputWithResponse
RequestOptions requestOptions = new RequestOptions();
inputToInputOutputWithResponse(BinaryData.fromObject(body), requestOptions).getValue();
}
/**
* Expected response body:
* ```json
* {
* "name": &lt;any string&gt;
* }
* ```.
*
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return usage override to roundtrip.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public OutputModel outputToInputOutput() {
// Generated convenience method for outputToInputOutputWithResponse
RequestOptions requestOptions = new RequestOptions();
return outputToInputOutputWithResponse(requestOptions).getValue().toObject(OutputModel.class);
}
/**
* "ResultModel" should be usage=output, as it is read-only and does not exist in request body.
*
* Expected body parameter:
* ```json
* {
* }
* ```
*
* Expected response body:
* ```json
* {
* "result": {
* "name": &lt;any string&gt;
* }
* }
* ```.
*
* @param body The body parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the response.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public RoundTripModel modelInReadOnlyProperty(RoundTripModel body) {
// Generated convenience method for modelInReadOnlyPropertyWithResponse
RequestOptions requestOptions = new RequestOptions();
return modelInReadOnlyPropertyWithResponse(BinaryData.fromObject(body), requestOptions).getValue()
.toObject(RoundTripModel.class);
}
}

Просмотреть файл

@ -0,0 +1,288 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.usage;
import com._specs_.azure.clientgenerator.core.usage.implementation.UsageClientImpl;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.ServiceClientBuilder;
import com.azure.core.client.traits.ConfigurationTrait;
import com.azure.core.client.traits.EndpointTrait;
import com.azure.core.client.traits.HttpTrait;
import com.azure.core.http.HttpClient;
import com.azure.core.http.HttpHeaders;
import com.azure.core.http.HttpPipeline;
import com.azure.core.http.HttpPipelineBuilder;
import com.azure.core.http.HttpPipelinePosition;
import com.azure.core.http.policy.AddDatePolicy;
import com.azure.core.http.policy.AddHeadersFromContextPolicy;
import com.azure.core.http.policy.AddHeadersPolicy;
import com.azure.core.http.policy.HttpLoggingPolicy;
import com.azure.core.http.policy.HttpLogOptions;
import com.azure.core.http.policy.HttpPipelinePolicy;
import com.azure.core.http.policy.HttpPolicyProviders;
import com.azure.core.http.policy.RequestIdPolicy;
import com.azure.core.http.policy.RetryOptions;
import com.azure.core.http.policy.RetryPolicy;
import com.azure.core.http.policy.UserAgentPolicy;
import com.azure.core.util.ClientOptions;
import com.azure.core.util.Configuration;
import com.azure.core.util.CoreUtils;
import com.azure.core.util.builder.ClientBuilderUtil;
import com.azure.core.util.logging.ClientLogger;
import com.azure.core.util.serializer.JacksonAdapter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* A builder for creating a new instance of the UsageClient type.
*/
@ServiceClientBuilder(serviceClients = { UsageClient.class, UsageAsyncClient.class })
public final class UsageClientBuilder implements HttpTrait<UsageClientBuilder>, ConfigurationTrait<UsageClientBuilder>,
EndpointTrait<UsageClientBuilder> {
@Generated
private static final String SDK_NAME = "name";
@Generated
private static final String SDK_VERSION = "version";
@Generated
private static final Map<String, String> PROPERTIES
= CoreUtils.getProperties("_specs_-azure-clientgenerator-core-usage.properties");
@Generated
private final List<HttpPipelinePolicy> pipelinePolicies;
/**
* Create an instance of the UsageClientBuilder.
*/
@Generated
public UsageClientBuilder() {
this.pipelinePolicies = new ArrayList<>();
}
/*
* The HTTP pipeline to send requests through.
*/
@Generated
private HttpPipeline pipeline;
/**
* {@inheritDoc}.
*/
@Generated
@Override
public UsageClientBuilder pipeline(HttpPipeline pipeline) {
if (this.pipeline != null && pipeline == null) {
LOGGER.atInfo().log("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.pipeline = pipeline;
return this;
}
/*
* The HTTP client used to send the request.
*/
@Generated
private HttpClient httpClient;
/**
* {@inheritDoc}.
*/
@Generated
@Override
public UsageClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/*
* The logging configuration for HTTP requests and responses.
*/
@Generated
private HttpLogOptions httpLogOptions;
/**
* {@inheritDoc}.
*/
@Generated
@Override
public UsageClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/*
* The client options such as application ID and custom headers to set on a request.
*/
@Generated
private ClientOptions clientOptions;
/**
* {@inheritDoc}.
*/
@Generated
@Override
public UsageClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/*
* The retry options to configure retry policy for failed requests.
*/
@Generated
private RetryOptions retryOptions;
/**
* {@inheritDoc}.
*/
@Generated
@Override
public UsageClientBuilder retryOptions(RetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* {@inheritDoc}.
*/
@Generated
@Override
public UsageClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.");
pipelinePolicies.add(customPolicy);
return this;
}
/*
* The configuration store that is used during construction of the service client.
*/
@Generated
private Configuration configuration;
/**
* {@inheritDoc}.
*/
@Generated
@Override
public UsageClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/*
* The service endpoint
*/
@Generated
private String endpoint;
/**
* {@inheritDoc}.
*/
@Generated
@Override
public UsageClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/*
* The retry policy that will attempt to retry failed requests, if applicable.
*/
@Generated
private RetryPolicy retryPolicy;
/**
* Sets The retry policy that will attempt to retry failed requests, if applicable.
*
* @param retryPolicy the retryPolicy value.
* @return the UsageClientBuilder.
*/
@Generated
public UsageClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Builds an instance of UsageClientImpl with the provided parameters.
*
* @return an instance of UsageClientImpl.
*/
@Generated
private UsageClientImpl buildInnerClient() {
this.validateClient();
HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline();
String localEndpoint = (endpoint != null) ? endpoint : "http://localhost:3000";
UsageClientImpl client
= new UsageClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), localEndpoint);
return client;
}
@Generated
private void validateClient() {
// This method is invoked from 'buildInnerClient'/'buildClient' method.
// Developer can customize this method, to validate that the necessary conditions are met for the new client.
}
@Generated
private HttpPipeline createHttpPipeline() {
Configuration buildConfiguration
= (configuration == null) ? Configuration.getGlobalConfiguration() : configuration;
HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions;
ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions;
List<HttpPipelinePolicy> policies = new ArrayList<>();
String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion");
String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions);
policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration));
policies.add(new RequestIdPolicy());
policies.add(new AddHeadersFromContextPolicy());
HttpHeaders headers = CoreUtils.createHttpHeadersFromClientOptions(localClientOptions);
if (headers != null) {
policies.add(new AddHeadersPolicy(headers));
}
this.pipelinePolicies.stream()
.filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL)
.forEach(p -> policies.add(p));
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy()));
policies.add(new AddDatePolicy());
this.pipelinePolicies.stream()
.filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY)
.forEach(p -> policies.add(p));
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(localHttpLogOptions));
HttpPipeline httpPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.clientOptions(localClientOptions)
.build();
return httpPipeline;
}
/**
* Builds an instance of UsageAsyncClient class.
*
* @return an instance of UsageAsyncClient.
*/
@Generated
public UsageAsyncClient buildAsyncClient() {
return new UsageAsyncClient(buildInnerClient().getModelInOperations());
}
/**
* Builds an instance of UsageClient class.
*
* @return an instance of UsageClient.
*/
@Generated
public UsageClient buildClient() {
return new UsageClient(buildInnerClient().getModelInOperations());
}
private static final ClientLogger LOGGER = new ClientLogger(UsageClientBuilder.class);
}

Просмотреть файл

@ -0,0 +1,345 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.usage.implementation;
import com.azure.core.annotation.BodyParam;
import com.azure.core.annotation.ExpectedResponses;
import com.azure.core.annotation.Get;
import com.azure.core.annotation.HeaderParam;
import com.azure.core.annotation.Host;
import com.azure.core.annotation.HostParam;
import com.azure.core.annotation.Post;
import com.azure.core.annotation.Put;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceInterface;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.annotation.UnexpectedResponseExceptionType;
import com.azure.core.exception.ClientAuthenticationException;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.RestProxy;
import com.azure.core.util.BinaryData;
import com.azure.core.util.Context;
import com.azure.core.util.FluxUtil;
import reactor.core.publisher.Mono;
/**
* An instance of this class provides access to all the operations defined in ModelInOperations.
*/
public final class ModelInOperationsImpl {
/**
* The proxy service used to perform REST calls.
*/
private final ModelInOperationsService service;
/**
* The service client containing this operation class.
*/
private final UsageClientImpl client;
/**
* Initializes an instance of ModelInOperationsImpl.
*
* @param client the instance of the service client containing this operation class.
*/
ModelInOperationsImpl(UsageClientImpl client) {
this.service
= RestProxy.create(ModelInOperationsService.class, client.getHttpPipeline(), client.getSerializerAdapter());
this.client = client;
}
/**
* The interface defining all the services for UsageClientModelInOperations to be used by the proxy service to
* perform REST calls.
*/
@Host("{endpoint}")
@ServiceInterface(name = "UsageClientModelInOp")
public interface ModelInOperationsService {
@Post("/azure/client-generator-core/usage/inputToInputOutput")
@ExpectedResponses({ 204 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Mono<Response<Void>> inputToInputOutput(@HostParam("endpoint") String endpoint,
@HeaderParam("Content-Type") String contentType, @BodyParam("application/json") BinaryData body,
RequestOptions requestOptions, Context context);
@Post("/azure/client-generator-core/usage/inputToInputOutput")
@ExpectedResponses({ 204 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Response<Void> inputToInputOutputSync(@HostParam("endpoint") String endpoint,
@HeaderParam("Content-Type") String contentType, @BodyParam("application/json") BinaryData body,
RequestOptions requestOptions, Context context);
@Get("/azure/client-generator-core/usage/outputToInputOutput")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Mono<Response<BinaryData>> outputToInputOutput(@HostParam("endpoint") String endpoint,
@HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context);
@Get("/azure/client-generator-core/usage/outputToInputOutput")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Response<BinaryData> outputToInputOutputSync(@HostParam("endpoint") String endpoint,
@HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context);
@Put("/azure/client-generator-core/usage/modelInReadOnlyProperty")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Mono<Response<BinaryData>> modelInReadOnlyProperty(@HostParam("endpoint") String endpoint,
@HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept,
@BodyParam("application/json") BinaryData body, RequestOptions requestOptions, Context context);
@Put("/azure/client-generator-core/usage/modelInReadOnlyProperty")
@ExpectedResponses({ 200 })
@UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
@UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
@UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
@UnexpectedResponseExceptionType(HttpResponseException.class)
Response<BinaryData> modelInReadOnlyPropertySync(@HostParam("endpoint") String endpoint,
@HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept,
@BodyParam("application/json") BinaryData body, RequestOptions requestOptions, Context context);
}
/**
* Expected body parameter:
* ```json
* {
* "name": &lt;any string&gt;
* }
* ```.
* <p><strong>Request Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param body The body parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return the {@link Response} on successful completion of {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> inputToInputOutputWithResponseAsync(BinaryData body, RequestOptions requestOptions) {
final String contentType = "application/json";
return FluxUtil.withContext(context -> service.inputToInputOutput(this.client.getEndpoint(), contentType, body,
requestOptions, context));
}
/**
* Expected body parameter:
* ```json
* {
* "name": &lt;any string&gt;
* }
* ```.
* <p><strong>Request Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param body The body parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return the {@link Response}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> inputToInputOutputWithResponse(BinaryData body, RequestOptions requestOptions) {
final String contentType = "application/json";
return service.inputToInputOutputSync(this.client.getEndpoint(), contentType, body, requestOptions,
Context.NONE);
}
/**
* Expected response body:
* ```json
* {
* "name": &lt;any string&gt;
* }
* ```.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return usage override to roundtrip along with {@link Response} on successful completion of {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BinaryData>> outputToInputOutputWithResponseAsync(RequestOptions requestOptions) {
final String accept = "application/json";
return FluxUtil.withContext(
context -> service.outputToInputOutput(this.client.getEndpoint(), accept, requestOptions, context));
}
/**
* Expected response body:
* ```json
* {
* "name": &lt;any string&gt;
* }
* ```.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* name: String (Required)
* }
* }</pre>
*
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return usage override to roundtrip along with {@link Response}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BinaryData> outputToInputOutputWithResponse(RequestOptions requestOptions) {
final String accept = "application/json";
return service.outputToInputOutputSync(this.client.getEndpoint(), accept, requestOptions, Context.NONE);
}
/**
* "ResultModel" should be usage=output, as it is read-only and does not exist in request body.
*
* Expected body parameter:
* ```json
* {
* }
* ```
*
* Expected response body:
* ```json
* {
* "result": {
* "name": &lt;any string&gt;
* }
* }
* ```.
* <p><strong>Request Body Schema</strong></p>
*
* <pre>{@code
* {
* result (Required): {
* name: String (Required)
* }
* }
* }</pre>
*
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* result (Required): {
* name: String (Required)
* }
* }
* }</pre>
*
* @param body The body parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return the response body along with {@link Response} on successful completion of {@link Mono}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BinaryData>> modelInReadOnlyPropertyWithResponseAsync(BinaryData body,
RequestOptions requestOptions) {
final String contentType = "application/json";
final String accept = "application/json";
return FluxUtil.withContext(context -> service.modelInReadOnlyProperty(this.client.getEndpoint(), contentType,
accept, body, requestOptions, context));
}
/**
* "ResultModel" should be usage=output, as it is read-only and does not exist in request body.
*
* Expected body parameter:
* ```json
* {
* }
* ```
*
* Expected response body:
* ```json
* {
* "result": {
* "name": &lt;any string&gt;
* }
* }
* ```.
* <p><strong>Request Body Schema</strong></p>
*
* <pre>{@code
* {
* result (Required): {
* name: String (Required)
* }
* }
* }</pre>
*
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* result (Required): {
* name: String (Required)
* }
* }
* }</pre>
*
* @param body The body parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return the response body along with {@link Response}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BinaryData> modelInReadOnlyPropertyWithResponse(BinaryData body, RequestOptions requestOptions) {
final String contentType = "application/json";
final String accept = "application/json";
return service.modelInReadOnlyPropertySync(this.client.getEndpoint(), contentType, accept, body, requestOptions,
Context.NONE);
}
}

Просмотреть файл

@ -0,0 +1,107 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.usage.implementation;
import com.azure.core.http.HttpPipeline;
import com.azure.core.http.HttpPipelineBuilder;
import com.azure.core.http.policy.RetryPolicy;
import com.azure.core.http.policy.UserAgentPolicy;
import com.azure.core.util.serializer.JacksonAdapter;
import com.azure.core.util.serializer.SerializerAdapter;
/**
* Initializes a new instance of the UsageClient type.
*/
public final class UsageClientImpl {
/**
* Service host.
*/
private final String endpoint;
/**
* Gets Service host.
*
* @return the endpoint value.
*/
public String getEndpoint() {
return this.endpoint;
}
/**
* The HTTP pipeline to send requests through.
*/
private final HttpPipeline httpPipeline;
/**
* Gets The HTTP pipeline to send requests through.
*
* @return the httpPipeline value.
*/
public HttpPipeline getHttpPipeline() {
return this.httpPipeline;
}
/**
* The serializer to serialize an object into a string.
*/
private final SerializerAdapter serializerAdapter;
/**
* Gets The serializer to serialize an object into a string.
*
* @return the serializerAdapter value.
*/
public SerializerAdapter getSerializerAdapter() {
return this.serializerAdapter;
}
/**
* The ModelInOperationsImpl object to access its operations.
*/
private final ModelInOperationsImpl modelInOperations;
/**
* Gets the ModelInOperationsImpl object to access its operations.
*
* @return the ModelInOperationsImpl object.
*/
public ModelInOperationsImpl getModelInOperations() {
return this.modelInOperations;
}
/**
* Initializes an instance of UsageClient client.
*
* @param endpoint Service host.
*/
public UsageClientImpl(String endpoint) {
this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(),
JacksonAdapter.createDefaultSerializerAdapter(), endpoint);
}
/**
* Initializes an instance of UsageClient client.
*
* @param httpPipeline The HTTP pipeline to send requests through.
* @param endpoint Service host.
*/
public UsageClientImpl(HttpPipeline httpPipeline, String endpoint) {
this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), endpoint);
}
/**
* Initializes an instance of UsageClient client.
*
* @param httpPipeline The HTTP pipeline to send requests through.
* @param serializerAdapter The serializer to serialize an object into a string.
* @param endpoint Service host.
*/
public UsageClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint) {
this.httpPipeline = httpPipeline;
this.serializerAdapter = serializerAdapter;
this.endpoint = endpoint;
this.modelInOperations = new ModelInOperationsImpl(this);
}
}

Просмотреть файл

@ -0,0 +1,11 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
/**
* <!-- start generated doc -->
* Package containing the implementations for Usage.
* Test for internal decorator.
* <!-- end generated doc -->
*/
package com._specs_.azure.clientgenerator.core.usage.implementation;

Просмотреть файл

@ -0,0 +1,83 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.usage.models;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.Immutable;
import com.azure.json.JsonReader;
import com.azure.json.JsonSerializable;
import com.azure.json.JsonToken;
import com.azure.json.JsonWriter;
import java.io.IOException;
/**
* Usage override to roundtrip.
*/
@Immutable
public final class InputModel implements JsonSerializable<InputModel> {
/*
* The name property.
*/
@Generated
private final String name;
/**
* Creates an instance of InputModel class.
*
* @param name the name value to set.
*/
@Generated
public InputModel(String name) {
this.name = name;
}
/**
* Get the name property: The name property.
*
* @return the name value.
*/
@Generated
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Generated
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStartObject();
jsonWriter.writeStringField("name", this.name);
return jsonWriter.writeEndObject();
}
/**
* Reads an instance of InputModel from the JsonReader.
*
* @param jsonReader The JsonReader being read.
* @return An instance of InputModel if the JsonReader was pointing to an instance of it, or null if it was pointing
* to JSON null.
* @throws IllegalStateException If the deserialized JSON object was missing any required properties.
* @throws IOException If an error occurs while reading the InputModel.
*/
@Generated
public static InputModel fromJson(JsonReader jsonReader) throws IOException {
return jsonReader.readObject(reader -> {
String name = null;
while (reader.nextToken() != JsonToken.END_OBJECT) {
String fieldName = reader.getFieldName();
reader.nextToken();
if ("name".equals(fieldName)) {
name = reader.getString();
} else {
reader.skipChildren();
}
}
return new InputModel(name);
});
}
}

Просмотреть файл

@ -0,0 +1,83 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.usage.models;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.Immutable;
import com.azure.json.JsonReader;
import com.azure.json.JsonSerializable;
import com.azure.json.JsonToken;
import com.azure.json.JsonWriter;
import java.io.IOException;
/**
* Not used anywhere, but access is override to public so still need to be generated and exported with serialization.
*/
@Immutable
public final class OrphanModel implements JsonSerializable<OrphanModel> {
/*
* The name property.
*/
@Generated
private final String name;
/**
* Creates an instance of OrphanModel class.
*
* @param name the name value to set.
*/
@Generated
public OrphanModel(String name) {
this.name = name;
}
/**
* Get the name property: The name property.
*
* @return the name value.
*/
@Generated
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Generated
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStartObject();
jsonWriter.writeStringField("name", this.name);
return jsonWriter.writeEndObject();
}
/**
* Reads an instance of OrphanModel from the JsonReader.
*
* @param jsonReader The JsonReader being read.
* @return An instance of OrphanModel if the JsonReader was pointing to an instance of it, or null if it was
* pointing to JSON null.
* @throws IllegalStateException If the deserialized JSON object was missing any required properties.
* @throws IOException If an error occurs while reading the OrphanModel.
*/
@Generated
public static OrphanModel fromJson(JsonReader jsonReader) throws IOException {
return jsonReader.readObject(reader -> {
String name = null;
while (reader.nextToken() != JsonToken.END_OBJECT) {
String fieldName = reader.getFieldName();
reader.nextToken();
if ("name".equals(fieldName)) {
name = reader.getString();
} else {
reader.skipChildren();
}
}
return new OrphanModel(name);
});
}
}

Просмотреть файл

@ -0,0 +1,83 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.usage.models;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.Immutable;
import com.azure.json.JsonReader;
import com.azure.json.JsonSerializable;
import com.azure.json.JsonToken;
import com.azure.json.JsonWriter;
import java.io.IOException;
/**
* Usage override to roundtrip.
*/
@Immutable
public final class OutputModel implements JsonSerializable<OutputModel> {
/*
* The name property.
*/
@Generated
private final String name;
/**
* Creates an instance of OutputModel class.
*
* @param name the name value to set.
*/
@Generated
public OutputModel(String name) {
this.name = name;
}
/**
* Get the name property: The name property.
*
* @return the name value.
*/
@Generated
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Generated
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStartObject();
jsonWriter.writeStringField("name", this.name);
return jsonWriter.writeEndObject();
}
/**
* Reads an instance of OutputModel from the JsonReader.
*
* @param jsonReader The JsonReader being read.
* @return An instance of OutputModel if the JsonReader was pointing to an instance of it, or null if it was
* pointing to JSON null.
* @throws IllegalStateException If the deserialized JSON object was missing any required properties.
* @throws IOException If an error occurs while reading the OutputModel.
*/
@Generated
public static OutputModel fromJson(JsonReader jsonReader) throws IOException {
return jsonReader.readObject(reader -> {
String name = null;
while (reader.nextToken() != JsonToken.END_OBJECT) {
String fieldName = reader.getFieldName();
reader.nextToken();
if ("name".equals(fieldName)) {
name = reader.getString();
} else {
reader.skipChildren();
}
}
return new OutputModel(name);
});
}
}

Просмотреть файл

@ -0,0 +1,83 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.usage.models;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.Immutable;
import com.azure.json.JsonReader;
import com.azure.json.JsonSerializable;
import com.azure.json.JsonToken;
import com.azure.json.JsonWriter;
import java.io.IOException;
/**
* The ResultModel model.
*/
@Immutable
public final class ResultModel implements JsonSerializable<ResultModel> {
/*
* The name property.
*/
@Generated
private final String name;
/**
* Creates an instance of ResultModel class.
*
* @param name the name value to set.
*/
@Generated
private ResultModel(String name) {
this.name = name;
}
/**
* Get the name property: The name property.
*
* @return the name value.
*/
@Generated
public String getName() {
return this.name;
}
/**
* {@inheritDoc}
*/
@Generated
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStartObject();
jsonWriter.writeStringField("name", this.name);
return jsonWriter.writeEndObject();
}
/**
* Reads an instance of ResultModel from the JsonReader.
*
* @param jsonReader The JsonReader being read.
* @return An instance of ResultModel if the JsonReader was pointing to an instance of it, or null if it was
* pointing to JSON null.
* @throws IllegalStateException If the deserialized JSON object was missing any required properties.
* @throws IOException If an error occurs while reading the ResultModel.
*/
@Generated
public static ResultModel fromJson(JsonReader jsonReader) throws IOException {
return jsonReader.readObject(reader -> {
String name = null;
while (reader.nextToken() != JsonToken.END_OBJECT) {
String fieldName = reader.getFieldName();
reader.nextToken();
if ("name".equals(fieldName)) {
name = reader.getString();
} else {
reader.skipChildren();
}
}
return new ResultModel(name);
});
}
}

Просмотреть файл

@ -0,0 +1,80 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.clientgenerator.core.usage.models;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.Immutable;
import com.azure.json.JsonReader;
import com.azure.json.JsonSerializable;
import com.azure.json.JsonToken;
import com.azure.json.JsonWriter;
import java.io.IOException;
/**
* The RoundTripModel model.
*/
@Immutable
public final class RoundTripModel implements JsonSerializable<RoundTripModel> {
/*
* The result property.
*/
@Generated
private ResultModel result;
/**
* Creates an instance of RoundTripModel class.
*/
@Generated
public RoundTripModel() {
}
/**
* Get the result property: The result property.
*
* @return the result value.
*/
@Generated
public ResultModel getResult() {
return this.result;
}
/**
* {@inheritDoc}
*/
@Generated
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStartObject();
return jsonWriter.writeEndObject();
}
/**
* Reads an instance of RoundTripModel from the JsonReader.
*
* @param jsonReader The JsonReader being read.
* @return An instance of RoundTripModel if the JsonReader was pointing to an instance of it, or null if it was
* pointing to JSON null.
* @throws IllegalStateException If the deserialized JSON object was missing any required properties.
* @throws IOException If an error occurs while reading the RoundTripModel.
*/
@Generated
public static RoundTripModel fromJson(JsonReader jsonReader) throws IOException {
return jsonReader.readObject(reader -> {
RoundTripModel deserializedRoundTripModel = new RoundTripModel();
while (reader.nextToken() != JsonToken.END_OBJECT) {
String fieldName = reader.getFieldName();
reader.nextToken();
if ("result".equals(fieldName)) {
deserializedRoundTripModel.result = ResultModel.fromJson(reader);
} else {
reader.skipChildren();
}
}
return deserializedRoundTripModel;
});
}
}

Просмотреть файл

@ -0,0 +1,11 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
/**
* <!-- start generated doc -->
* Package containing the data models for Usage.
* Test for internal decorator.
* <!-- end generated doc -->
*/
package com._specs_.azure.clientgenerator.core.usage.models;

Просмотреть файл

@ -0,0 +1,11 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
/**
* <!-- start generated doc -->
* Package containing the classes for Usage.
* Test for internal decorator.
* <!-- end generated doc -->
*/
package com._specs_.azure.clientgenerator.core.usage;

Просмотреть файл

@ -0,0 +1,524 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.core.basic;
import com._specs_.azure.core.basic.implementation.BasicClientImpl;
import com._specs_.azure.core.basic.implementation.JsonMergePatchHelper;
import com._specs_.azure.core.basic.models.User;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.exception.ClientAuthenticationException;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedResponse;
import com.azure.core.http.rest.PagedResponseBase;
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.util.BinaryData;
import com.azure.core.util.FluxUtil;
import java.util.List;
import java.util.stream.Collectors;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* Initializes a new instance of the asynchronous BasicClient type.
*/
@ServiceClient(builder = BasicClientBuilder.class, isAsync = true)
public final class BasicAsyncClient {
@Generated
private final BasicClientImpl serviceClient;
/**
* Initializes an instance of BasicAsyncClient class.
*
* @param serviceClient the service client implementation.
*/
@Generated
BasicAsyncClient(BasicClientImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* Adds a user or updates a user's fields.
*
* Creates or updates a User.
* <p><strong>Request Body Schema</strong></p>
*
* <pre>{@code
* {
* id: int (Required)
* name: String (Optional, Required on create)
* orders (Optional): [
* (Optional){
* id: int (Required)
* userId: int (Optional, Required on create)
* detail: String (Optional, Required on create)
* }
* ]
* etag: String (Required)
* }
* }</pre>
*
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* id: int (Required)
* name: String (Optional, Required on create)
* orders (Optional): [
* (Optional){
* id: int (Required)
* userId: int (Optional, Required on create)
* detail: String (Optional, Required on create)
* }
* ]
* etag: String (Required)
* }
* }</pre>
*
* @param id The user's id.
* @param resource The resource instance.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return details about a user along with {@link Response} on successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BinaryData>> createOrUpdateWithResponse(int id, BinaryData resource,
RequestOptions requestOptions) {
return this.serviceClient.createOrUpdateWithResponseAsync(id, resource, requestOptions);
}
/**
* Adds a user or replaces a user's fields.
*
* Creates or replaces a User.
* <p><strong>Request Body Schema</strong></p>
*
* <pre>{@code
* {
* id: int (Required)
* name: String (Optional, Required on create)
* orders (Optional): [
* (Optional){
* id: int (Required)
* userId: int (Optional, Required on create)
* detail: String (Optional, Required on create)
* }
* ]
* etag: String (Required)
* }
* }</pre>
*
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* id: int (Required)
* name: String (Optional, Required on create)
* orders (Optional): [
* (Optional){
* id: int (Required)
* userId: int (Optional, Required on create)
* detail: String (Optional, Required on create)
* }
* ]
* etag: String (Required)
* }
* }</pre>
*
* @param id The user's id.
* @param resource The resource instance.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return details about a user along with {@link Response} on successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BinaryData>> createOrReplaceWithResponse(int id, BinaryData resource,
RequestOptions requestOptions) {
return this.serviceClient.createOrReplaceWithResponseAsync(id, resource, requestOptions);
}
/**
* Gets a user.
*
* Gets a User.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* id: int (Required)
* name: String (Optional, Required on create)
* orders (Optional): [
* (Optional){
* id: int (Required)
* userId: int (Optional, Required on create)
* detail: String (Optional, Required on create)
* }
* ]
* etag: String (Required)
* }
* }</pre>
*
* @param id The user's id.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return a user.
*
* Gets a User along with {@link Response} on successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BinaryData>> getWithResponse(int id, RequestOptions requestOptions) {
return this.serviceClient.getWithResponseAsync(id, requestOptions);
}
/**
* Lists all users.
*
* Lists all Users.
* <p><strong>Query Parameters</strong></p>
* <table border="1">
* <caption>Query Parameters</caption>
* <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr>
* <tr><td>top</td><td>Integer</td><td>No</td><td>The number of result items to return.</td></tr>
* <tr><td>skip</td><td>Integer</td><td>No</td><td>The number of result items to skip.</td></tr>
* <tr><td>maxpagesize</td><td>Integer</td><td>No</td><td>The maximum number of result items per page.</td></tr>
* <tr><td>orderby</td><td>List&lt;String&gt;</td><td>No</td><td>Expressions that specify the order of returned
* results. Call {@link RequestOptions#addQueryParam} to add string to array.</td></tr>
* <tr><td>filter</td><td>String</td><td>No</td><td>Filter the result list using the given expression.</td></tr>
* <tr><td>select</td><td>List&lt;String&gt;</td><td>No</td><td>Select the specified fields to be included in the
* response. Call {@link RequestOptions#addQueryParam} to add string to array.</td></tr>
* <tr><td>expand</td><td>List&lt;String&gt;</td><td>No</td><td>Expand the indicated resources into the response.
* Call {@link RequestOptions#addQueryParam} to add string to array.</td></tr>
* </table>
* You can add these to a request with {@link RequestOptions#addQueryParam}
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* id: int (Required)
* name: String (Optional, Required on create)
* orders (Optional): [
* (Optional){
* id: int (Required)
* userId: int (Optional, Required on create)
* detail: String (Optional, Required on create)
* }
* ]
* etag: String (Required)
* }
* }</pre>
*
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return paged collection of User items as paginated response with {@link PagedFlux}.
*/
@Generated
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<BinaryData> list(RequestOptions requestOptions) {
return this.serviceClient.listAsync(requestOptions);
}
/**
* Deletes a user.
*
* Deletes a User.
*
* @param id The user's id.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return the {@link Response} on successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteWithResponse(int id, RequestOptions requestOptions) {
return this.serviceClient.deleteWithResponseAsync(id, requestOptions);
}
/**
* Exports a user.
*
* Exports a User.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* id: int (Required)
* name: String (Optional, Required on create)
* orders (Optional): [
* (Optional){
* id: int (Required)
* userId: int (Optional, Required on create)
* detail: String (Optional, Required on create)
* }
* ]
* etag: String (Required)
* }
* }</pre>
*
* @param id The user's id.
* @param format The format of the data.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return details about a user along with {@link Response} on successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BinaryData>> exportWithResponse(int id, String format, RequestOptions requestOptions) {
return this.serviceClient.exportWithResponseAsync(id, format, requestOptions);
}
/**
* Adds a user or updates a user's fields.
*
* Creates or updates a User.
*
* @param id The user's id.
* @param resource The resource instance.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return details about a user on successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<User> createOrUpdate(int id, User resource) {
// Generated convenience method for createOrUpdateWithResponse
RequestOptions requestOptions = new RequestOptions();
JsonMergePatchHelper.getUserAccessor().prepareModelForJsonMergePatch(resource, true);
BinaryData resourceInBinaryData = BinaryData.fromObject(resource);
// BinaryData.fromObject() will not fire serialization, use getLength() to fire serialization.
resourceInBinaryData.getLength();
JsonMergePatchHelper.getUserAccessor().prepareModelForJsonMergePatch(resource, false);
return createOrUpdateWithResponse(id, resourceInBinaryData, requestOptions).flatMap(FluxUtil::toMono)
.map(protocolMethodData -> protocolMethodData.toObject(User.class));
}
/**
* Adds a user or replaces a user's fields.
*
* Creates or replaces a User.
*
* @param id The user's id.
* @param resource The resource instance.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return details about a user on successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<User> createOrReplace(int id, User resource) {
// Generated convenience method for createOrReplaceWithResponse
RequestOptions requestOptions = new RequestOptions();
return createOrReplaceWithResponse(id, BinaryData.fromObject(resource), requestOptions)
.flatMap(FluxUtil::toMono)
.map(protocolMethodData -> protocolMethodData.toObject(User.class));
}
/**
* Gets a user.
*
* Gets a User.
*
* @param id The user's id.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a user.
*
* Gets a User on successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<User> get(int id) {
// Generated convenience method for getWithResponse
RequestOptions requestOptions = new RequestOptions();
return getWithResponse(id, requestOptions).flatMap(FluxUtil::toMono)
.map(protocolMethodData -> protocolMethodData.toObject(User.class));
}
/**
* Lists all users.
*
* Lists all Users.
*
* @param top The number of result items to return.
* @param skip The number of result items to skip.
* @param orderBy Expressions that specify the order of returned results.
* @param filter Filter the result list using the given expression.
* @param select Select the specified fields to be included in the response.
* @param expand Expand the indicated resources into the response.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return paged collection of User items as paginated response with {@link PagedFlux}.
*/
@Generated
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<User> list(Integer top, Integer skip, List<String> orderBy, String filter, List<String> select,
List<String> expand) {
// Generated convenience method for list
RequestOptions requestOptions = new RequestOptions();
if (top != null) {
requestOptions.addQueryParam("top", String.valueOf(top), false);
}
if (skip != null) {
requestOptions.addQueryParam("skip", String.valueOf(skip), false);
}
if (orderBy != null) {
for (String paramItemValue : orderBy) {
if (paramItemValue != null) {
requestOptions.addQueryParam("orderby", paramItemValue, false);
}
}
}
if (filter != null) {
requestOptions.addQueryParam("filter", filter, false);
}
if (select != null) {
for (String paramItemValue : select) {
if (paramItemValue != null) {
requestOptions.addQueryParam("select", paramItemValue, false);
}
}
}
if (expand != null) {
for (String paramItemValue : expand) {
if (paramItemValue != null) {
requestOptions.addQueryParam("expand", paramItemValue, false);
}
}
}
PagedFlux<BinaryData> pagedFluxResponse = list(requestOptions);
return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> {
Flux<PagedResponse<BinaryData>> flux = (continuationTokenParam == null)
? pagedFluxResponse.byPage().take(1)
: pagedFluxResponse.byPage(continuationTokenParam).take(1);
return flux.map(pagedResponse -> new PagedResponseBase<Void, User>(pagedResponse.getRequest(),
pagedResponse.getStatusCode(), pagedResponse.getHeaders(),
pagedResponse.getValue()
.stream()
.map(protocolMethodData -> protocolMethodData.toObject(User.class))
.collect(Collectors.toList()),
pagedResponse.getContinuationToken(), null));
});
}
/**
* Lists all users.
*
* Lists all Users.
*
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return paged collection of User items as paginated response with {@link PagedFlux}.
*/
@Generated
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<User> list() {
// Generated convenience method for list
RequestOptions requestOptions = new RequestOptions();
PagedFlux<BinaryData> pagedFluxResponse = list(requestOptions);
return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> {
Flux<PagedResponse<BinaryData>> flux = (continuationTokenParam == null)
? pagedFluxResponse.byPage().take(1)
: pagedFluxResponse.byPage(continuationTokenParam).take(1);
return flux.map(pagedResponse -> new PagedResponseBase<Void, User>(pagedResponse.getRequest(),
pagedResponse.getStatusCode(), pagedResponse.getHeaders(),
pagedResponse.getValue()
.stream()
.map(protocolMethodData -> protocolMethodData.toObject(User.class))
.collect(Collectors.toList()),
pagedResponse.getContinuationToken(), null));
});
}
/**
* Deletes a user.
*
* Deletes a User.
*
* @param id The user's id.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return A {@link Mono} that completes when a successful response is received.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> delete(int id) {
// Generated convenience method for deleteWithResponse
RequestOptions requestOptions = new RequestOptions();
return deleteWithResponse(id, requestOptions).flatMap(FluxUtil::toMono);
}
/**
* Exports a user.
*
* Exports a User.
*
* @param id The user's id.
* @param format The format of the data.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return details about a user on successful completion of {@link Mono}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<User> export(int id, String format) {
// Generated convenience method for exportWithResponse
RequestOptions requestOptions = new RequestOptions();
return exportWithResponse(id, format, requestOptions).flatMap(FluxUtil::toMono)
.map(protocolMethodData -> protocolMethodData.toObject(User.class));
}
}

Просмотреть файл

@ -0,0 +1,488 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.core.basic;
import com._specs_.azure.core.basic.implementation.BasicClientImpl;
import com._specs_.azure.core.basic.implementation.JsonMergePatchHelper;
import com._specs_.azure.core.basic.models.User;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.exception.ClientAuthenticationException;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.util.BinaryData;
import java.util.List;
/**
* Initializes a new instance of the synchronous BasicClient type.
*/
@ServiceClient(builder = BasicClientBuilder.class)
public final class BasicClient {
@Generated
private final BasicClientImpl serviceClient;
/**
* Initializes an instance of BasicClient class.
*
* @param serviceClient the service client implementation.
*/
@Generated
BasicClient(BasicClientImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* Adds a user or updates a user's fields.
*
* Creates or updates a User.
* <p><strong>Request Body Schema</strong></p>
*
* <pre>{@code
* {
* id: int (Required)
* name: String (Optional, Required on create)
* orders (Optional): [
* (Optional){
* id: int (Required)
* userId: int (Optional, Required on create)
* detail: String (Optional, Required on create)
* }
* ]
* etag: String (Required)
* }
* }</pre>
*
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* id: int (Required)
* name: String (Optional, Required on create)
* orders (Optional): [
* (Optional){
* id: int (Required)
* userId: int (Optional, Required on create)
* detail: String (Optional, Required on create)
* }
* ]
* etag: String (Required)
* }
* }</pre>
*
* @param id The user's id.
* @param resource The resource instance.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return details about a user along with {@link Response}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BinaryData> createOrUpdateWithResponse(int id, BinaryData resource, RequestOptions requestOptions) {
return this.serviceClient.createOrUpdateWithResponse(id, resource, requestOptions);
}
/**
* Adds a user or replaces a user's fields.
*
* Creates or replaces a User.
* <p><strong>Request Body Schema</strong></p>
*
* <pre>{@code
* {
* id: int (Required)
* name: String (Optional, Required on create)
* orders (Optional): [
* (Optional){
* id: int (Required)
* userId: int (Optional, Required on create)
* detail: String (Optional, Required on create)
* }
* ]
* etag: String (Required)
* }
* }</pre>
*
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* id: int (Required)
* name: String (Optional, Required on create)
* orders (Optional): [
* (Optional){
* id: int (Required)
* userId: int (Optional, Required on create)
* detail: String (Optional, Required on create)
* }
* ]
* etag: String (Required)
* }
* }</pre>
*
* @param id The user's id.
* @param resource The resource instance.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return details about a user along with {@link Response}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BinaryData> createOrReplaceWithResponse(int id, BinaryData resource,
RequestOptions requestOptions) {
return this.serviceClient.createOrReplaceWithResponse(id, resource, requestOptions);
}
/**
* Gets a user.
*
* Gets a User.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* id: int (Required)
* name: String (Optional, Required on create)
* orders (Optional): [
* (Optional){
* id: int (Required)
* userId: int (Optional, Required on create)
* detail: String (Optional, Required on create)
* }
* ]
* etag: String (Required)
* }
* }</pre>
*
* @param id The user's id.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return a user.
*
* Gets a User along with {@link Response}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BinaryData> getWithResponse(int id, RequestOptions requestOptions) {
return this.serviceClient.getWithResponse(id, requestOptions);
}
/**
* Lists all users.
*
* Lists all Users.
* <p><strong>Query Parameters</strong></p>
* <table border="1">
* <caption>Query Parameters</caption>
* <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr>
* <tr><td>top</td><td>Integer</td><td>No</td><td>The number of result items to return.</td></tr>
* <tr><td>skip</td><td>Integer</td><td>No</td><td>The number of result items to skip.</td></tr>
* <tr><td>maxpagesize</td><td>Integer</td><td>No</td><td>The maximum number of result items per page.</td></tr>
* <tr><td>orderby</td><td>List&lt;String&gt;</td><td>No</td><td>Expressions that specify the order of returned
* results. Call {@link RequestOptions#addQueryParam} to add string to array.</td></tr>
* <tr><td>filter</td><td>String</td><td>No</td><td>Filter the result list using the given expression.</td></tr>
* <tr><td>select</td><td>List&lt;String&gt;</td><td>No</td><td>Select the specified fields to be included in the
* response. Call {@link RequestOptions#addQueryParam} to add string to array.</td></tr>
* <tr><td>expand</td><td>List&lt;String&gt;</td><td>No</td><td>Expand the indicated resources into the response.
* Call {@link RequestOptions#addQueryParam} to add string to array.</td></tr>
* </table>
* You can add these to a request with {@link RequestOptions#addQueryParam}
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* id: int (Required)
* name: String (Optional, Required on create)
* orders (Optional): [
* (Optional){
* id: int (Required)
* userId: int (Optional, Required on create)
* detail: String (Optional, Required on create)
* }
* ]
* etag: String (Required)
* }
* }</pre>
*
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return paged collection of User items as paginated response with {@link PagedIterable}.
*/
@Generated
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<BinaryData> list(RequestOptions requestOptions) {
return this.serviceClient.list(requestOptions);
}
/**
* Deletes a user.
*
* Deletes a User.
*
* @param id The user's id.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return the {@link Response}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> deleteWithResponse(int id, RequestOptions requestOptions) {
return this.serviceClient.deleteWithResponse(id, requestOptions);
}
/**
* Exports a user.
*
* Exports a User.
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* id: int (Required)
* name: String (Optional, Required on create)
* orders (Optional): [
* (Optional){
* id: int (Required)
* userId: int (Optional, Required on create)
* detail: String (Optional, Required on create)
* }
* ]
* etag: String (Required)
* }
* }</pre>
*
* @param id The user's id.
* @param format The format of the data.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return details about a user along with {@link Response}.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<BinaryData> exportWithResponse(int id, String format, RequestOptions requestOptions) {
return this.serviceClient.exportWithResponse(id, format, requestOptions);
}
/**
* Adds a user or updates a user's fields.
*
* Creates or updates a User.
*
* @param id The user's id.
* @param resource The resource instance.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return details about a user.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public User createOrUpdate(int id, User resource) {
// Generated convenience method for createOrUpdateWithResponse
RequestOptions requestOptions = new RequestOptions();
JsonMergePatchHelper.getUserAccessor().prepareModelForJsonMergePatch(resource, true);
BinaryData resourceInBinaryData = BinaryData.fromObject(resource);
// BinaryData.fromObject() will not fire serialization, use getLength() to fire serialization.
resourceInBinaryData.getLength();
JsonMergePatchHelper.getUserAccessor().prepareModelForJsonMergePatch(resource, false);
return createOrUpdateWithResponse(id, resourceInBinaryData, requestOptions).getValue().toObject(User.class);
}
/**
* Adds a user or replaces a user's fields.
*
* Creates or replaces a User.
*
* @param id The user's id.
* @param resource The resource instance.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return details about a user.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public User createOrReplace(int id, User resource) {
// Generated convenience method for createOrReplaceWithResponse
RequestOptions requestOptions = new RequestOptions();
return createOrReplaceWithResponse(id, BinaryData.fromObject(resource), requestOptions).getValue()
.toObject(User.class);
}
/**
* Gets a user.
*
* Gets a User.
*
* @param id The user's id.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a user.
*
* Gets a User.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public User get(int id) {
// Generated convenience method for getWithResponse
RequestOptions requestOptions = new RequestOptions();
return getWithResponse(id, requestOptions).getValue().toObject(User.class);
}
/**
* Lists all users.
*
* Lists all Users.
*
* @param top The number of result items to return.
* @param skip The number of result items to skip.
* @param orderBy Expressions that specify the order of returned results.
* @param filter Filter the result list using the given expression.
* @param select Select the specified fields to be included in the response.
* @param expand Expand the indicated resources into the response.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return paged collection of User items as paginated response with {@link PagedIterable}.
*/
@Generated
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<User> list(Integer top, Integer skip, List<String> orderBy, String filter, List<String> select,
List<String> expand) {
// Generated convenience method for list
RequestOptions requestOptions = new RequestOptions();
if (top != null) {
requestOptions.addQueryParam("top", String.valueOf(top), false);
}
if (skip != null) {
requestOptions.addQueryParam("skip", String.valueOf(skip), false);
}
if (orderBy != null) {
for (String paramItemValue : orderBy) {
if (paramItemValue != null) {
requestOptions.addQueryParam("orderby", paramItemValue, false);
}
}
}
if (filter != null) {
requestOptions.addQueryParam("filter", filter, false);
}
if (select != null) {
for (String paramItemValue : select) {
if (paramItemValue != null) {
requestOptions.addQueryParam("select", paramItemValue, false);
}
}
}
if (expand != null) {
for (String paramItemValue : expand) {
if (paramItemValue != null) {
requestOptions.addQueryParam("expand", paramItemValue, false);
}
}
}
return serviceClient.list(requestOptions).mapPage(bodyItemValue -> bodyItemValue.toObject(User.class));
}
/**
* Lists all users.
*
* Lists all Users.
*
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return paged collection of User items as paginated response with {@link PagedIterable}.
*/
@Generated
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<User> list() {
// Generated convenience method for list
RequestOptions requestOptions = new RequestOptions();
return serviceClient.list(requestOptions).mapPage(bodyItemValue -> bodyItemValue.toObject(User.class));
}
/**
* Deletes a user.
*
* Deletes a User.
*
* @param id The user's id.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public void delete(int id) {
// Generated convenience method for deleteWithResponse
RequestOptions requestOptions = new RequestOptions();
deleteWithResponse(id, requestOptions).getValue();
}
/**
* Exports a user.
*
* Exports a User.
*
* @param id The user's id.
* @param format The format of the data.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return details about a user.
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public User export(int id, String format) {
// Generated convenience method for exportWithResponse
RequestOptions requestOptions = new RequestOptions();
return exportWithResponse(id, format, requestOptions).getValue().toObject(User.class);
}
}

Просмотреть файл

@ -0,0 +1,308 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.core.basic;
import com._specs_.azure.core.basic.implementation.BasicClientImpl;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.ServiceClientBuilder;
import com.azure.core.client.traits.ConfigurationTrait;
import com.azure.core.client.traits.EndpointTrait;
import com.azure.core.client.traits.HttpTrait;
import com.azure.core.http.HttpClient;
import com.azure.core.http.HttpHeaders;
import com.azure.core.http.HttpPipeline;
import com.azure.core.http.HttpPipelineBuilder;
import com.azure.core.http.HttpPipelinePosition;
import com.azure.core.http.policy.AddDatePolicy;
import com.azure.core.http.policy.AddHeadersFromContextPolicy;
import com.azure.core.http.policy.AddHeadersPolicy;
import com.azure.core.http.policy.HttpLoggingPolicy;
import com.azure.core.http.policy.HttpLogOptions;
import com.azure.core.http.policy.HttpPipelinePolicy;
import com.azure.core.http.policy.HttpPolicyProviders;
import com.azure.core.http.policy.RequestIdPolicy;
import com.azure.core.http.policy.RetryOptions;
import com.azure.core.http.policy.RetryPolicy;
import com.azure.core.http.policy.UserAgentPolicy;
import com.azure.core.util.ClientOptions;
import com.azure.core.util.Configuration;
import com.azure.core.util.CoreUtils;
import com.azure.core.util.builder.ClientBuilderUtil;
import com.azure.core.util.logging.ClientLogger;
import com.azure.core.util.serializer.JacksonAdapter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* A builder for creating a new instance of the BasicClient type.
*/
@ServiceClientBuilder(serviceClients = { BasicClient.class, BasicAsyncClient.class })
public final class BasicClientBuilder implements HttpTrait<BasicClientBuilder>, ConfigurationTrait<BasicClientBuilder>,
EndpointTrait<BasicClientBuilder> {
@Generated
private static final String SDK_NAME = "name";
@Generated
private static final String SDK_VERSION = "version";
@Generated
private static final Map<String, String> PROPERTIES
= CoreUtils.getProperties("_specs_-azure-core-basic.properties");
@Generated
private final List<HttpPipelinePolicy> pipelinePolicies;
/**
* Create an instance of the BasicClientBuilder.
*/
@Generated
public BasicClientBuilder() {
this.pipelinePolicies = new ArrayList<>();
}
/*
* The HTTP pipeline to send requests through.
*/
@Generated
private HttpPipeline pipeline;
/**
* {@inheritDoc}.
*/
@Generated
@Override
public BasicClientBuilder pipeline(HttpPipeline pipeline) {
if (this.pipeline != null && pipeline == null) {
LOGGER.atInfo().log("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.pipeline = pipeline;
return this;
}
/*
* The HTTP client used to send the request.
*/
@Generated
private HttpClient httpClient;
/**
* {@inheritDoc}.
*/
@Generated
@Override
public BasicClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/*
* The logging configuration for HTTP requests and responses.
*/
@Generated
private HttpLogOptions httpLogOptions;
/**
* {@inheritDoc}.
*/
@Generated
@Override
public BasicClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/*
* The client options such as application ID and custom headers to set on a request.
*/
@Generated
private ClientOptions clientOptions;
/**
* {@inheritDoc}.
*/
@Generated
@Override
public BasicClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/*
* The retry options to configure retry policy for failed requests.
*/
@Generated
private RetryOptions retryOptions;
/**
* {@inheritDoc}.
*/
@Generated
@Override
public BasicClientBuilder retryOptions(RetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* {@inheritDoc}.
*/
@Generated
@Override
public BasicClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.");
pipelinePolicies.add(customPolicy);
return this;
}
/*
* The configuration store that is used during construction of the service client.
*/
@Generated
private Configuration configuration;
/**
* {@inheritDoc}.
*/
@Generated
@Override
public BasicClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/*
* The service endpoint
*/
@Generated
private String endpoint;
/**
* {@inheritDoc}.
*/
@Generated
@Override
public BasicClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/*
* Service version
*/
@Generated
private BasicServiceVersion serviceVersion;
/**
* Sets Service version.
*
* @param serviceVersion the serviceVersion value.
* @return the BasicClientBuilder.
*/
@Generated
public BasicClientBuilder serviceVersion(BasicServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/*
* The retry policy that will attempt to retry failed requests, if applicable.
*/
@Generated
private RetryPolicy retryPolicy;
/**
* Sets The retry policy that will attempt to retry failed requests, if applicable.
*
* @param retryPolicy the retryPolicy value.
* @return the BasicClientBuilder.
*/
@Generated
public BasicClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Builds an instance of BasicClientImpl with the provided parameters.
*
* @return an instance of BasicClientImpl.
*/
@Generated
private BasicClientImpl buildInnerClient() {
this.validateClient();
HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline();
String localEndpoint = (endpoint != null) ? endpoint : "http://localhost:3000";
BasicServiceVersion localServiceVersion
= (serviceVersion != null) ? serviceVersion : BasicServiceVersion.getLatest();
BasicClientImpl client = new BasicClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter(),
localEndpoint, localServiceVersion);
return client;
}
@Generated
private void validateClient() {
// This method is invoked from 'buildInnerClient'/'buildClient' method.
// Developer can customize this method, to validate that the necessary conditions are met for the new client.
}
@Generated
private HttpPipeline createHttpPipeline() {
Configuration buildConfiguration
= (configuration == null) ? Configuration.getGlobalConfiguration() : configuration;
HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions;
ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions;
List<HttpPipelinePolicy> policies = new ArrayList<>();
String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion");
String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions);
policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration));
policies.add(new RequestIdPolicy());
policies.add(new AddHeadersFromContextPolicy());
HttpHeaders headers = CoreUtils.createHttpHeadersFromClientOptions(localClientOptions);
if (headers != null) {
policies.add(new AddHeadersPolicy(headers));
}
this.pipelinePolicies.stream()
.filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL)
.forEach(p -> policies.add(p));
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy()));
policies.add(new AddDatePolicy());
this.pipelinePolicies.stream()
.filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY)
.forEach(p -> policies.add(p));
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(localHttpLogOptions));
HttpPipeline httpPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.clientOptions(localClientOptions)
.build();
return httpPipeline;
}
/**
* Builds an instance of BasicAsyncClient class.
*
* @return an instance of BasicAsyncClient.
*/
@Generated
public BasicAsyncClient buildAsyncClient() {
return new BasicAsyncClient(buildInnerClient());
}
/**
* Builds an instance of BasicClient class.
*
* @return an instance of BasicClient.
*/
@Generated
public BasicClient buildClient() {
return new BasicClient(buildInnerClient());
}
private static final ClientLogger LOGGER = new ClientLogger(BasicClientBuilder.class);
}

Просмотреть файл

@ -0,0 +1,40 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.core.basic;
import com.azure.core.util.ServiceVersion;
/**
* Service version of BasicClient.
*/
public enum BasicServiceVersion implements ServiceVersion {
/**
* Enum value 2022-12-01-preview.
*/
V2022_12_01_PREVIEW("2022-12-01-preview");
private final String version;
BasicServiceVersion(String version) {
this.version = version;
}
/**
* {@inheritDoc}
*/
@Override
public String getVersion() {
return this.version;
}
/**
* Gets the latest service version supported by this client library.
*
* @return The latest {@link BasicServiceVersion}.
*/
public static BasicServiceVersion getLatest() {
return V2022_12_01_PREVIEW;
}
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -0,0 +1,45 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.core.basic.implementation;
import com._specs_.azure.core.basic.models.User;
import com._specs_.azure.core.basic.models.UserOrder;
/**
* This is the Helper class to enable json merge patch serialization for a model.
*/
public class JsonMergePatchHelper {
private static UserAccessor userAccessor;
public interface UserAccessor {
User prepareModelForJsonMergePatch(User user, boolean jsonMergePatchEnabled);
boolean isJsonMergePatch(User user);
}
public static void setUserAccessor(UserAccessor accessor) {
userAccessor = accessor;
}
public static UserAccessor getUserAccessor() {
return userAccessor;
}
private static UserOrderAccessor userOrderAccessor;
public interface UserOrderAccessor {
UserOrder prepareModelForJsonMergePatch(UserOrder userOrder, boolean jsonMergePatchEnabled);
boolean isJsonMergePatch(UserOrder userOrder);
}
public static void setUserOrderAccessor(UserOrderAccessor accessor) {
userOrderAccessor = accessor;
}
public static UserOrderAccessor getUserOrderAccessor() {
return userOrderAccessor;
}
}

Просмотреть файл

@ -0,0 +1,11 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
/**
* <!-- start generated doc -->
* Package containing the implementations for Basic.
* Illustrates bodies templated with Azure Core.
* <!-- end generated doc -->
*/
package com._specs_.azure.core.basic.implementation;

Просмотреть файл

@ -0,0 +1,221 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.core.basic.models;
import com._specs_.azure.core.basic.implementation.JsonMergePatchHelper;
import com.azure.core.annotation.Fluent;
import com.azure.core.annotation.Generated;
import com.azure.json.JsonReader;
import com.azure.json.JsonSerializable;
import com.azure.json.JsonToken;
import com.azure.json.JsonWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Details about a user.
*/
@Fluent
public final class User implements JsonSerializable<User> {
/*
* The user's id.
*/
@Generated
private int id;
/*
* The user's name.
*/
@Generated
private String name;
/*
* The user's order list
*/
@Generated
private List<UserOrder> orders;
/*
* The entity tag for this resource.
*/
@Generated
private String etag;
/**
* Stores updated model property, the value is property name, not serialized name.
*/
@Generated
private final Set<String> updatedProperties = new HashSet<>();
@Generated
private boolean jsonMergePatch;
@Generated
private void serializeAsJsonMergePatch(boolean jsonMergePatch) {
this.jsonMergePatch = jsonMergePatch;
}
static {
JsonMergePatchHelper.setUserAccessor(new JsonMergePatchHelper.UserAccessor() {
@Override
public User prepareModelForJsonMergePatch(User model, boolean jsonMergePatchEnabled) {
model.serializeAsJsonMergePatch(jsonMergePatchEnabled);
return model;
}
@Override
public boolean isJsonMergePatch(User model) {
return model.jsonMergePatch;
}
});
}
/**
* Creates an instance of User class.
*/
@Generated
public User() {
}
/**
* Get the id property: The user's id.
*
* @return the id value.
*/
@Generated
public int getId() {
return this.id;
}
/**
* Get the name property: The user's name.
*
* @return the name value.
*/
@Generated
public String getName() {
return this.name;
}
/**
* Set the name property: The user's name.
* <p>Required when create the resource.</p>
*
* @param name the name value to set.
* @return the User object itself.
*/
@Generated
public User setName(String name) {
this.name = name;
this.updatedProperties.add("name");
return this;
}
/**
* Get the orders property: The user's order list.
*
* @return the orders value.
*/
@Generated
public List<UserOrder> getOrders() {
return this.orders;
}
/**
* Set the orders property: The user's order list.
*
* @param orders the orders value to set.
* @return the User object itself.
*/
@Generated
public User setOrders(List<UserOrder> orders) {
this.orders = orders;
this.updatedProperties.add("orders");
return this;
}
/**
* Get the etag property: The entity tag for this resource.
*
* @return the etag value.
*/
@Generated
public String getEtag() {
return this.etag;
}
/**
* {@inheritDoc}
*/
@Generated
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
if (jsonMergePatch) {
return toJsonMergePatch(jsonWriter);
} else {
jsonWriter.writeStartObject();
jsonWriter.writeStringField("name", this.name);
jsonWriter.writeArrayField("orders", this.orders, (writer, element) -> writer.writeJson(element));
return jsonWriter.writeEndObject();
}
}
@Generated
private JsonWriter toJsonMergePatch(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStartObject();
if (updatedProperties.contains("name")) {
if (this.name == null) {
jsonWriter.writeNullField("name");
} else {
jsonWriter.writeStringField("name", this.name);
}
}
if (updatedProperties.contains("orders")) {
if (this.orders == null) {
jsonWriter.writeNullField("orders");
} else {
jsonWriter.writeArrayField("orders", this.orders, (writer, element) -> writer.writeJson(element));
}
}
return jsonWriter.writeEndObject();
}
/**
* Reads an instance of User from the JsonReader.
*
* @param jsonReader The JsonReader being read.
* @return An instance of User if the JsonReader was pointing to an instance of it, or null if it was pointing to
* JSON null.
* @throws IllegalStateException If the deserialized JSON object was missing any required properties.
* @throws IOException If an error occurs while reading the User.
*/
@Generated
public static User fromJson(JsonReader jsonReader) throws IOException {
return jsonReader.readObject(reader -> {
User deserializedUser = new User();
while (reader.nextToken() != JsonToken.END_OBJECT) {
String fieldName = reader.getFieldName();
reader.nextToken();
if ("id".equals(fieldName)) {
deserializedUser.id = reader.getInt();
} else if ("etag".equals(fieldName)) {
deserializedUser.etag = reader.getString();
} else if ("name".equals(fieldName)) {
deserializedUser.name = reader.getString();
} else if ("orders".equals(fieldName)) {
List<UserOrder> orders = reader.readArray(reader1 -> UserOrder.fromJson(reader1));
deserializedUser.orders = orders;
} else {
reader.skipChildren();
}
}
return deserializedUser;
});
}
}

Просмотреть файл

@ -0,0 +1,198 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.core.basic.models;
import com._specs_.azure.core.basic.implementation.JsonMergePatchHelper;
import com.azure.core.annotation.Fluent;
import com.azure.core.annotation.Generated;
import com.azure.json.JsonReader;
import com.azure.json.JsonSerializable;
import com.azure.json.JsonToken;
import com.azure.json.JsonWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
/**
* UserOrder for testing list with expand.
*/
@Fluent
public final class UserOrder implements JsonSerializable<UserOrder> {
/*
* The user's id.
*/
@Generated
private int id;
/*
* The user's id.
*/
@Generated
private int userId;
/*
* The user's order detail
*/
@Generated
private String detail;
/**
* Stores updated model property, the value is property name, not serialized name.
*/
@Generated
private final Set<String> updatedProperties = new HashSet<>();
@Generated
private boolean jsonMergePatch;
@Generated
private void serializeAsJsonMergePatch(boolean jsonMergePatch) {
this.jsonMergePatch = jsonMergePatch;
}
static {
JsonMergePatchHelper.setUserOrderAccessor(new JsonMergePatchHelper.UserOrderAccessor() {
@Override
public UserOrder prepareModelForJsonMergePatch(UserOrder model, boolean jsonMergePatchEnabled) {
model.serializeAsJsonMergePatch(jsonMergePatchEnabled);
return model;
}
@Override
public boolean isJsonMergePatch(UserOrder model) {
return model.jsonMergePatch;
}
});
}
/**
* Creates an instance of UserOrder class.
*/
@Generated
public UserOrder() {
}
/**
* Get the id property: The user's id.
*
* @return the id value.
*/
@Generated
public int getId() {
return this.id;
}
/**
* Get the userId property: The user's id.
*
* @return the userId value.
*/
@Generated
public int getUserId() {
return this.userId;
}
/**
* Set the userId property: The user's id.
* <p>Required when create the resource.</p>
*
* @param userId the userId value to set.
* @return the UserOrder object itself.
*/
@Generated
public UserOrder setUserId(int userId) {
this.userId = userId;
this.updatedProperties.add("userId");
return this;
}
/**
* Get the detail property: The user's order detail.
*
* @return the detail value.
*/
@Generated
public String getDetail() {
return this.detail;
}
/**
* Set the detail property: The user's order detail.
* <p>Required when create the resource.</p>
*
* @param detail the detail value to set.
* @return the UserOrder object itself.
*/
@Generated
public UserOrder setDetail(String detail) {
this.detail = detail;
this.updatedProperties.add("detail");
return this;
}
/**
* {@inheritDoc}
*/
@Generated
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
if (jsonMergePatch) {
return toJsonMergePatch(jsonWriter);
} else {
jsonWriter.writeStartObject();
jsonWriter.writeIntField("userId", this.userId);
jsonWriter.writeStringField("detail", this.detail);
return jsonWriter.writeEndObject();
}
}
@Generated
private JsonWriter toJsonMergePatch(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStartObject();
if (updatedProperties.contains("userId")) {
jsonWriter.writeIntField("userId", this.userId);
}
if (updatedProperties.contains("detail")) {
if (this.detail == null) {
jsonWriter.writeNullField("detail");
} else {
jsonWriter.writeStringField("detail", this.detail);
}
}
return jsonWriter.writeEndObject();
}
/**
* Reads an instance of UserOrder from the JsonReader.
*
* @param jsonReader The JsonReader being read.
* @return An instance of UserOrder if the JsonReader was pointing to an instance of it, or null if it was pointing
* to JSON null.
* @throws IllegalStateException If the deserialized JSON object was missing any required properties.
* @throws IOException If an error occurs while reading the UserOrder.
*/
@Generated
public static UserOrder fromJson(JsonReader jsonReader) throws IOException {
return jsonReader.readObject(reader -> {
UserOrder deserializedUserOrder = new UserOrder();
while (reader.nextToken() != JsonToken.END_OBJECT) {
String fieldName = reader.getFieldName();
reader.nextToken();
if ("id".equals(fieldName)) {
deserializedUserOrder.id = reader.getInt();
} else if ("userId".equals(fieldName)) {
deserializedUserOrder.userId = reader.getInt();
} else if ("detail".equals(fieldName)) {
deserializedUserOrder.detail = reader.getString();
} else {
reader.skipChildren();
}
}
return deserializedUserOrder;
});
}
}

Просмотреть файл

@ -0,0 +1,11 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
/**
* <!-- start generated doc -->
* Package containing the data models for Basic.
* Illustrates bodies templated with Azure Core.
* <!-- end generated doc -->
*/
package com._specs_.azure.core.basic.models;

Просмотреть файл

@ -0,0 +1,11 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
/**
* <!-- start generated doc -->
* Package containing the classes for Basic.
* Illustrates bodies templated with Azure Core.
* <!-- end generated doc -->
*/
package com._specs_.azure.core.basic;

Просмотреть файл

@ -0,0 +1,104 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.core.lro.rpc;
import com._specs_.azure.core.lro.rpc.implementation.RpcClientImpl;
import com._specs_.azure.core.lro.rpc.models.GenerationOptions;
import com._specs_.azure.core.lro.rpc.models.GenerationResult;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.exception.ClientAuthenticationException;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.util.BinaryData;
import com.azure.core.util.polling.PollerFlux;
import com.azure.core.util.polling.PollOperationDetails;
/**
* Initializes a new instance of the asynchronous RpcClient type.
*/
@ServiceClient(builder = RpcClientBuilder.class, isAsync = true)
public final class RpcAsyncClient {
@Generated
private final RpcClientImpl serviceClient;
/**
* Initializes an instance of RpcAsyncClient class.
*
* @param serviceClient the service client implementation.
*/
@Generated
RpcAsyncClient(RpcClientImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* Generate data.
* <p><strong>Request Body Schema</strong></p>
*
* <pre>{@code
* {
* prompt: String (Required)
* }
* }</pre>
*
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* id: String (Required)
* status: String(NotStarted/Running/Succeeded/Failed/Canceled) (Required)
* error (Optional): {
* code: String (Required)
* message: String (Required)
* target: String (Optional)
* details (Optional): [
* (recursive schema, see above)
* ]
* }
* result (Optional): {
* data: String (Required)
* }
* }
* }</pre>
*
* @param body The body parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return the {@link PollerFlux} for polling of provides status details for long running operations.
*/
@Generated
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
public PollerFlux<BinaryData, BinaryData> beginLongRunningRpc(BinaryData body, RequestOptions requestOptions) {
return this.serviceClient.beginLongRunningRpcAsync(body, requestOptions);
}
/**
* Generate data.
*
* @param body The body parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the {@link PollerFlux} for polling of provides status details for long running operations.
*/
@Generated
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
public PollerFlux<PollOperationDetails, GenerationResult> beginLongRunningRpc(GenerationOptions body) {
// Generated convenience method for beginLongRunningRpcWithModel
RequestOptions requestOptions = new RequestOptions();
return serviceClient.beginLongRunningRpcWithModelAsync(BinaryData.fromObject(body), requestOptions);
}
}

Просмотреть файл

@ -0,0 +1,104 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) TypeSpec Code Generator.
package com._specs_.azure.core.lro.rpc;
import com._specs_.azure.core.lro.rpc.implementation.RpcClientImpl;
import com._specs_.azure.core.lro.rpc.models.GenerationOptions;
import com._specs_.azure.core.lro.rpc.models.GenerationResult;
import com.azure.core.annotation.Generated;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.exception.ClientAuthenticationException;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.util.BinaryData;
import com.azure.core.util.polling.PollOperationDetails;
import com.azure.core.util.polling.SyncPoller;
/**
* Initializes a new instance of the synchronous RpcClient type.
*/
@ServiceClient(builder = RpcClientBuilder.class)
public final class RpcClient {
@Generated
private final RpcClientImpl serviceClient;
/**
* Initializes an instance of RpcClient class.
*
* @param serviceClient the service client implementation.
*/
@Generated
RpcClient(RpcClientImpl serviceClient) {
this.serviceClient = serviceClient;
}
/**
* Generate data.
* <p><strong>Request Body Schema</strong></p>
*
* <pre>{@code
* {
* prompt: String (Required)
* }
* }</pre>
*
* <p><strong>Response Body Schema</strong></p>
*
* <pre>{@code
* {
* id: String (Required)
* status: String(NotStarted/Running/Succeeded/Failed/Canceled) (Required)
* error (Optional): {
* code: String (Required)
* message: String (Required)
* target: String (Optional)
* details (Optional): [
* (recursive schema, see above)
* ]
* }
* result (Optional): {
* data: String (Required)
* }
* }
* }</pre>
*
* @param body The body parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @return the {@link SyncPoller} for polling of provides status details for long running operations.
*/
@Generated
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
public SyncPoller<BinaryData, BinaryData> beginLongRunningRpc(BinaryData body, RequestOptions requestOptions) {
return this.serviceClient.beginLongRunningRpc(body, requestOptions);
}
/**
* Generate data.
*
* @param body The body parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
* @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404.
* @throws ResourceModifiedException thrown if the request is rejected by server on status code 409.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the {@link SyncPoller} for polling of provides status details for long running operations.
*/
@Generated
@ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
public SyncPoller<PollOperationDetails, GenerationResult> beginLongRunningRpc(GenerationOptions body) {
// Generated convenience method for beginLongRunningRpcWithModel
RequestOptions requestOptions = new RequestOptions();
return serviceClient.beginLongRunningRpcWithModel(BinaryData.fromObject(body), requestOptions);
}
}

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше