From 6dc0c12ffd13f940a39c12d56a07b4b531d1f7b6 Mon Sep 17 00:00:00 2001 From: Burke Davison <40617934+burkedavison@users.noreply.github.com> Date: Fri, 18 Aug 2023 21:40:02 +0000 Subject: [PATCH] chore: add linter (#187) * chore: add linter * ci: fix github actions syntax * chore: format * chore: update goldens --- .github/workflows/ci.yml | 40 +- third_party/docfx-doclet-143274/README.md | 9 +- .../intellij-java-google-style.xml | 598 ------------------ third_party/docfx-doclet-143274/pom.xml | 17 + .../java/com/microsoft/build/BuilderUtil.java | 306 ++++----- .../com/microsoft/build/ClassBuilder.java | 318 +++++----- .../main/java/com/microsoft/build/Lookup.java | 186 +++--- .../com/microsoft/build/LookupContext.java | 34 +- .../com/microsoft/build/PackageBuilder.java | 46 +- .../com/microsoft/build/ProjectBuilder.java | 64 +- .../com/microsoft/build/ReferenceBuilder.java | 501 ++++++++------- .../com/microsoft/build/YmlFilesBuilder.java | 184 +++--- .../com/microsoft/doclet/DocFxDoclet.java | 265 ++++---- .../com/microsoft/doclet/DocletRunner.java | 28 +- .../java/com/microsoft/lookup/BaseLookup.java | 542 ++++++++-------- .../microsoft/lookup/ClassItemsLookup.java | 365 ++++++----- .../com/microsoft/lookup/ClassLookup.java | 364 ++++++----- .../com/microsoft/lookup/PackageLookup.java | 81 ++- .../model/ExtendedMetadataFileItem.java | 214 +++---- .../com/microsoft/model/ExceptionItem.java | 24 +- .../main/java/com/microsoft/model/Guide.java | 26 +- .../java/com/microsoft/model/KindTitle.java | 22 +- .../com/microsoft/model/MetadataFile.java | 83 ++- .../com/microsoft/model/MetadataFileItem.java | 492 +++++++------- .../com/microsoft/model/MethodParameter.java | 40 +- .../com/microsoft/model/ProjectContents.java | 26 +- .../main/java/com/microsoft/model/Return.java | 51 +- .../com/microsoft/model/SpecViewModel.java | 109 ++-- .../main/java/com/microsoft/model/Status.java | 12 +- .../main/java/com/microsoft/model/Syntax.java | 61 +- .../java/com/microsoft/model/TocContents.java | 61 +- .../java/com/microsoft/model/TocFile.java | 63 +- .../java/com/microsoft/model/TocItem.java | 77 +-- .../java/com/microsoft/model/TocTypeMap.java | 34 +- .../com/microsoft/model/TypeParameter.java | 14 +- .../java/com/microsoft/model/YmlFile.java | 4 +- .../com/microsoft/util/CommentHelper.java | 130 ++-- .../java/com/microsoft/util/ElementUtil.java | 120 ++-- .../java/com/microsoft/util/FileUtil.java | 27 +- .../com/microsoft/util/OptionsFileUtil.java | 46 +- .../main/java/com/microsoft/util/Utils.java | 484 +++++++------- .../java/com/microsoft/util/YamlUtil.java | 55 +- .../com/microsoft/build/BuilderUtilTest.java | 189 +++--- .../com/microsoft/build/ClassBuilderTest.java | 92 +-- .../microsoft/build/LookupContextTest.java | 85 +-- .../java/com/microsoft/build/LookupTest.java | 139 ++-- .../microsoft/build/ReferenceBuilderTest.java | 179 +++--- .../microsoft/build/YmlFilesBuilderTest.java | 82 +-- .../com/microsoft/doclet/DocFxDocletTest.java | 90 +-- .../microsoft/doclet/DocletRunnerTest.java | 140 ++-- .../com/microsoft/lookup/BaseLookupTest.java | 524 ++++++++------- .../lookup/ClassItemsLookupTest.java | 587 ++++++++--------- .../com/microsoft/lookup/ClassLookupTest.java | 395 ++++++------ .../microsoft/lookup/PackageLookupTest.java | 89 ++- .../microsoft/model/MetadataFileItemTest.java | 290 ++++----- .../java/com/microsoft/model/StatusTest.java | 16 +- .../com/microsoft/model/TocContentsTest.java | 161 ++--- .../java/com/microsoft/model/TocFileTest.java | 40 +- .../com/microsoft/model/TocTypeMapTest.java | 29 +- .../samples/BasePartnerComponent.java | 62 +- .../samples/BasePartnerComponentString.java | 44 +- .../microsoft/samples/ExceptionHandler.java | 5 +- .../java/com/microsoft/samples/IPartner.java | 32 +- .../com/microsoft/samples/KeyValuePair.java | 27 +- .../test/java/com/microsoft/samples/Link.java | 70 +- .../com/microsoft/samples/Subpackage.java | 4 +- .../java/com/microsoft/samples/SuperHero.java | 190 +++--- .../AgreementDetailsCollectionOperations.java | 43 +- .../samples/agreements/AgreementMetaData.java | 94 ++- .../IAgreementDetailsCollection.java | 16 +- .../agreements/ResourceCollection.java | 7 +- .../samples/commentinheritance/Animal.java | 30 +- .../commentinheritance/Carnivorous.java | 22 +- .../samples/commentinheritance/Dog.java | 117 ++-- .../commentinheritance/Herbivorous.java | 26 +- .../samples/commentinheritance/Mammal.java | 11 +- .../commentinheritance/Omnivorous.java | 21 +- .../samples/commentinheritance/Organism.java | 6 +- .../commentinheritance/Viviparous.java | 12 +- .../com/microsoft/samples/google/BetaApi.java | 20 +- .../samples/google/ProductSearchSettings.java | 7 +- .../samples/google/RecognitionAudio.java | 75 ++- .../samples/google/SpeechClient.java | 8 +- .../samples/google/SpeechSettings.java | 5 +- .../samples/google/ValidationException.java | 11 +- .../samples/google/v1beta/SpeechClient.java | 6 +- .../google/v1p1alpha/SpeechClient.java | 12 +- .../com/microsoft/samples/offers/Offer.java | 55 +- .../SomeClassInExcludedPackage.java | 14 +- .../samples/subpackage/CustomException.java | 28 +- .../microsoft/samples/subpackage/Display.java | 8 +- .../samples/subpackage/InternalException.java | 6 +- .../microsoft/samples/subpackage/Person.java | 97 ++- .../samples/subpackage/SomeExcludedClass.java | 14 +- .../microsoft/samples/subpackage/Tuple.java | 39 +- .../samples/subpackage/package-info.java | 4 +- .../com/microsoft/util/ElementUtilTest.java | 155 +++-- .../java/com/microsoft/util/FileUtilTest.java | 87 ++- .../microsoft/util/OptionsFileUtilTest.java | 54 +- .../java/com/microsoft/util/UtilsTest.java | 169 ++--- .../java/com/microsoft/util/YamlUtilTest.java | 363 ++++++----- ...microsoft.samples.BasePartnerComponent.yml | 2 +- .../com.microsoft.samples.IPartner.yml | 2 +- .../com.microsoft.samples.SuperHero.yml | 6 +- ...t.samples.agreements.AgreementMetaData.yml | 2 +- ....samples.agreements.ResourceCollection.yml | 2 +- ...soft.samples.commentinheritance.Animal.yml | 2 +- ...crosoft.samples.commentinheritance.Dog.yml | 2 +- ...soft.samples.commentinheritance.Mammal.yml | 2 +- ....samples.commentinheritance.Omnivorous.yml | 2 +- .../com.microsoft.samples.google.BetaApi.yml | 2 +- ...oft.samples.google.ValidationException.yml | 2 +- ....samples.google.v1p1alpha.SpeechClient.yml | 2 +- ...m.microsoft.samples.subpackage.Display.yml | 2 +- ...om.microsoft.samples.subpackage.Person.yml | 2 +- 115 files changed, 5611 insertions(+), 5847 deletions(-) delete mode 100644 third_party/docfx-doclet-143274/intellij-java-google-style.xml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ae1b5e64..db7370f3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,48 +1,44 @@ -# This is a basic workflow to help you get started with Actions +name: ci -name: CI - -# Controls when the action will run. on: - # Triggers the workflow on push or pull request events but only for the main branch push: branches: [ main ] pull_request: branches: [ main ] - - # Allows you to run this workflow manually from the Actions tab workflow_dispatch: -# A workflow run is made up of one or more jobs that can run sequentially or in parallel +defaults: + run: + working-directory: ./third_party/docfx-doclet-143274 + jobs: - # This workflow contains a single job called "build" build: - # The type of runner that the job will run on runs-on: ubuntu-latest - - # Steps represent a sequence of tasks that will be executed as part of the job steps: - # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - uses: actions/checkout@v3 - uses: actions/setup-java@v3 with: java-version: 11 distribution: temurin - - name: build project - working-directory: ./third_party/docfx-doclet-143274 - run: mvn clean install -DskipTests + - run: mvn -B -ntp install -DskipTests + test: - # The type of runner that the job will run on runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-java@v3 + with: + java-version: 11 + distribution: temurin + - run: mvn -B -ntp test - # Steps represent a sequence of tasks that will be executed as part of the job + lint: + runs-on: ubuntu-latest steps: - # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - uses: actions/checkout@v3 - uses: actions/setup-java@v3 with: java-version: 11 distribution: temurin - - name: pass tests - working-directory: ./third_party/docfx-doclet-143274 - run: mvn clean test + - run: mvn --version + - run: mvn -B -ntp fmt:check diff --git a/third_party/docfx-doclet-143274/README.md b/third_party/docfx-doclet-143274/README.md index 4a97a0f4..774581b2 100644 --- a/third_party/docfx-doclet-143274/README.md +++ b/third_party/docfx-doclet-143274/README.md @@ -23,13 +23,18 @@ mvn package This will produce two JAR files that you can use - one with dependencies, and another one without. +To run the linter: +```bash +mvn fmt:format +``` + ## Usage ### With `maven-javadoc-plugin` When there is an existing java project where Maven is used as a build tool, one could add `maven-javadoc-plugin` to the root `pom.xml`: -```java +```xml org.apache.maven.plugins maven-javadoc-plugin @@ -121,7 +126,7 @@ You can take a look at an [example documentation generation script](https://gith ## Development -When making changes, it is important to ensure that you are using `DocletRunner` class - it is responsible for makeing the `javadoc` call and takes params from an external configuration file. +When making changes, it is important to ensure that you are using `DocletRunner` class - it is responsible for making the `javadoc` call and takes params from an external configuration file. To use it: diff --git a/third_party/docfx-doclet-143274/intellij-java-google-style.xml b/third_party/docfx-doclet-143274/intellij-java-google-style.xml deleted file mode 100644 index f3a6743e..00000000 --- a/third_party/docfx-doclet-143274/intellij-java-google-style.xml +++ /dev/null @@ -1,598 +0,0 @@ - - - - - - diff --git a/third_party/docfx-doclet-143274/pom.xml b/third_party/docfx-doclet-143274/pom.xml index 884abf10..25983b61 100644 --- a/third_party/docfx-doclet-143274/pom.xml +++ b/third_party/docfx-doclet-143274/pom.xml @@ -93,6 +93,23 @@ + + + com.coveo + fmt-maven-plugin + 2.13 + + + true + + + + com.google.googlejavaformat + google-java-format + 1.16.0 + + + diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/BuilderUtil.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/BuilderUtil.java index 46214575..4869b4ec 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/BuilderUtil.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/BuilderUtil.java @@ -20,175 +20,181 @@ import com.microsoft.model.MetadataFileItem; import com.microsoft.model.SpecViewModel; import com.microsoft.util.YamlUtil; -import org.apache.commons.lang3.RegExUtils; -import org.apache.commons.lang3.StringUtils; - -import javax.lang.model.element.Element; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; +import javax.lang.model.element.Element; +import org.apache.commons.lang3.RegExUtils; +import org.apache.commons.lang3.StringUtils; final class BuilderUtil { - private static final Pattern XREF_LINK_PATTERN = Pattern.compile(".*?"); - private static final Pattern XREF_LINK_CONTENT_PATTERN = Pattern.compile("(?<=.*?)"); - private static final Pattern XREF_LINK_RESOLVE_PATTERN = Pattern.compile("(?\\w+)\\#(?\\w+)(\\((?.*)\\))?"); - public final static String[] LANGS = {"java"}; - - static String populateUidValues(String text, LookupContext lookupContext) { - if (StringUtils.isBlank(text)) { - return text; - } - - Matcher linkMatcher = XREF_LINK_PATTERN.matcher(text); - while (linkMatcher.find()) { - String link = linkMatcher.group(); - Matcher linkContentMatcher = XREF_LINK_CONTENT_PATTERN.matcher(link); - if (!linkContentMatcher.find()) { - continue; - } - - String linkContent = linkContentMatcher.group(); - String uid = resolveUidFromLinkContent(linkContent, lookupContext); - String updatedLink = linkContentMatcher.replaceAll(uid); - text = StringUtils.replace(text, link, updatedLink); - } - return text; + private static final Pattern XREF_LINK_PATTERN = + Pattern.compile(".*?"); + private static final Pattern XREF_LINK_CONTENT_PATTERN = + Pattern.compile("(?<=.*?)"); + private static final Pattern XREF_LINK_RESOLVE_PATTERN = + Pattern.compile("(?\\w+)\\#(?\\w+)(\\((?.*)\\))?"); + public static final String[] LANGS = {"java"}; + + static String populateUidValues(String text, LookupContext lookupContext) { + if (StringUtils.isBlank(text)) { + return text; } - /** - * The linkContent could be in following format - * #memeber - * Class#member - * Class#method() - * Class#method(params) - */ - static String resolveUidFromLinkContent(String linkContent, LookupContext lookupContext) { - if (StringUtils.isBlank(linkContent)) { - return ""; - } - - linkContent = linkContent.trim(); - - // complete class name for class internal link - if (linkContent.startsWith("#")) { - String firstKey = lookupContext.getOwnerUid(); - linkContent = firstKey + linkContent; - } - - // fuzzy resolve, target for items from project external references - String fuzzyResolvedUid = resolveUidFromReference(linkContent, lookupContext); - - // exact resolve in lookupContext - linkContent = linkContent.replace("#", "."); - String exactResolveUid = resolveUidByLookup(linkContent, lookupContext); - return exactResolveUid.isEmpty() ? fuzzyResolvedUid : exactResolveUid; + Matcher linkMatcher = XREF_LINK_PATTERN.matcher(text); + while (linkMatcher.find()) { + String link = linkMatcher.group(); + Matcher linkContentMatcher = XREF_LINK_CONTENT_PATTERN.matcher(link); + if (!linkContentMatcher.find()) { + continue; + } + + String linkContent = linkContentMatcher.group(); + String uid = resolveUidFromLinkContent(linkContent, lookupContext); + String updatedLink = linkContentMatcher.replaceAll(uid); + text = StringUtils.replace(text, link, updatedLink); } - - static List splitUidWithGenericsIntoClassNames(String uid) { - uid = RegExUtils.removeAll(uid, "[>]+$"); - return Arrays.asList(StringUtils.split(uid, "<")); + return text; + } + + /** + * The linkContent could be in following format #memeber Class#member Class#method() + * Class#method(params) + */ + static String resolveUidFromLinkContent(String linkContent, LookupContext lookupContext) { + if (StringUtils.isBlank(linkContent)) { + return ""; } - static List replaceUidAndSplit(String uid) { - String retValue = RegExUtils.replaceAll(uid, "\\<", "//", "//>//"); - retValue = RegExUtils.replaceAll(retValue, ",", "//,//"); - retValue = RegExUtils.replaceAll(retValue, "\\[\\]", "//[]//"); - - return Arrays.asList(StringUtils.split(retValue, "//")); - } + linkContent = linkContent.trim(); - static List getJavaSpec(List references) { - List specList = new ArrayList<>(); - - Optional.ofNullable(references).ifPresent( - ref -> references.forEach( - uid -> { - if (uid.equalsIgnoreCase("<") - || uid.equalsIgnoreCase(">") - || uid.equalsIgnoreCase(",") - || uid.equalsIgnoreCase("[]")) - specList.add(new SpecViewModel(null, uid)); - else if (uid != "") - specList.add(new SpecViewModel(uid, uid)); - }) - ); - - return specList; + // complete class name for class internal link + if (linkContent.startsWith("#")) { + String firstKey = lookupContext.getOwnerUid(); + linkContent = firstKey + linkContent; } - static void populateUidValues(List packageMetadataFiles, List classMetadataFiles) { - Lookup lookup = new Lookup(packageMetadataFiles, classMetadataFiles); - - classMetadataFiles.forEach(classMetadataFile -> { - LookupContext lookupContext = lookup.buildContext(classMetadataFile); - - for (MetadataFileItem item : classMetadataFile.getItems()) { - item.setSummary(YamlUtil.cleanupHtml( - populateUidValues(item.getSummary(), lookupContext) - )); - - Optional.ofNullable(item.getSyntax()).ifPresent(syntax -> { - Optional.ofNullable(syntax.getParameters()).ifPresent( - methodParams -> methodParams.forEach( - param -> { - param.setDescription(populateUidValues(param.getDescription(), lookupContext)); - }) - ); - Optional.ofNullable(syntax.getReturnValue()).ifPresent(returnValue -> - returnValue.setReturnDescription( - populateUidValues(syntax.getReturnValue().getReturnDescription(), lookupContext) - ) - ); - } - ); - } + // fuzzy resolve, target for items from project external references + String fuzzyResolvedUid = resolveUidFromReference(linkContent, lookupContext); + + // exact resolve in lookupContext + linkContent = linkContent.replace("#", "."); + String exactResolveUid = resolveUidByLookup(linkContent, lookupContext); + return exactResolveUid.isEmpty() ? fuzzyResolvedUid : exactResolveUid; + } + + static List splitUidWithGenericsIntoClassNames(String uid) { + uid = RegExUtils.removeAll(uid, "[>]+$"); + return Arrays.asList(StringUtils.split(uid, "<")); + } + + static List replaceUidAndSplit(String uid) { + String retValue = RegExUtils.replaceAll(uid, "\\<", "//", "//>//"); + retValue = RegExUtils.replaceAll(retValue, ",", "//,//"); + retValue = RegExUtils.replaceAll(retValue, "\\[\\]", "//[]//"); + + return Arrays.asList(StringUtils.split(retValue, "//")); + } + + static List getJavaSpec(List references) { + List specList = new ArrayList<>(); + + Optional.ofNullable(references) + .ifPresent( + ref -> + references.forEach( + uid -> { + if (uid.equalsIgnoreCase("<") + || uid.equalsIgnoreCase(">") + || uid.equalsIgnoreCase(",") + || uid.equalsIgnoreCase("[]")) specList.add(new SpecViewModel(null, uid)); + else if (uid != "") specList.add(new SpecViewModel(uid, uid)); + })); + + return specList; + } + + static void populateUidValues( + List packageMetadataFiles, List classMetadataFiles) { + Lookup lookup = new Lookup(packageMetadataFiles, classMetadataFiles); + + classMetadataFiles.forEach( + classMetadataFile -> { + LookupContext lookupContext = lookup.buildContext(classMetadataFile); + + for (MetadataFileItem item : classMetadataFile.getItems()) { + item.setSummary( + YamlUtil.cleanupHtml(populateUidValues(item.getSummary(), lookupContext))); + + Optional.ofNullable(item.getSyntax()) + .ifPresent( + syntax -> { + Optional.ofNullable(syntax.getParameters()) + .ifPresent( + methodParams -> + methodParams.forEach( + param -> { + param.setDescription( + populateUidValues( + param.getDescription(), lookupContext)); + })); + Optional.ofNullable(syntax.getReturnValue()) + .ifPresent( + returnValue -> + returnValue.setReturnDescription( + populateUidValues( + syntax.getReturnValue().getReturnDescription(), + lookupContext))); + }); + } }); - } - - /** - * this method is used to do fuzzy resolve - * "*" will be added at the end of uid for method for xerf service resolve purpose - */ - static String resolveUidFromReference(String linkContent, LookupContext lookupContext) { - String uid = ""; - Matcher matcher = XREF_LINK_RESOLVE_PATTERN.matcher(linkContent); - - if (matcher.find()) { - String className = matcher.group("class"); - String memberName = matcher.group("member"); - uid = resolveUidByLookup(className, lookupContext); - if (!uid.isEmpty()) { - uid = uid.concat(".").concat(memberName); - - // linkContent targets a method - if (!StringUtils.isBlank(matcher.group(3))) { - uid = uid.concat("*"); - } - } - } - return uid; - } - - static String resolveUidByLookup(String signature, LookupContext lookupContext) { - if (StringUtils.isBlank(signature) || lookupContext == null) { - return ""; + } + + /** + * this method is used to do fuzzy resolve "*" will be added at the end of uid for method for xerf + * service resolve purpose + */ + static String resolveUidFromReference(String linkContent, LookupContext lookupContext) { + String uid = ""; + Matcher matcher = XREF_LINK_RESOLVE_PATTERN.matcher(linkContent); + + if (matcher.find()) { + String className = matcher.group("class"); + String memberName = matcher.group("member"); + uid = resolveUidByLookup(className, lookupContext); + if (!uid.isEmpty()) { + uid = uid.concat(".").concat(memberName); + + // linkContent targets a method + if (!StringUtils.isBlank(matcher.group(3))) { + uid = uid.concat("*"); } - return lookupContext.containsKey(signature) ? lookupContext.resolve(signature) : ""; + } } + return uid; + } - static void populateItemFields(MetadataFileItem item, BaseLookup lookup, T element) { - String name = lookup.extractName(element); - item.setName(name); - item.setNameWithType(lookup.extractNameWithType(element)); - item.setFullName(lookup.extractFullName(element)); - item.setType(lookup.extractType(element)); - item.setJavaType(lookup.extractJavaType(element)); - item.setSummary(lookup.extractSummary(element)); - item.setStatus(lookup.extractStatus(element)); - item.setContent(lookup.extractContent(element)); + static String resolveUidByLookup(String signature, LookupContext lookupContext) { + if (StringUtils.isBlank(signature) || lookupContext == null) { + return ""; } + return lookupContext.containsKey(signature) ? lookupContext.resolve(signature) : ""; + } + + static void populateItemFields( + MetadataFileItem item, BaseLookup lookup, T element) { + String name = lookup.extractName(element); + item.setName(name); + item.setNameWithType(lookup.extractNameWithType(element)); + item.setFullName(lookup.extractFullName(element)); + item.setType(lookup.extractType(element)); + item.setJavaType(lookup.extractJavaType(element)); + item.setSummary(lookup.extractSummary(element)); + item.setStatus(lookup.extractStatus(element)); + item.setContent(lookup.extractContent(element)); + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/ClassBuilder.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/ClassBuilder.java index efcd26ec..84e3d3eb 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/ClassBuilder.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/ClassBuilder.java @@ -15,175 +15,189 @@ */ package com.microsoft.build; +import static com.microsoft.build.BuilderUtil.LANGS; +import static com.microsoft.build.BuilderUtil.populateItemFields; + import com.microsoft.lookup.ClassItemsLookup; import com.microsoft.lookup.ClassLookup; import com.microsoft.model.MetadataFile; import com.microsoft.model.MetadataFileItem; -import com.microsoft.model.Status; import com.microsoft.model.TocItem; import com.microsoft.model.TocTypeMap; import com.microsoft.util.ElementUtil; import com.microsoft.util.Utils; - +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.util.ElementFilter; -import java.util.List; -import java.util.function.Function; -import java.util.stream.Collectors; - -import static com.microsoft.build.BuilderUtil.LANGS; -import static com.microsoft.build.BuilderUtil.populateItemFields; class ClassBuilder { - private ElementUtil elementUtil; - private ClassLookup classLookup; - private ClassItemsLookup classItemsLookup; - private String outputPath; - private ReferenceBuilder referenceBuilder; - - ClassBuilder(ElementUtil elementUtil, ClassLookup classLookup, ClassItemsLookup classItemsLookup, String outputPath, ReferenceBuilder referenceBuilder) { - this.elementUtil = elementUtil; - this.classLookup = classLookup; - this.classItemsLookup = classItemsLookup; - this.outputPath = outputPath; - this.referenceBuilder = referenceBuilder; - } - - void buildFilesForInnerClasses(Element element, TocTypeMap tocTypeMap, List container) { - for (TypeElement classElement : elementUtil.extractSortedElements(element)) { - String uid = classLookup.extractUid(classElement); - String name = classLookup.extractTocName(classElement); - String status = classLookup.extractStatus(classElement); - - if (tocTypeMap.get(classElement.getKind().name()) != null) { - if (classElement.getKind().name().equals(ElementKind.CLASS.name()) && name.contains("Exception")) { - tocTypeMap.get("EXCEPTION").add(new TocItem(uid, name, status)); - } else { - tocTypeMap.get(classElement.getKind().name()).add(new TocItem(uid, name, status)); - } - } else { - tocTypeMap.get(ElementKind.CLASS.name()).add(new TocItem(uid, name, status)); - } - - container.add(buildClassYmlFile(classElement)); - buildFilesForInnerClasses(classElement, tocTypeMap, container); - } - } - - private MetadataFile buildClassYmlFile(TypeElement classElement) { - String fileName = classLookup.extractHref(classElement); - MetadataFile classMetadataFile = new MetadataFile(outputPath, fileName); - addClassInfo(classElement, classMetadataFile); - addConstructorsInfo(classElement, classMetadataFile); - addMethodsInfo(classElement, classMetadataFile); - addFieldsInfo(classElement, classMetadataFile); - referenceBuilder.addReferencesInfo(classElement, classMetadataFile); - applyPostProcessing(classMetadataFile); - return classMetadataFile; - } - - private void addClassInfo(TypeElement classElement, MetadataFile classMetadataFile) { - MetadataFileItem classItem = new MetadataFileItem(LANGS, classLookup.extractUid(classElement)); - classItem.setId(classLookup.extractId(classElement)); - classItem.setParent(classLookup.extractParent(classElement)); - addChildren(classElement, classItem.getChildren()); - populateItemFields(classItem, classLookup, classElement); - classItem.setPackageName(classLookup.extractPackageName(classElement)); - classItem.setTypeParameters(classLookup.extractTypeParameters(classElement)); - classItem.setInheritance(classLookup.extractSuperclass(classElement)); - classItem.setInterfaces(classLookup.extractInterfaces(classElement)); - classItem.setInheritedMethods(classLookup.extractInheritedMethods(classElement)); - classItem.setSummary(classLookup.extractSummary(classElement)); - classItem.setStatus(classLookup.extractStatus(classElement)); - classMetadataFile.getItems().add(classItem); - } - - void addConstructorsInfo(TypeElement classElement, MetadataFile classMetadataFile) { - for (ExecutableElement constructorElement : ElementFilter.constructorsIn(elementUtil.getEnclosedElements(classElement))) { - MetadataFileItem constructorItem = buildMetadataFileItem(constructorElement); - constructorItem.setOverload(classItemsLookup.extractOverload(constructorElement)); - constructorItem.setContent(classItemsLookup.extractConstructorContent(constructorElement)); - constructorItem.setParameters(classItemsLookup.extractParameters(constructorElement)); - classMetadataFile.getItems().add(constructorItem); - - referenceBuilder.addParameterReferences(constructorItem, classMetadataFile); - referenceBuilder.addOverloadReferences(constructorItem, classMetadataFile); + private ElementUtil elementUtil; + private ClassLookup classLookup; + private ClassItemsLookup classItemsLookup; + private String outputPath; + private ReferenceBuilder referenceBuilder; + + ClassBuilder( + ElementUtil elementUtil, + ClassLookup classLookup, + ClassItemsLookup classItemsLookup, + String outputPath, + ReferenceBuilder referenceBuilder) { + this.elementUtil = elementUtil; + this.classLookup = classLookup; + this.classItemsLookup = classItemsLookup; + this.outputPath = outputPath; + this.referenceBuilder = referenceBuilder; + } + + void buildFilesForInnerClasses( + Element element, TocTypeMap tocTypeMap, List container) { + for (TypeElement classElement : elementUtil.extractSortedElements(element)) { + String uid = classLookup.extractUid(classElement); + String name = classLookup.extractTocName(classElement); + String status = classLookup.extractStatus(classElement); + + if (tocTypeMap.get(classElement.getKind().name()) != null) { + if (classElement.getKind().name().equals(ElementKind.CLASS.name()) + && name.contains("Exception")) { + tocTypeMap.get("EXCEPTION").add(new TocItem(uid, name, status)); + } else { + tocTypeMap.get(classElement.getKind().name()).add(new TocItem(uid, name, status)); } - } - - private void addMethodsInfo(TypeElement classElement, MetadataFile classMetadataFile) { - ElementFilter.methodsIn(elementUtil.getEnclosedElements(classElement)).stream() - .filter(methodElement -> !Utils.isPrivateOrPackagePrivate(methodElement)) - .forEach(methodElement -> { - MetadataFileItem methodItem = buildMetadataFileItem(methodElement); - methodItem.setOverload(classItemsLookup.extractOverload(methodElement)); - methodItem.setContent(classItemsLookup.extractMethodContent(methodElement)); - methodItem.setExceptions(classItemsLookup.extractExceptions(methodElement)); - methodItem.setParameters(classItemsLookup.extractParameters(methodElement)); - methodItem.setReturn(classItemsLookup.extractReturn(methodElement)); - methodItem.setOverridden(classItemsLookup.extractOverridden(methodElement)); - - classMetadataFile.getItems().add(methodItem); - referenceBuilder.addExceptionReferences(methodItem, classMetadataFile); - referenceBuilder.addParameterReferences(methodItem, classMetadataFile); - referenceBuilder.addReturnReferences(methodItem, classMetadataFile); - referenceBuilder.addOverloadReferences(methodItem, classMetadataFile); - }); - } - - private void addFieldsInfo(TypeElement classElement, MetadataFile classMetadataFile) { - ElementFilter.fieldsIn(elementUtil.getEnclosedElements(classElement)).stream() - .filter(fieldElement -> !Utils.isPrivateOrPackagePrivate(fieldElement)) - .forEach(fieldElement -> { - MetadataFileItem fieldItem = buildMetadataFileItem(fieldElement); - fieldItem.setContent(classItemsLookup.extractFieldContent(fieldElement)); - fieldItem.setReturn(classItemsLookup.extractReturn(fieldElement)); - classMetadataFile.getItems().add(fieldItem); - referenceBuilder.addReturnReferences(fieldItem, classMetadataFile); - }); - } - - private void applyPostProcessing(MetadataFile classMetadataFile) { - referenceBuilder.expandComplexGenericsInReferences(classMetadataFile); - } - - private MetadataFileItem buildMetadataFileItem(Element element) { - return new MetadataFileItem(LANGS, classItemsLookup.extractUid(element)) {{ - String name = classItemsLookup.extractName(element); - setId(classItemsLookup.extractId(element)); - setParent(classItemsLookup.extractParent(element)); - setName(name); - setNameWithType(classItemsLookup.extractNameWithType(element)); - setFullName(classItemsLookup.extractFullName(element)); - setType(classItemsLookup.extractType(element)); - setJavaType(classItemsLookup.extractJavaType(element)); - setPackageName(classItemsLookup.extractPackageName(element)); - setSummary(classItemsLookup.extractSummary(element)); - setStatus(classItemsLookup.extractStatus(element)); - }}; - } + } else { + tocTypeMap.get(ElementKind.CLASS.name()).add(new TocItem(uid, name, status)); + } - private void addChildren(TypeElement classElement, List children) { - collect(classElement, children, ElementFilter::constructorsIn, classItemsLookup::extractUid); - collect(classElement, children, ElementFilter::methodsIn, classItemsLookup::extractUid); - collect(classElement, children, ElementFilter::fieldsIn, classItemsLookup::extractUid); - collect(classElement, children, ElementFilter::typesIn, String::valueOf); + container.add(buildClassYmlFile(classElement)); + buildFilesForInnerClasses(classElement, tocTypeMap, container); } - - private void collect(TypeElement classElement, List children, - Function, List> selectFunc, - Function mapFunc) { - - List elements = selectFunc.apply(elementUtil.getEnclosedElements(classElement)); - children.addAll(filterPrivateElements(elements).stream() - .map(mapFunc).collect(Collectors.toList())); - } - - private List filterPrivateElements(List elements) { - return elements.stream() - .filter(element -> !Utils.isPrivateOrPackagePrivate(element)).collect(Collectors.toList()); + } + + private MetadataFile buildClassYmlFile(TypeElement classElement) { + String fileName = classLookup.extractHref(classElement); + MetadataFile classMetadataFile = new MetadataFile(outputPath, fileName); + addClassInfo(classElement, classMetadataFile); + addConstructorsInfo(classElement, classMetadataFile); + addMethodsInfo(classElement, classMetadataFile); + addFieldsInfo(classElement, classMetadataFile); + referenceBuilder.addReferencesInfo(classElement, classMetadataFile); + applyPostProcessing(classMetadataFile); + return classMetadataFile; + } + + private void addClassInfo(TypeElement classElement, MetadataFile classMetadataFile) { + MetadataFileItem classItem = new MetadataFileItem(LANGS, classLookup.extractUid(classElement)); + classItem.setId(classLookup.extractId(classElement)); + classItem.setParent(classLookup.extractParent(classElement)); + addChildren(classElement, classItem.getChildren()); + populateItemFields(classItem, classLookup, classElement); + classItem.setPackageName(classLookup.extractPackageName(classElement)); + classItem.setTypeParameters(classLookup.extractTypeParameters(classElement)); + classItem.setInheritance(classLookup.extractSuperclass(classElement)); + classItem.setInterfaces(classLookup.extractInterfaces(classElement)); + classItem.setInheritedMethods(classLookup.extractInheritedMethods(classElement)); + classItem.setSummary(classLookup.extractSummary(classElement)); + classItem.setStatus(classLookup.extractStatus(classElement)); + classMetadataFile.getItems().add(classItem); + } + + void addConstructorsInfo(TypeElement classElement, MetadataFile classMetadataFile) { + for (ExecutableElement constructorElement : + ElementFilter.constructorsIn(elementUtil.getEnclosedElements(classElement))) { + MetadataFileItem constructorItem = buildMetadataFileItem(constructorElement); + constructorItem.setOverload(classItemsLookup.extractOverload(constructorElement)); + constructorItem.setContent(classItemsLookup.extractConstructorContent(constructorElement)); + constructorItem.setParameters(classItemsLookup.extractParameters(constructorElement)); + classMetadataFile.getItems().add(constructorItem); + + referenceBuilder.addParameterReferences(constructorItem, classMetadataFile); + referenceBuilder.addOverloadReferences(constructorItem, classMetadataFile); } + } + + private void addMethodsInfo(TypeElement classElement, MetadataFile classMetadataFile) { + ElementFilter.methodsIn(elementUtil.getEnclosedElements(classElement)).stream() + .filter(methodElement -> !Utils.isPrivateOrPackagePrivate(methodElement)) + .forEach( + methodElement -> { + MetadataFileItem methodItem = buildMetadataFileItem(methodElement); + methodItem.setOverload(classItemsLookup.extractOverload(methodElement)); + methodItem.setContent(classItemsLookup.extractMethodContent(methodElement)); + methodItem.setExceptions(classItemsLookup.extractExceptions(methodElement)); + methodItem.setParameters(classItemsLookup.extractParameters(methodElement)); + methodItem.setReturn(classItemsLookup.extractReturn(methodElement)); + methodItem.setOverridden(classItemsLookup.extractOverridden(methodElement)); + + classMetadataFile.getItems().add(methodItem); + referenceBuilder.addExceptionReferences(methodItem, classMetadataFile); + referenceBuilder.addParameterReferences(methodItem, classMetadataFile); + referenceBuilder.addReturnReferences(methodItem, classMetadataFile); + referenceBuilder.addOverloadReferences(methodItem, classMetadataFile); + }); + } + + private void addFieldsInfo(TypeElement classElement, MetadataFile classMetadataFile) { + ElementFilter.fieldsIn(elementUtil.getEnclosedElements(classElement)).stream() + .filter(fieldElement -> !Utils.isPrivateOrPackagePrivate(fieldElement)) + .forEach( + fieldElement -> { + MetadataFileItem fieldItem = buildMetadataFileItem(fieldElement); + fieldItem.setContent(classItemsLookup.extractFieldContent(fieldElement)); + fieldItem.setReturn(classItemsLookup.extractReturn(fieldElement)); + classMetadataFile.getItems().add(fieldItem); + referenceBuilder.addReturnReferences(fieldItem, classMetadataFile); + }); + } + + private void applyPostProcessing(MetadataFile classMetadataFile) { + referenceBuilder.expandComplexGenericsInReferences(classMetadataFile); + } + + private MetadataFileItem buildMetadataFileItem(Element element) { + return new MetadataFileItem(LANGS, classItemsLookup.extractUid(element)) { + { + String name = classItemsLookup.extractName(element); + setId(classItemsLookup.extractId(element)); + setParent(classItemsLookup.extractParent(element)); + setName(name); + setNameWithType(classItemsLookup.extractNameWithType(element)); + setFullName(classItemsLookup.extractFullName(element)); + setType(classItemsLookup.extractType(element)); + setJavaType(classItemsLookup.extractJavaType(element)); + setPackageName(classItemsLookup.extractPackageName(element)); + setSummary(classItemsLookup.extractSummary(element)); + setStatus(classItemsLookup.extractStatus(element)); + } + }; + } + + private void addChildren(TypeElement classElement, List children) { + collect(classElement, children, ElementFilter::constructorsIn, classItemsLookup::extractUid); + collect(classElement, children, ElementFilter::methodsIn, classItemsLookup::extractUid); + collect(classElement, children, ElementFilter::fieldsIn, classItemsLookup::extractUid); + collect(classElement, children, ElementFilter::typesIn, String::valueOf); + } + + private void collect( + TypeElement classElement, + List children, + Function, List> selectFunc, + Function mapFunc) { + + List elements = + selectFunc.apply(elementUtil.getEnclosedElements(classElement)); + children.addAll( + filterPrivateElements(elements).stream().map(mapFunc).collect(Collectors.toList())); + } + + private List filterPrivateElements(List elements) { + return elements.stream() + .filter(element -> !Utils.isPrivateOrPackagePrivate(element)) + .collect(Collectors.toList()); + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/Lookup.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/Lookup.java index df74ebb1..1ffc7dd0 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/Lookup.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/Lookup.java @@ -1,102 +1,126 @@ package com.microsoft.build; -import com.microsoft.model.MetadataFile; +import static org.apache.commons.lang3.RegExUtils.removeAll; +import static org.apache.commons.lang3.RegExUtils.replaceAll; +import com.microsoft.model.MetadataFile; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import static org.apache.commons.lang3.RegExUtils.removeAll; -import static org.apache.commons.lang3.RegExUtils.replaceAll; - public class Lookup { - private static final int INITIAL_CAPACITY = 10000; - private final Map globalLookup; - private final Map> localLookupByFileName; + private static final int INITIAL_CAPACITY = 10000; + private final Map globalLookup; + private final Map> localLookupByFileName; - private final String UID_PACKAGE_NAME_REGEXP = "^.*?\\.(?=[A-Z].*)"; - private final String PARAM_PACKAGE_NAME_REGEXP = "(?<=[\\( ]).*?(?=[A-Z].*)"; - private final String METHOD_PARAMS_REGEXP = "\\s[^\\s]+?(?=[,)])"; + private final String UID_PACKAGE_NAME_REGEXP = "^.*?\\.(?=[A-Z].*)"; + private final String PARAM_PACKAGE_NAME_REGEXP = "(?<=[\\( ]).*?(?=[A-Z].*)"; + private final String METHOD_PARAMS_REGEXP = "\\s[^\\s]+?(?=[,)])"; - public Lookup(List packageMetadataFiles, List classMetadataFiles) { - this.globalLookup = new HashMap<>(INITIAL_CAPACITY); - this.localLookupByFileName = new HashMap<>(INITIAL_CAPACITY); - consume(packageMetadataFiles); - consume(classMetadataFiles); - } + public Lookup(List packageMetadataFiles, List classMetadataFiles) { + this.globalLookup = new HashMap<>(INITIAL_CAPACITY); + this.localLookupByFileName = new HashMap<>(INITIAL_CAPACITY); + consume(packageMetadataFiles); + consume(classMetadataFiles); + } - public LookupContext buildContext(MetadataFile metadataFile) { - Map localLookup = localLookupByFileName.get(metadataFile.getFileNameWithPath()); - return new LookupContext(globalLookup, localLookup); - } + public LookupContext buildContext(MetadataFile metadataFile) { + Map localLookup = localLookupByFileName.get(metadataFile.getFileNameWithPath()); + return new LookupContext(globalLookup, localLookup); + } - /** - * For each such item from items and references of metadata file: - *
-     * - uid: "com.microsoft.samples.subpackage.Person.setFirstName(java.lang.String, boolean)"
-     *   nameWithType: "Person.setFirstName(String firstName, boolean flag)"
-     *   ...
-     * 
- * add several key-value pairs to lookup where keys are: - *
    - *
  • Name with type without generics:
    Person.setFirstName(String firstName, boolean flag)
  • - *
  • Uid as is:
    com.microsoft.samples.subpackage.Person.setFirstName(java.lang.String, boolean)
  • - *
  • Uid with param types without package:
    com.microsoft.samples.subpackage.Person.setFirstName(String, - * boolean)
  • - *
  • Uid without package:
    Person.setFirstName(java.lang.String, boolean)
  • - *
  • Name with type without generics and param names:
    Person.setFirstName(String, boolean)
  • - *
  • Name with type as is:
    Person.setFirstName(String, boolean)
  • - *
- * and value equals to uid:
com.microsoft.samples.subpackage.Person.setFirstName(java.lang.String) - */ - private void consume(List metadataFiles) { - metadataFiles.forEach(file -> { - /** - * It's important to use LinkedHashMap here, to put item related with owner class on first place. - * Logic of {@link YmlFilesBuilder#resolveUidByLookup} based on this for case when @link starts from '#' - */ - Map map = new LinkedHashMap<>(); - Map specForJavaMap = new LinkedHashMap<>(); + /** + * For each such item from items and references of metadata file: + * + *
+   * - uid: "com.microsoft.samples.subpackage.Person.setFirstName(java.lang.String, boolean)"
+   *   nameWithType: "Person.setFirstName(String firstName, boolean flag)"
+   *   ...
+   * 
+ * + * add several key-value pairs to lookup where keys are: + * + *
    + *
  • Name with type without generics:
    + * Person.setFirstName(String firstName, boolean flag) + *
  • Uid as is:
    + * com.microsoft.samples.subpackage.Person.setFirstName(java.lang.String, boolean) + *
  • Uid with param types without package:
    + * com.microsoft.samples.subpackage.Person.setFirstName(String, boolean) + *
  • Uid without package:
    + * Person.setFirstName(java.lang.String, boolean) + *
  • Name with type without generics and param names:
    + * Person.setFirstName(String, boolean) + *
  • Name with type as is:
    + * Person.setFirstName(String, boolean) + *
+ * + * and value equals to uid:
+ * com.microsoft.samples.subpackage.Person.setFirstName(java.lang.String) + */ + private void consume(List metadataFiles) { + metadataFiles.forEach( + file -> { + /** + * It's important to use LinkedHashMap here, to put item related with owner class on first + * place. Logic of {@link YmlFilesBuilder#resolveUidByLookup} based on this for case + * when @link starts from '#' + */ + Map map = new LinkedHashMap<>(); + Map specForJavaMap = new LinkedHashMap<>(); - file.getItems().forEach(item -> { - String uid = item.getUid(); - String nameWithType = item.getNameWithType(); - String nameWithTypeWithoutGenerics = removeAll(nameWithType, "<.*?>"); + file.getItems() + .forEach( + item -> { + String uid = item.getUid(); + String nameWithType = item.getNameWithType(); + String nameWithTypeWithoutGenerics = removeAll(nameWithType, "<.*?>"); - map.put(nameWithTypeWithoutGenerics, uid); // This item should go first - map.put(uid, uid); - map.put(removeAll(uid, PARAM_PACKAGE_NAME_REGEXP), uid); - map.put(removeAll(uid, UID_PACKAGE_NAME_REGEXP), uid); - map.put(removeAll(nameWithTypeWithoutGenerics, METHOD_PARAMS_REGEXP), uid); - map.put(removeAll(nameWithType, METHOD_PARAMS_REGEXP), uid); + map.put(nameWithTypeWithoutGenerics, uid); // This item should go first + map.put(uid, uid); + map.put(removeAll(uid, PARAM_PACKAGE_NAME_REGEXP), uid); + map.put(removeAll(uid, UID_PACKAGE_NAME_REGEXP), uid); + map.put(removeAll(nameWithTypeWithoutGenerics, METHOD_PARAMS_REGEXP), uid); + map.put(removeAll(nameWithType, METHOD_PARAMS_REGEXP), uid); - map.put(replaceAll(uid, ",", ", "), uid); - map.put(replaceAll(removeAll(uid, PARAM_PACKAGE_NAME_REGEXP), ",", ", "), uid); - map.put(replaceAll(removeAll(uid, UID_PACKAGE_NAME_REGEXP), ",", ", "), uid); - map.put(replaceAll(removeAll(nameWithTypeWithoutGenerics, METHOD_PARAMS_REGEXP), ", ", ","), uid); - }); + map.put(replaceAll(uid, ",", ", "), uid); + map.put(replaceAll(removeAll(uid, PARAM_PACKAGE_NAME_REGEXP), ",", ", "), uid); + map.put(replaceAll(removeAll(uid, UID_PACKAGE_NAME_REGEXP), ",", ", "), uid); + map.put( + replaceAll( + removeAll(nameWithTypeWithoutGenerics, METHOD_PARAMS_REGEXP), + ", ", + ","), + uid); + }); - file.getReferences().forEach(item -> { - map.put(item.getUid(), item.getUid()); + file.getReferences() + .forEach( + item -> { + map.put(item.getUid(), item.getUid()); - // complex types are recorded in "specForJava" as arrayList of items, thus it has no "NameWithType" - // thus we need to get every reference item from specForJava, and add to localLookup - if (item.getNameWithType() == null || item.getNameWithType().isEmpty()) { - item.getSpecForJava().forEach(spec -> { - specForJavaMap.put(spec.getName(), spec.getUid()); - specForJavaMap.put(spec.getFullName(), spec.getUid()); - }); - } else { - map.put(item.getNameWithType(), item.getUid()); - } - }); + // complex types are recorded in "specForJava" as arrayList of items, thus it + // has no "NameWithType" + // thus we need to get every reference item from specForJava, and add to + // localLookup + if (item.getNameWithType() == null || item.getNameWithType().isEmpty()) { + item.getSpecForJava() + .forEach( + spec -> { + specForJavaMap.put(spec.getName(), spec.getUid()); + specForJavaMap.put(spec.getFullName(), spec.getUid()); + }); + } else { + map.put(item.getNameWithType(), item.getUid()); + } + }); - // to avoid conflict, the items from specForJava should only add to localLookup - globalLookup.putAll(map); - map.putAll(specForJavaMap); - localLookupByFileName.put(file.getFileNameWithPath(), map); + // to avoid conflict, the items from specForJava should only add to localLookup + globalLookup.putAll(map); + map.putAll(specForJavaMap); + localLookupByFileName.put(file.getFileNameWithPath(), map); }); - } -} \ No newline at end of file + } +} diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/LookupContext.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/LookupContext.java index eee61c22..1ddc8f74 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/LookupContext.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/LookupContext.java @@ -4,26 +4,26 @@ public class LookupContext { - private final Map globalLookup; - private final Map localLookup; + private final Map globalLookup; + private final Map localLookup; - public LookupContext(Map globalLookup, Map localLookup) { - this.globalLookup = globalLookup; - this.localLookup = localLookup; - } + public LookupContext(Map globalLookup, Map localLookup) { + this.globalLookup = globalLookup; + this.localLookup = localLookup; + } - public String resolve(String key) { - if (localLookup.containsKey(key)) { - return localLookup.get(key); - } - return globalLookup.get(key); + public String resolve(String key) { + if (localLookup.containsKey(key)) { + return localLookup.get(key); } + return globalLookup.get(key); + } - public String getOwnerUid() { - return localLookup.keySet().iterator().next(); - } + public String getOwnerUid() { + return localLookup.keySet().iterator().next(); + } - public boolean containsKey(String key) { - return localLookup.containsKey(key) || globalLookup.containsKey(key); - } + public boolean containsKey(String key) { + return localLookup.containsKey(key) || globalLookup.containsKey(key); + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/PackageBuilder.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/PackageBuilder.java index 42228bbd..435de9e6 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/PackageBuilder.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/PackageBuilder.java @@ -15,34 +15,36 @@ */ package com.microsoft.build; +import static com.microsoft.build.BuilderUtil.LANGS; +import static com.microsoft.build.BuilderUtil.populateItemFields; + import com.microsoft.lookup.PackageLookup; import com.microsoft.model.MetadataFile; import com.microsoft.model.MetadataFileItem; - import javax.lang.model.element.PackageElement; -import static com.microsoft.build.BuilderUtil.LANGS; -import static com.microsoft.build.BuilderUtil.populateItemFields; - class PackageBuilder { - private final PackageLookup packageLookup; - private final String outputPath; - private final ReferenceBuilder referenceBuilder; + private final PackageLookup packageLookup; + private final String outputPath; + private final ReferenceBuilder referenceBuilder; - PackageBuilder(PackageLookup packageLookup, String outputPath, ReferenceBuilder referenceBuilder) { - this.packageLookup = packageLookup; - this.outputPath = outputPath; - this.referenceBuilder = referenceBuilder; - } + PackageBuilder( + PackageLookup packageLookup, String outputPath, ReferenceBuilder referenceBuilder) { + this.packageLookup = packageLookup; + this.outputPath = outputPath; + this.referenceBuilder = referenceBuilder; + } - MetadataFile buildPackageMetadataFile(PackageElement packageElement) { - String fileName = packageLookup.extractHref(packageElement); - MetadataFile packageMetadataFile = new MetadataFile(outputPath, fileName); - MetadataFileItem packageItem = new MetadataFileItem(LANGS, packageLookup.extractUid(packageElement)); - packageItem.setId(packageLookup.extractId(packageElement)); - referenceBuilder.addChildrenReferences(packageElement, packageItem.getChildren(), packageMetadataFile.getReferences()); - populateItemFields(packageItem, packageLookup, packageElement); - packageMetadataFile.getItems().add(packageItem); - return packageMetadataFile; - } + MetadataFile buildPackageMetadataFile(PackageElement packageElement) { + String fileName = packageLookup.extractHref(packageElement); + MetadataFile packageMetadataFile = new MetadataFile(outputPath, fileName); + MetadataFileItem packageItem = + new MetadataFileItem(LANGS, packageLookup.extractUid(packageElement)); + packageItem.setId(packageLookup.extractId(packageElement)); + referenceBuilder.addChildrenReferences( + packageElement, packageItem.getChildren(), packageMetadataFile.getReferences()); + populateItemFields(packageItem, packageLookup, packageElement); + packageMetadataFile.getItems().add(packageItem); + return packageMetadataFile; + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/ProjectBuilder.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/ProjectBuilder.java index f51f95d9..b43b1783 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/ProjectBuilder.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/ProjectBuilder.java @@ -15,41 +15,43 @@ */ package com.microsoft.build; +import static com.microsoft.build.BuilderUtil.LANGS; + import com.microsoft.model.MetadataFile; import com.microsoft.model.MetadataFileItem; - import java.util.ArrayList; import java.util.List; -import static com.microsoft.build.BuilderUtil.LANGS; - class ProjectBuilder { - private final String projectName; - - ProjectBuilder(String projectName) { - this.projectName = projectName; - } - - void buildProjectMetadataFile(List packageItems, MetadataFile projectMetadataFile) { - MetadataFileItem projectItem = new MetadataFileItem(LANGS, projectName); - projectItem.setNameWithType(projectName); - projectItem.setFullName(projectName); - projectItem.setType("Namespace"); - projectItem.setJavaType("overview"); - - List children = new ArrayList<>(); - List references = new ArrayList<>(); - packageItems.stream().forEach(i -> { - children.add(i.getUid()); - MetadataFileItem refItem = new MetadataFileItem(i.getUid()); - refItem.setName(i.getName()); - refItem.setNameWithType(i.getNameWithType()); - refItem.setFullName(i.getFullName()); - references.add(refItem); - }); - - projectItem.getChildren().addAll(children); - projectMetadataFile.getReferences().addAll(references); - projectMetadataFile.getItems().add(projectItem); - } + private final String projectName; + + ProjectBuilder(String projectName) { + this.projectName = projectName; + } + + void buildProjectMetadataFile( + List packageItems, MetadataFile projectMetadataFile) { + MetadataFileItem projectItem = new MetadataFileItem(LANGS, projectName); + projectItem.setNameWithType(projectName); + projectItem.setFullName(projectName); + projectItem.setType("Namespace"); + projectItem.setJavaType("overview"); + + List children = new ArrayList<>(); + List references = new ArrayList<>(); + packageItems.stream() + .forEach( + i -> { + children.add(i.getUid()); + MetadataFileItem refItem = new MetadataFileItem(i.getUid()); + refItem.setName(i.getName()); + refItem.setNameWithType(i.getNameWithType()); + refItem.setFullName(i.getFullName()); + references.add(refItem); + }); + + projectItem.getChildren().addAll(children); + projectMetadataFile.getReferences().addAll(references); + projectMetadataFile.getItems().add(projectItem); + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/ReferenceBuilder.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/ReferenceBuilder.java index c1ed3387..f0a5658e 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/ReferenceBuilder.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/ReferenceBuilder.java @@ -15,17 +15,16 @@ */ package com.microsoft.build; +import static com.microsoft.build.BuilderUtil.getJavaSpec; +import static com.microsoft.build.BuilderUtil.populateItemFields; +import static com.microsoft.build.BuilderUtil.replaceUidAndSplit; +import static com.microsoft.build.BuilderUtil.splitUidWithGenericsIntoClassNames; + import com.microsoft.lookup.ClassLookup; import com.microsoft.model.MetadataFile; import com.microsoft.model.MetadataFileItem; import com.microsoft.model.SpecViewModel; import com.microsoft.util.ElementUtil; -import jdk.javadoc.doclet.DocletEnvironment; -import org.apache.commons.lang3.RegExUtils; - -import javax.lang.model.element.Element; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.ElementFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; @@ -36,248 +35,286 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; - -import static com.microsoft.build.BuilderUtil.getJavaSpec; -import static com.microsoft.build.BuilderUtil.populateItemFields; -import static com.microsoft.build.BuilderUtil.replaceUidAndSplit; -import static com.microsoft.build.BuilderUtil.splitUidWithGenericsIntoClassNames; +import javax.lang.model.element.Element; +import javax.lang.model.element.TypeElement; +import javax.lang.model.util.ElementFilter; +import jdk.javadoc.doclet.DocletEnvironment; +import org.apache.commons.lang3.RegExUtils; class ReferenceBuilder { - private final Pattern JAVA_PATTERN = Pattern.compile("^java.*"); - private final Pattern PROTOBUF_PATTERN = Pattern.compile("^com.google.protobuf.*"); - private final Pattern GAX_PATTERN = Pattern.compile("^com.google.api.gax.*"); - private final Pattern APICOMMON_PATTERN = Pattern.compile("^com.google.api.core.*"); - private final Pattern LONGRUNNING_PATTERN = Pattern.compile("^com.google.longrunning.*"); - private final Pattern ENDING_PATTERN = Pattern.compile(".*<\\?>$"); - private final String PRIMITIVE_URL = "https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html"; - private final String JAVA_BASE_URL = "https://docs.oracle.com/javase/8/docs/api/"; - private final DocletEnvironment environment; - private final ClassLookup classLookup; - private final ElementUtil elementUtil; - - ReferenceBuilder(DocletEnvironment environment, ClassLookup classLookup, ElementUtil elementUtil) { - this.environment = environment; - this.classLookup = classLookup; - this.elementUtil = elementUtil; + private final Pattern JAVA_PATTERN = Pattern.compile("^java.*"); + private final Pattern PROTOBUF_PATTERN = Pattern.compile("^com.google.protobuf.*"); + private final Pattern GAX_PATTERN = Pattern.compile("^com.google.api.gax.*"); + private final Pattern APICOMMON_PATTERN = Pattern.compile("^com.google.api.core.*"); + private final Pattern LONGRUNNING_PATTERN = Pattern.compile("^com.google.longrunning.*"); + private final Pattern ENDING_PATTERN = Pattern.compile(".*<\\?>$"); + private final String PRIMITIVE_URL = + "https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html"; + private final String JAVA_BASE_URL = "https://docs.oracle.com/javase/8/docs/api/"; + private final DocletEnvironment environment; + private final ClassLookup classLookup; + private final ElementUtil elementUtil; + + ReferenceBuilder( + DocletEnvironment environment, ClassLookup classLookup, ElementUtil elementUtil) { + this.environment = environment; + this.classLookup = classLookup; + this.elementUtil = elementUtil; + } + + MetadataFileItem buildClassReference(TypeElement classElement) { + MetadataFileItem referenceItem = new MetadataFileItem(classLookup.extractUid(classElement)); + referenceItem.setName(classLookup.extractName(classElement)); + referenceItem.setNameWithType(classLookup.extractNameWithType(classElement)); + referenceItem.setFullName(classLookup.extractFullName(classElement)); + return referenceItem; + } + + void addReferencesInfo(TypeElement classElement, MetadataFile classMetadataFile) { + MetadataFileItem classReference = new MetadataFileItem(classLookup.extractUid(classElement)); + classReference.setParent(classLookup.extractParent(classElement)); + populateItemFields(classReference, classLookup, classElement); + classReference.setTypeParameters(classLookup.extractTypeParameters(classElement)); + + addTypeParameterReferences(classReference, classMetadataFile); + addSuperclassAndInterfacesReferences(classElement, classMetadataFile); + addInnerClassesReferences(classElement, classMetadataFile); + } + + void addChildrenReferences( + Element element, List packageChildren, Set referencesCollector) { + for (TypeElement classElement : elementUtil.extractSortedElements(element)) { + referencesCollector.add(buildClassReference(classElement)); + + packageChildren.add(classLookup.extractUid(classElement)); + addChildrenReferences(classElement, packageChildren, referencesCollector); } + } - MetadataFileItem buildClassReference(TypeElement classElement) { - MetadataFileItem referenceItem = new MetadataFileItem(classLookup.extractUid(classElement)); - referenceItem.setName(classLookup.extractName(classElement)); - referenceItem.setNameWithType(classLookup.extractNameWithType(classElement)); - referenceItem.setFullName(classLookup.extractFullName(classElement)); - return referenceItem; + String getJavaReferenceHref(String uid) { + if (uid == null || uid.equals("")) { + return JAVA_BASE_URL; } - - void addReferencesInfo(TypeElement classElement, MetadataFile classMetadataFile) { - MetadataFileItem classReference = new MetadataFileItem(classLookup.extractUid(classElement)); - classReference.setParent(classLookup.extractParent(classElement)); - populateItemFields(classReference, classLookup, classElement); - classReference.setTypeParameters(classLookup.extractTypeParameters(classElement)); - - addTypeParameterReferences(classReference, classMetadataFile); - addSuperclassAndInterfacesReferences(classElement, classMetadataFile); - addInnerClassesReferences(classElement, classMetadataFile); + // example1 uid: "java.lang.Object.equals(java.lang.Object)" + // example2 uid: "java.lang.Object" + String endURL = uid.replaceAll("", ""); + + Pattern argPattern = Pattern.compile(".*\\(.*\\).*"); + if (argPattern.matcher(endURL).find()) { + // example1 + // argumentSplit: ["java.lang.Object.equals", "java.lang.Object)"] + // nameSplit: ["java", "lang", "Object", "equals"] + List argumentSplit = Arrays.asList(endURL.split("\\(")); + List nameSplit = Arrays.asList(argumentSplit.get(0).split("\\.")); + + // className: "java/lang/Object" + // methodName: "#equals" + // argumentsName: "#java.lang.Object-" + String className = String.join("/", nameSplit.subList(0, nameSplit.size() - 1)); + String methodName = "#" + nameSplit.get(nameSplit.size() - 1); + String argumentsName = argumentSplit.get(1).replaceAll("[,)]", "-"); + + // endURL: "java/lang/Object.html#equals-java.lang.Object-" + endURL = className + ".html" + methodName + "-" + argumentsName; + } else { + // example2 + // endURL = java/lang/Object.html + endURL = endURL.replaceAll("\\.", "/"); + endURL = endURL + ".html"; } + return JAVA_BASE_URL + endURL; + } - void addChildrenReferences(Element element, List packageChildren, - Set referencesCollector) { - for (TypeElement classElement : elementUtil.extractSortedElements(element)) { - referencesCollector.add(buildClassReference(classElement)); + void updateExternalReferences(List classMetadataFiles) { + classMetadataFiles.forEach( + file -> file.getReferences().forEach(ref -> updateExternalReference(ref))); + } - packageChildren.add(classLookup.extractUid(classElement)); - addChildrenReferences(classElement, packageChildren, referencesCollector); - } - } + private void updateExternalReference(MetadataFileItem reference) { + String uid = reference.getUid(); + uid = updateReferenceUid(uid); - String getJavaReferenceHref(String uid) { - if (uid == null || uid.equals("")) { - return JAVA_BASE_URL; - } - // example1 uid: "java.lang.Object.equals(java.lang.Object)" - // example2 uid: "java.lang.Object" - String endURL = uid.replaceAll("", ""); - - Pattern argPattern = Pattern.compile(".*\\(.*\\).*"); - if (argPattern.matcher(endURL).find()) { - // example1 - // argumentSplit: ["java.lang.Object.equals", "java.lang.Object)"] - // nameSplit: ["java", "lang", "Object", "equals"] - List argumentSplit = Arrays.asList(endURL.split("\\(")); - List nameSplit = Arrays.asList(argumentSplit.get(0).split("\\.")); - - // className: "java/lang/Object" - // methodName: "#equals" - // argumentsName: "#java.lang.Object-" - String className = String.join("/", nameSplit.subList(0, nameSplit.size() - 1)); - String methodName = "#" + nameSplit.get(nameSplit.size() - 1); - String argumentsName = argumentSplit.get(1).replaceAll("[,)]", "-"); - - // endURL: "java/lang/Object.html#equals-java.lang.Object-" - endURL = className + ".html" + methodName + "-" + argumentsName; - } else { - // example2 - // endURL = java/lang/Object.html - endURL = endURL.replaceAll("\\.", "/"); - endURL = endURL + ".html"; - } - return JAVA_BASE_URL + endURL; + if (isJavaPrimitive(uid)) { + reference.setHref(PRIMITIVE_URL); + return; } - - void updateExternalReferences(List classMetadataFiles) { - classMetadataFiles.forEach(file -> file.getReferences() - .forEach(ref -> updateExternalReference(ref))); + if (isJavaLibrary(uid)) { + reference.setHref(getJavaReferenceHref(uid)); } - - private void updateExternalReference(MetadataFileItem reference) { - String uid = reference.getUid(); - uid = updateReferenceUid(uid); - - if (isJavaPrimitive(uid)) { - reference.setHref(PRIMITIVE_URL); - return; - } - if (isJavaLibrary(uid)) { - reference.setHref(getJavaReferenceHref(uid)); - } - if (isExternalReference(uid)) { - reference.setIsExternal(true); - } - if (reference.getSpecForJava().size() > 0) { - for (SpecViewModel spec : reference.getSpecForJava()) { - String specUid = spec.getUid(); - if (specUid != null) { - if (isJavaPrimitive(specUid)) { - spec.setHref(PRIMITIVE_URL); - } - if (isJavaLibrary(specUid)) { - spec.setHref(getJavaReferenceHref(specUid)); - } - if (isExternalReference(specUid)) { - spec.setIsExternal(true); - } - } - } - } + if (isExternalReference(uid)) { + reference.setIsExternal(true); } - - private String updateReferenceUid(String uid) { - if (ENDING_PATTERN.matcher(uid).find()) { - uid = uid.replace("", ""); + if (reference.getSpecForJava().size() > 0) { + for (SpecViewModel spec : reference.getSpecForJava()) { + String specUid = spec.getUid(); + if (specUid != null) { + if (isJavaPrimitive(specUid)) { + spec.setHref(PRIMITIVE_URL); + } + if (isJavaLibrary(specUid)) { + spec.setHref(getJavaReferenceHref(specUid)); + } + if (isExternalReference(specUid)) { + spec.setIsExternal(true); + } } - return uid; - } - - private boolean isExternalReference(String uid) { - return (PROTOBUF_PATTERN.matcher(uid).find() || GAX_PATTERN.matcher(uid).find() || APICOMMON_PATTERN.matcher(uid).find() || GAX_PATTERN.matcher(uid).find() || LONGRUNNING_PATTERN.matcher(uid).find()); + } } + } - private boolean isJavaPrimitive(String uid) { - return (uid.equals("boolean") || uid.equals("int") || uid.equals("byte") || uid.equals("long") || uid.equals("float") || uid.equals("double") || uid.equals("char") || uid.equals("short")); + private String updateReferenceUid(String uid) { + if (ENDING_PATTERN.matcher(uid).find()) { + uid = uid.replace("", ""); } - - private boolean isJavaLibrary(String uid) { - return JAVA_PATTERN.matcher(uid).find(); - } - - void addParameterReferences(MetadataFileItem methodItem, MetadataFile classMetadataFile) { - classMetadataFile.getReferences().addAll( - methodItem.getSyntax().getParameters().stream() - .map(parameter -> buildRefItem(parameter.getType())) - .filter(o -> !classMetadataFile.getItems().contains(o)) - .collect(Collectors.toList())); - } - - void addReturnReferences(MetadataFileItem methodItem, MetadataFile classMetadataFile) { - classMetadataFile.getReferences().addAll( - Stream.of(methodItem.getSyntax().getReturnValue()) - .filter(Objects::nonNull) - .map(returnValue -> buildRefItem(returnValue.getReturnType())) - .filter(o -> !classMetadataFile.getItems().contains(o)) - .collect(Collectors.toList())); - } - - void addExceptionReferences(MetadataFileItem methodItem, MetadataFile classMetadataFile) { - classMetadataFile.getReferences().addAll( - methodItem.getExceptions().stream() - .map(exceptionItem -> buildRefItem(exceptionItem.getType())) - .filter(o -> !classMetadataFile.getItems().contains(o)) - .collect(Collectors.toList())); + return uid; + } + + private boolean isExternalReference(String uid) { + return (PROTOBUF_PATTERN.matcher(uid).find() + || GAX_PATTERN.matcher(uid).find() + || APICOMMON_PATTERN.matcher(uid).find() + || GAX_PATTERN.matcher(uid).find() + || LONGRUNNING_PATTERN.matcher(uid).find()); + } + + private boolean isJavaPrimitive(String uid) { + return (uid.equals("boolean") + || uid.equals("int") + || uid.equals("byte") + || uid.equals("long") + || uid.equals("float") + || uid.equals("double") + || uid.equals("char") + || uid.equals("short")); + } + + private boolean isJavaLibrary(String uid) { + return JAVA_PATTERN.matcher(uid).find(); + } + + void addParameterReferences(MetadataFileItem methodItem, MetadataFile classMetadataFile) { + classMetadataFile + .getReferences() + .addAll( + methodItem.getSyntax().getParameters().stream() + .map(parameter -> buildRefItem(parameter.getType())) + .filter(o -> !classMetadataFile.getItems().contains(o)) + .collect(Collectors.toList())); + } + + void addReturnReferences(MetadataFileItem methodItem, MetadataFile classMetadataFile) { + classMetadataFile + .getReferences() + .addAll( + Stream.of(methodItem.getSyntax().getReturnValue()) + .filter(Objects::nonNull) + .map(returnValue -> buildRefItem(returnValue.getReturnType())) + .filter(o -> !classMetadataFile.getItems().contains(o)) + .collect(Collectors.toList())); + } + + void addExceptionReferences(MetadataFileItem methodItem, MetadataFile classMetadataFile) { + classMetadataFile + .getReferences() + .addAll( + methodItem.getExceptions().stream() + .map(exceptionItem -> buildRefItem(exceptionItem.getType())) + .filter(o -> !classMetadataFile.getItems().contains(o)) + .collect(Collectors.toList())); + } + + void addTypeParameterReferences(MetadataFileItem methodItem, MetadataFile classMetadataFile) { + classMetadataFile + .getReferences() + .addAll( + methodItem.getSyntax().getTypeParameters().stream() + .map( + typeParameter -> { + String id = typeParameter.getId(); + return new MetadataFileItem(id, id, false); + }) + .collect(Collectors.toList())); + } + + void addSuperclassAndInterfacesReferences( + TypeElement classElement, MetadataFile classMetadataFile) { + classMetadataFile.getReferences().addAll(classLookup.extractReferences(classElement)); + } + + void addInnerClassesReferences(TypeElement classElement, MetadataFile classMetadataFile) { + classMetadataFile + .getReferences() + .addAll( + ElementFilter.typesIn(elementUtil.extractSortedElements(classElement)).stream() + .map(this::buildClassReference) + .collect(Collectors.toList())); + } + + void addOverloadReferences(MetadataFileItem item, MetadataFile classMetadataFile) { + classMetadataFile + .getReferences() + .add( + new MetadataFileItem(item.getOverload()) { + { + setName(RegExUtils.removeAll(item.getName(), "\\(.*\\)$")); + setNameWithType(RegExUtils.removeAll(item.getNameWithType(), "\\(.*\\)$")); + setFullName(RegExUtils.removeAll(item.getFullName(), "\\(.*\\)$")); + setPackageName(item.getPackageName()); + } + }); + } + + /** + * Replace one record in 'references' with several records in this way: + * + *
+   * a.b.c.List> ->
+   *     - a.b.c.List
+   *     - df.mn.ClassOne
+   *     - tr.T
+   * 
+ */ + void expandComplexGenericsInReferences(MetadataFile classMetadataFile) { + Set additionalItems = new LinkedHashSet<>(); + Iterator iterator = classMetadataFile.getReferences().iterator(); + while (iterator.hasNext()) { + MetadataFileItem item = iterator.next(); + String uid = item.getUid(); + if (!uid.endsWith("*") && uid.contains("<")) { + List classNames = splitUidWithGenericsIntoClassNames(uid); + additionalItems.addAll( + classNames.stream() + .map(s -> new MetadataFileItem(s, classLookup.makeTypeShort(s), false)) + .collect(Collectors.toSet())); + } } - - void addTypeParameterReferences(MetadataFileItem methodItem, MetadataFile classMetadataFile) { - classMetadataFile.getReferences().addAll( - methodItem.getSyntax().getTypeParameters().stream() - .map(typeParameter -> { - String id = typeParameter.getId(); - return new MetadataFileItem(id, id, false); - }).collect(Collectors.toList())); - } - - void addSuperclassAndInterfacesReferences(TypeElement classElement, MetadataFile classMetadataFile) { - classMetadataFile.getReferences().addAll(classLookup.extractReferences(classElement)); - } - - void addInnerClassesReferences(TypeElement classElement, MetadataFile classMetadataFile) { - classMetadataFile.getReferences().addAll( - ElementFilter.typesIn(elementUtil.extractSortedElements(classElement)).stream() - .map(this::buildClassReference) - .collect(Collectors.toList())); - } - - void addOverloadReferences(MetadataFileItem item, MetadataFile classMetadataFile) { - classMetadataFile.getReferences().add(new MetadataFileItem(item.getOverload()) {{ - setName(RegExUtils.removeAll(item.getName(), "\\(.*\\)$")); - setNameWithType(RegExUtils.removeAll(item.getNameWithType(), "\\(.*\\)$")); - setFullName(RegExUtils.removeAll(item.getFullName(), "\\(.*\\)$")); - setPackageName(item.getPackageName()); - }}); - } - - /** - * Replace one record in 'references' with several records in this way: - *
-     * a.b.c.List> ->
-     *     - a.b.c.List
-     *     - df.mn.ClassOne
-     *     - tr.T
-     * 
- */ - void expandComplexGenericsInReferences(MetadataFile classMetadataFile) { - Set additionalItems = new LinkedHashSet<>(); - Iterator iterator = classMetadataFile.getReferences().iterator(); - while (iterator.hasNext()) { - MetadataFileItem item = iterator.next(); - String uid = item.getUid(); - if (!uid.endsWith("*") && uid.contains("<")) { - List classNames = splitUidWithGenericsIntoClassNames(uid); - additionalItems.addAll(classNames.stream() - .map(s -> new MetadataFileItem(s, classLookup.makeTypeShort(s), false)) - .collect(Collectors.toSet())); - } - } - // Remove items which already exist in 'items' section (compared by 'uid' field) - additionalItems.removeAll(classMetadataFile.getItems()); - - classMetadataFile.getReferences().addAll(additionalItems); - } - - MetadataFileItem buildRefItem(String uid) { - if (!uid.endsWith("*") && (uid.contains("<") || uid.contains("[]"))) { - return new MetadataFileItem(uid, getJavaSpec(replaceUidAndSplit(uid))); - } else { - List fullNameList = new ArrayList<>(); - - environment.getIncludedElements().forEach( - element -> elementUtil.extractSortedElements(element).forEach( - typeElement -> fullNameList.add(classLookup.extractFullName(typeElement))) - ); - - if (fullNameList.contains(uid)) { - return new MetadataFileItem(uid, classLookup.makeTypeShort(uid), false); - } else { - return new MetadataFileItem(uid, getJavaSpec(replaceUidAndSplit(uid))); - } - } + // Remove items which already exist in 'items' section (compared by 'uid' field) + additionalItems.removeAll(classMetadataFile.getItems()); + + classMetadataFile.getReferences().addAll(additionalItems); + } + + MetadataFileItem buildRefItem(String uid) { + if (!uid.endsWith("*") && (uid.contains("<") || uid.contains("[]"))) { + return new MetadataFileItem(uid, getJavaSpec(replaceUidAndSplit(uid))); + } else { + List fullNameList = new ArrayList<>(); + + environment + .getIncludedElements() + .forEach( + element -> + elementUtil + .extractSortedElements(element) + .forEach( + typeElement -> + fullNameList.add(classLookup.extractFullName(typeElement)))); + + if (fullNameList.contains(uid)) { + return new MetadataFileItem(uid, classLookup.makeTypeShort(uid), false); + } else { + return new MetadataFileItem(uid, getJavaSpec(replaceUidAndSplit(uid))); + } } + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/YmlFilesBuilder.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/YmlFilesBuilder.java index 7288b135..7e0d1f66 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/YmlFilesBuilder.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/build/YmlFilesBuilder.java @@ -1,5 +1,7 @@ package com.microsoft.build; +import static com.microsoft.build.BuilderUtil.populateUidValues; + import com.microsoft.lookup.ClassItemsLookup; import com.microsoft.lookup.ClassLookup; import com.microsoft.lookup.PackageLookup; @@ -10,105 +12,115 @@ import com.microsoft.model.TocTypeMap; import com.microsoft.util.ElementUtil; import com.microsoft.util.FileUtil; -import jdk.javadoc.doclet.DocletEnvironment; - -import javax.lang.model.element.PackageElement; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; - -import static com.microsoft.build.BuilderUtil.populateUidValues; +import javax.lang.model.element.PackageElement; +import jdk.javadoc.doclet.DocletEnvironment; public class YmlFilesBuilder { - private DocletEnvironment environment; - private String outputPath; - private ElementUtil elementUtil; - private PackageLookup packageLookup; - private String projectName; - private boolean disableChangelog; - private ProjectBuilder projectBuilder; - private PackageBuilder packageBuilder; - private ClassBuilder classBuilder; - private ReferenceBuilder referenceBuilder; + private DocletEnvironment environment; + private String outputPath; + private ElementUtil elementUtil; + private PackageLookup packageLookup; + private String projectName; + private boolean disableChangelog; + private ProjectBuilder projectBuilder; + private PackageBuilder packageBuilder; + private ClassBuilder classBuilder; + private ReferenceBuilder referenceBuilder; - public YmlFilesBuilder(DocletEnvironment environment, String outputPath, - String[] excludePackages, String[] excludeClasses, String projectName, boolean disableChangelog) { - this.environment = environment; - this.outputPath = outputPath; - this.elementUtil = new ElementUtil(excludePackages, excludeClasses); - this.packageLookup = new PackageLookup(environment); - this.projectName = projectName; - this.disableChangelog = disableChangelog; - this.projectBuilder = new ProjectBuilder(projectName); - ClassLookup classLookup = new ClassLookup(environment, elementUtil); - this.referenceBuilder = new ReferenceBuilder(environment, classLookup, elementUtil); - this.packageBuilder = new PackageBuilder(packageLookup, outputPath, referenceBuilder); - this.classBuilder = new ClassBuilder(elementUtil, classLookup, new ClassItemsLookup(environment, elementUtil), outputPath, referenceBuilder); - } + public YmlFilesBuilder( + DocletEnvironment environment, + String outputPath, + String[] excludePackages, + String[] excludeClasses, + String projectName, + boolean disableChangelog) { + this.environment = environment; + this.outputPath = outputPath; + this.elementUtil = new ElementUtil(excludePackages, excludeClasses); + this.packageLookup = new PackageLookup(environment); + this.projectName = projectName; + this.disableChangelog = disableChangelog; + this.projectBuilder = new ProjectBuilder(projectName); + ClassLookup classLookup = new ClassLookup(environment, elementUtil); + this.referenceBuilder = new ReferenceBuilder(environment, classLookup, elementUtil); + this.packageBuilder = new PackageBuilder(packageLookup, outputPath, referenceBuilder); + this.classBuilder = + new ClassBuilder( + elementUtil, + classLookup, + new ClassItemsLookup(environment, elementUtil), + outputPath, + referenceBuilder); + } - public boolean build() { - // table of contents - TocFile tocFile = new TocFile(outputPath, projectName, disableChangelog); - // overview page - MetadataFile projectMetadataFile = new MetadataFile(outputPath, "overview.yml"); - // package summary pages - List packageMetadataFiles = new ArrayList<>(); - // packages - List packageItems = new ArrayList<>(); - // class/enum/interface/etc. pages - List classMetadataFiles = new ArrayList<>(); + public boolean build() { + // table of contents + TocFile tocFile = new TocFile(outputPath, projectName, disableChangelog); + // overview page + MetadataFile projectMetadataFile = new MetadataFile(outputPath, "overview.yml"); + // package summary pages + List packageMetadataFiles = new ArrayList<>(); + // packages + List packageItems = new ArrayList<>(); + // class/enum/interface/etc. pages + List classMetadataFiles = new ArrayList<>(); - for (PackageElement packageElement : - elementUtil.extractPackageElements(environment.getIncludedElements())) { - String packageUid = packageLookup.extractUid(packageElement); - String packageStatus = packageLookup.extractStatus(packageElement); - TocItem packageTocItem = new TocItem(packageUid, packageUid, packageStatus); - // build package summary - packageMetadataFiles.add(packageBuilder.buildPackageMetadataFile(packageElement)); - // add package summary to toc - packageTocItem.getItems().add(new TocItem(packageUid, "Package summary")); - tocFile.addTocItem(packageTocItem); + for (PackageElement packageElement : + elementUtil.extractPackageElements(environment.getIncludedElements())) { + String packageUid = packageLookup.extractUid(packageElement); + String packageStatus = packageLookup.extractStatus(packageElement); + TocItem packageTocItem = new TocItem(packageUid, packageUid, packageStatus); + // build package summary + packageMetadataFiles.add(packageBuilder.buildPackageMetadataFile(packageElement)); + // add package summary to toc + packageTocItem.getItems().add(new TocItem(packageUid, "Package summary")); + tocFile.addTocItem(packageTocItem); - // build classes/interfaces/enums/exceptions/annotations - TocTypeMap typeMap = new TocTypeMap(); - classBuilder.buildFilesForInnerClasses(packageElement, typeMap, classMetadataFiles); - packageTocItem.getItems().addAll(joinTocTypeItems(typeMap)); - } + // build classes/interfaces/enums/exceptions/annotations + TocTypeMap typeMap = new TocTypeMap(); + classBuilder.buildFilesForInnerClasses(packageElement, typeMap, classMetadataFiles); + packageTocItem.getItems().addAll(joinTocTypeItems(typeMap)); + } - for (MetadataFile packageFile : packageMetadataFiles) { - packageItems.addAll(packageFile.getItems()); - String packageFileName = packageFile.getFileName(); - for (MetadataFile classFile : classMetadataFiles) { - String classFileName = classFile.getFileName(); - if (packageFileName.equalsIgnoreCase(classFileName)) { - packageFile.setFileName(packageFileName.replaceAll("\\.yml$", "(package).yml")); - classFile.setFileName(classFileName.replaceAll("\\.yml$", "(class).yml")); - break; - } - } + for (MetadataFile packageFile : packageMetadataFiles) { + packageItems.addAll(packageFile.getItems()); + String packageFileName = packageFile.getFileName(); + for (MetadataFile classFile : classMetadataFiles) { + String classFileName = classFile.getFileName(); + if (packageFileName.equalsIgnoreCase(classFileName)) { + packageFile.setFileName(packageFileName.replaceAll("\\.yml$", "(package).yml")); + classFile.setFileName(classFileName.replaceAll("\\.yml$", "(class).yml")); + break; } - // build project summary page - projectBuilder.buildProjectMetadataFile(packageItems, projectMetadataFile); + } + } + // build project summary page + projectBuilder.buildProjectMetadataFile(packageItems, projectMetadataFile); - // post-processing - populateUidValues(packageMetadataFiles, classMetadataFiles); - referenceBuilder.updateExternalReferences(classMetadataFiles); + // post-processing + populateUidValues(packageMetadataFiles, classMetadataFiles); + referenceBuilder.updateExternalReferences(classMetadataFiles); - // write to yaml files - FileUtil.dumpToFile(projectMetadataFile); - packageMetadataFiles.forEach(FileUtil::dumpToFile); - classMetadataFiles.forEach(FileUtil::dumpToFile); - FileUtil.dumpToFile(tocFile); + // write to yaml files + FileUtil.dumpToFile(projectMetadataFile); + packageMetadataFiles.forEach(FileUtil::dumpToFile); + classMetadataFiles.forEach(FileUtil::dumpToFile); + FileUtil.dumpToFile(tocFile); - return true; - } + return true; + } - List joinTocTypeItems(TocTypeMap tocTypeMap) { - return tocTypeMap.getTitleList().stream() - .filter(kindTitle -> tocTypeMap.get(kindTitle.getElementKind()).size() > 0) - .flatMap(kindTitle -> { - tocTypeMap.get(kindTitle.getElementKind()).add(0, new TocItem(kindTitle.getTitle())); - return tocTypeMap.get(kindTitle.getElementKind()).stream(); - }).collect(Collectors.toList()); - } + List joinTocTypeItems(TocTypeMap tocTypeMap) { + return tocTypeMap.getTitleList().stream() + .filter(kindTitle -> tocTypeMap.get(kindTitle.getElementKind()).size() > 0) + .flatMap( + kindTitle -> { + tocTypeMap.get(kindTitle.getElementKind()).add(0, new TocItem(kindTitle.getTitle())); + return tocTypeMap.get(kindTitle.getElementKind()).stream(); + }) + .collect(Collectors.toList()); + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/doclet/DocFxDoclet.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/doclet/DocFxDoclet.java index 20050e74..7d9c5f15 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/doclet/DocFxDoclet.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/doclet/DocFxDoclet.java @@ -1,156 +1,171 @@ package com.microsoft.doclet; import com.microsoft.build.YmlFilesBuilder; +import java.util.*; +import javax.lang.model.SourceVersion; +import javax.tools.Diagnostic.Kind; import jdk.javadoc.doclet.Doclet; import jdk.javadoc.doclet.DocletEnvironment; import jdk.javadoc.doclet.Reporter; import org.apache.commons.lang3.StringUtils; -import javax.lang.model.SourceVersion; -import javax.tools.Diagnostic.Kind; -import java.util.*; - public class DocFxDoclet implements Doclet { - private Reporter reporter; + private Reporter reporter; + + @Override + public void init(Locale locale, Reporter reporter) { + reporter.print(Kind.NOTE, "Doclet using locale: " + locale); + this.reporter = reporter; + } + + @Override + public boolean run(DocletEnvironment environment) { + reporter.print(Kind.NOTE, "Output path: " + outputPath); + reporter.print(Kind.NOTE, "Excluded packages: " + Arrays.toString(excludePackages)); + reporter.print(Kind.NOTE, "Excluded classes: " + Arrays.toString(excludeClasses)); + reporter.print(Kind.NOTE, "Project name: " + projectName); + reporter.print(Kind.NOTE, "Disable changelog: " + disableChangelog); + + return (new YmlFilesBuilder( + environment, + outputPath, + excludePackages, + excludeClasses, + projectName, + disableChangelog)) + .build(); + } + + @Override + public String getName() { + return "DocFxDoclet"; + } + + private String outputPath; + private String[] excludePackages = {}; + private String[] excludeClasses = {}; + private String projectName; + private boolean disableChangelog; + + @Override + public Set getSupportedOptions() { + Option[] options = { + new CustomOption("Output path", Arrays.asList("-outputpath", "--output-path", "-d"), "path") { + @Override + public boolean process(String option, List arguments) { + outputPath = arguments.get(0); + return true; + } + }, + new CustomOption( + "Exclude packages", + Arrays.asList("-excludepackages", "--exclude-packages", "-ep"), + "packages") { + @Override + public boolean process(String option, List arguments) { + excludePackages = StringUtils.split(arguments.get(0), ":"); + return true; + } + }, + new CustomOption( + "Exclude classes", + Arrays.asList("-excludeclasses", "--exclude-classes", "-ec"), + "classes") { + @Override + public boolean process(String option, List arguments) { + excludeClasses = StringUtils.split(arguments.get(0), ":"); + return true; + } + }, + new CustomOption( + "Project name", Arrays.asList("-projectname", "--project-name", "-pn"), "name") { + @Override + public boolean process(String option, List arguments) { + // using artifact id as projectName - remove "-parent" since generation runs in parent + // pom + projectName = arguments.get(0).replaceAll("-parent", ""); + return true; + } + }, + new CustomOption( + "Disable changelog", + Arrays.asList("-disable-changelog", "--disable-changelog"), + "disableChangelog") { + @Override + public boolean process(String option, List arguments) { + if (arguments.get(0).equalsIgnoreCase("false")) { + disableChangelog = false; + } else { + disableChangelog = true; + } + return true; + } + }, + // Support next properties for compatibility with Gradle javadoc task. + // According to javadoc spec - these properties used by StandardDoclet and used only when + // 'doclet' parameter not populated. But Gradle javadoc not align with this rule and + // passes them in spite of 'doclet' parameter existence + new FakeOptionForCompatibilityWithStandardDoclet( + "Fake support of doctitle property", "-doctitle"), + new FakeOptionForCompatibilityWithStandardDoclet( + "Fake support of windowtitle property", "-windowtitle") + }; + return new HashSet<>(Arrays.asList(options)); + } + + @Override + public SourceVersion getSupportedSourceVersion() { + return SourceVersion.latest(); + } + + abstract static class CustomOption implements Option { + + private final String description; + private final List names; + private final String parameters; + + public CustomOption(String description, List names, String parameters) { + this.description = description; + this.names = names; + this.parameters = parameters; + } @Override - public void init(Locale locale, Reporter reporter) { - reporter.print(Kind.NOTE, "Doclet using locale: " + locale); - this.reporter = reporter; + public int getArgumentCount() { + return 1; } @Override - public boolean run(DocletEnvironment environment) { - reporter.print(Kind.NOTE, "Output path: " + outputPath); - reporter.print(Kind.NOTE, "Excluded packages: " + Arrays.toString(excludePackages)); - reporter.print(Kind.NOTE, "Excluded classes: " + Arrays.toString(excludeClasses)); - reporter.print(Kind.NOTE, "Project name: " + projectName); - reporter.print(Kind.NOTE, "Disable changelog: " + disableChangelog); - - return (new YmlFilesBuilder(environment, outputPath, excludePackages, excludeClasses, projectName, disableChangelog)).build(); + public String getDescription() { + return description; } @Override - public String getName() { - return "DocFxDoclet"; + public Kind getKind() { + return Kind.STANDARD; } - private String outputPath; - private String[] excludePackages = {}; - private String[] excludeClasses = {}; - private String projectName; - private boolean disableChangelog; - @Override - public Set getSupportedOptions() { - Option[] options = { - new CustomOption("Output path", Arrays.asList("-outputpath", "--output-path", "-d"), "path") { - @Override - public boolean process(String option, List arguments) { - outputPath = arguments.get(0); - return true; - } - }, - new CustomOption("Exclude packages", Arrays.asList("-excludepackages", "--exclude-packages", "-ep"), - "packages") { - @Override - public boolean process(String option, List arguments) { - excludePackages = StringUtils.split(arguments.get(0), ":"); - return true; - } - }, - new CustomOption("Exclude classes", Arrays.asList("-excludeclasses", "--exclude-classes", "-ec"), - "classes") { - @Override - public boolean process(String option, List arguments) { - excludeClasses = StringUtils.split(arguments.get(0), ":"); - return true; - } - }, - new CustomOption( - "Project name", Arrays.asList("-projectname", "--project-name", "-pn"), "name") { - @Override - public boolean process(String option, List arguments) { - // using artifact id as projectName - remove "-parent" since generation runs in parent pom - projectName = arguments.get(0).replaceAll("-parent", ""); - return true; - } - }, - new CustomOption( - "Disable changelog", Arrays.asList("-disable-changelog", "--disable-changelog"), "disableChangelog") { - @Override - public boolean process(String option, List arguments) { - if (arguments.get(0).equalsIgnoreCase("false")){ - disableChangelog = false; - } else { - disableChangelog = true; - } - return true; - } - }, - // Support next properties for compatibility with Gradle javadoc task. - // According to javadoc spec - these properties used by StandardDoclet and used only when - // 'doclet' parameter not populated. But Gradle javadoc not align with this rule and - // passes them in spite of 'doclet' parameter existence - new FakeOptionForCompatibilityWithStandardDoclet("Fake support of doctitle property", "-doctitle"), - new FakeOptionForCompatibilityWithStandardDoclet("Fake support of windowtitle property", "-windowtitle") - }; - return new HashSet<>(Arrays.asList(options)); + public List getNames() { + return names; } @Override - public SourceVersion getSupportedSourceVersion() { - return SourceVersion.latest(); + public String getParameters() { + return parameters; } + } - abstract static class CustomOption implements Option { + static class FakeOptionForCompatibilityWithStandardDoclet extends CustomOption { - private final String description; - private final List names; - private final String parameters; - - public CustomOption(String description, List names, String parameters) { - this.description = description; - this.names = names; - this.parameters = parameters; - } - - @Override - public int getArgumentCount() { - return 1; - } - - @Override - public String getDescription() { - return description; - } - - @Override - public Kind getKind() { - return Kind.STANDARD; - } - - @Override - public List getNames() { - return names; - } - - @Override - public String getParameters() { - return parameters; - } + public FakeOptionForCompatibilityWithStandardDoclet(String description, String name) { + super(description, Collections.singletonList(name), "none"); } - static class FakeOptionForCompatibilityWithStandardDoclet extends CustomOption { - - public FakeOptionForCompatibilityWithStandardDoclet(String description, String name) { - super(description, Collections.singletonList(name), "none"); - } - - @Override - public boolean process(String option, List arguments) { - return true; - } + @Override + public boolean process(String option, List arguments) { + return true; } + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/doclet/DocletRunner.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/doclet/DocletRunner.java index a96a8af0..f7153bb8 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/doclet/DocletRunner.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/doclet/DocletRunner.java @@ -14,20 +14,20 @@ */ public class DocletRunner { - public static void main(final String[] args) { - if (args.length < 1) { - System.err.println("Usage: java DocletRunner "); - return; - } + public static void main(final String[] args) { + if (args.length < 1) { + System.err.println("Usage: java DocletRunner "); + return; + } - List combined = new ArrayList<>(); - for (String arg : args) { - if (!(new java.io.File(arg)).isFile()) { - System.err.println(String.format("File '%s' does not exist", args[0])); - } - combined.addAll(OptionsFileUtil.processOptionsFile(arg)); - } - ToolProvider.getSystemDocumentationTool() - .run(null, null, null, combined.toArray(new String[0])); + List combined = new ArrayList<>(); + for (String arg : args) { + if (!(new java.io.File(arg)).isFile()) { + System.err.println(String.format("File '%s' does not exist", args[0])); + } + combined.addAll(OptionsFileUtil.processOptionsFile(arg)); } + ToolProvider.getSystemDocumentationTool() + .run(null, null, null, combined.toArray(new String[0])); + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/lookup/BaseLookup.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/lookup/BaseLookup.java index ba6b808b..df5eb075 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/lookup/BaseLookup.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/lookup/BaseLookup.java @@ -13,13 +13,6 @@ import com.sun.source.doctree.LinkTree; import com.sun.source.doctree.LiteralTree; import com.sun.source.doctree.SeeTree; -import jdk.javadoc.doclet.DocletEnvironment; -import org.apache.commons.lang3.RegExUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.text.StringEscapeUtils; - -import javax.lang.model.element.Element; -import javax.lang.model.element.ElementKind; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; @@ -29,276 +22,295 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; +import javax.lang.model.element.Element; +import javax.lang.model.element.ElementKind; +import jdk.javadoc.doclet.DocletEnvironment; +import org.apache.commons.lang3.RegExUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.text.StringEscapeUtils; public abstract class BaseLookup { - private static final int INITIAL_CAPACITY = 500000; - protected final Map elementKindLookup = new HashMap<>() {{ - put(ElementKind.PACKAGE, "Namespace"); - put(ElementKind.CLASS, "Class"); - put(ElementKind.ENUM, "Enum"); - put(ElementKind.ENUM_CONSTANT, "Field"); - put(ElementKind.INTERFACE, "Interface"); - put(ElementKind.ANNOTATION_TYPE, "Interface"); - put(ElementKind.CONSTRUCTOR, "Constructor"); - put(ElementKind.METHOD, "Method"); - put(ElementKind.FIELD, "Field"); - }}; - - protected Map map; - protected final DocletEnvironment environment; - - protected BaseLookup(DocletEnvironment environment) { - this.environment = environment; - this.map = new HashMap<>(INITIAL_CAPACITY); - } - - protected ExtendedMetadataFileItem resolve(T key) { - map.computeIfAbsent(key, this::buildMetadataFileItem); - return map.get(key); - } - - protected abstract ExtendedMetadataFileItem buildMetadataFileItem(T key); - - public String extractPackageName(T key) { - return resolve(key).getPackageName(); - } - - public String extractFullName(T key) { - return resolve(key).getFullName(); - } - - public String extractName(T key) { - return resolve(key).getName(); - } - - public String extractHref(T key) { - return resolve(key).getHref(); - } - - public String extractParent(T key) { - return resolve(key).getParent(); - } - - public String extractId(T key) { - return resolve(key).getId(); - } - - public String extractUid(T key) { - return resolve(key).getUid(); - } - - public String extractNameWithType(T key) { - return resolve(key).getNameWithType(); - } - - public String extractMethodContent(T key) { - return resolve(key).getMethodContent(); - } - - public String extractFieldContent(T key) { - return resolve(key).getFieldContent(); - } - - public String extractConstructorContent(T key) { - return resolve(key).getConstructorContent(); - } - - public String extractOverload(T key) { - return resolve(key).getOverload(); - } - - public List extractParameters(T key) { - return resolve(key).getParameters(); - } - - public List extractExceptions(T key) { - return resolve(key).getExceptions(); - } - - public Return extractReturn(T key) { - return resolve(key).getReturn(); - } - - public String extractSummary(T key) { - return resolve(key).getSummary(); - } - - public String extractType(T key) { - return resolve(key).getType(); - } - - public String extractJavaType(T element) {return null;} - - public String extractContent(T key) { - return resolve(key).getContent(); - } - - public List extractTypeParameters(T key) { - return resolve(key).getTypeParameters(); - } - - public List extractSuperclass(T key) { - List reversed = resolve(key).getSuperclass(); - Collections.reverse(reversed); - return reversed; - } - - public List extractInheritedMethods(T key) { - List sorted = resolve(key).getInheritedMethods(); - Collections.sort(sorted); - return sorted; - } - - public List extractInterfaces(T key) { - return resolve(key).getInterfaces(); - } - - public String extractTocName(T key) { - return resolve(key).getTocName(); - } - - public Set extractReferences(T key) { - return resolve(key).getReferences(); - } + private static final int INITIAL_CAPACITY = 500000; + protected final Map elementKindLookup = + new HashMap<>() { + { + put(ElementKind.PACKAGE, "Namespace"); + put(ElementKind.CLASS, "Class"); + put(ElementKind.ENUM, "Enum"); + put(ElementKind.ENUM_CONSTANT, "Field"); + put(ElementKind.INTERFACE, "Interface"); + put(ElementKind.ANNOTATION_TYPE, "Interface"); + put(ElementKind.CONSTRUCTOR, "Constructor"); + put(ElementKind.METHOD, "Method"); + put(ElementKind.FIELD, "Field"); + } + }; - public String extractOverridden(T key) { - return resolve(key).getOverridden(); - } + protected Map map; + protected final DocletEnvironment environment; - public String extractStatus(T element) { - Optional docCommentTree = getDocCommentTree(element); - if (docCommentTree.isPresent()) { - boolean isDeprecated = docCommentTree.get().getBlockTags().stream() - .filter(docTree -> docTree.getKind().equals(DocTree.Kind.DEPRECATED)) - .findFirst() - .isPresent(); - if (isDeprecated) { - return DocTree.Kind.DEPRECATED.name().toLowerCase(); - } - } - return null; - } + protected BaseLookup(DocletEnvironment environment) { + this.environment = environment; + this.map = new HashMap<>(INITIAL_CAPACITY); + } - protected String determineType(T element) { - return elementKindLookup.get(element.getKind()); - } + protected ExtendedMetadataFileItem resolve(T key) { + map.computeIfAbsent(key, this::buildMetadataFileItem); + return map.get(key); + } - protected String determinePackageName(T element) { - return String.valueOf(environment.getElementUtils().getPackageOf(element)); - } + protected abstract ExtendedMetadataFileItem buildMetadataFileItem(T key); - protected String determineComment(T element) { - Optional docCommentTree = getDocCommentTree(element); - if (docCommentTree.isPresent()) { - String comment = docCommentTree - .map(DocCommentTree::getFullBody) - .map(this::replaceLinksAndCodes) - .orElse(null); - return replaceBlockTags(docCommentTree.get(), comment); - } - return null; - } + public String extractPackageName(T key) { + return resolve(key).getPackageName(); + } - /** - * Provides support for deprecated and see tags - */ - String replaceBlockTags(DocCommentTree docCommentTree, String comment) { - Set seeItems = new HashSet<>(); - String commentWithBlockTags = comment; - for (DocTree blockTag : docCommentTree.getBlockTags()) { - switch (blockTag.getKind()) { - case DEPRECATED: - commentWithBlockTags = getDeprecatedSummary((DeprecatedTree) blockTag).concat(comment); - break; - case SEE: - seeItems.add(getSeeTagRef((SeeTree) blockTag)); - break; - default: - } - } - if (!seeItems.isEmpty()) { - commentWithBlockTags = commentWithBlockTags.concat(getSeeAlsoSummary(seeItems)); - } - return commentWithBlockTags; - } + public String extractFullName(T key) { + return resolve(key).getFullName(); + } - /** - *
    - *
  • Replace @link and @linkplain with tags
  • - *
  • Replace @code with tags
  • - *
- */ - String replaceLinksAndCodes(List items) { - return YamlUtil.cleanupHtml(items.stream().map( - bodyItem -> { - switch (bodyItem.getKind()) { + public String extractName(T key) { + return resolve(key).getName(); + } + + public String extractHref(T key) { + return resolve(key).getHref(); + } + + public String extractParent(T key) { + return resolve(key).getParent(); + } + + public String extractId(T key) { + return resolve(key).getId(); + } + + public String extractUid(T key) { + return resolve(key).getUid(); + } + + public String extractNameWithType(T key) { + return resolve(key).getNameWithType(); + } + + public String extractMethodContent(T key) { + return resolve(key).getMethodContent(); + } + + public String extractFieldContent(T key) { + return resolve(key).getFieldContent(); + } + + public String extractConstructorContent(T key) { + return resolve(key).getConstructorContent(); + } + + public String extractOverload(T key) { + return resolve(key).getOverload(); + } + + public List extractParameters(T key) { + return resolve(key).getParameters(); + } + + public List extractExceptions(T key) { + return resolve(key).getExceptions(); + } + + public Return extractReturn(T key) { + return resolve(key).getReturn(); + } + + public String extractSummary(T key) { + return resolve(key).getSummary(); + } + + public String extractType(T key) { + return resolve(key).getType(); + } + + public String extractJavaType(T element) { + return null; + } + + public String extractContent(T key) { + return resolve(key).getContent(); + } + + public List extractTypeParameters(T key) { + return resolve(key).getTypeParameters(); + } + + public List extractSuperclass(T key) { + List reversed = resolve(key).getSuperclass(); + Collections.reverse(reversed); + return reversed; + } + + public List extractInheritedMethods(T key) { + List sorted = resolve(key).getInheritedMethods(); + Collections.sort(sorted); + return sorted; + } + + public List extractInterfaces(T key) { + return resolve(key).getInterfaces(); + } + + public String extractTocName(T key) { + return resolve(key).getTocName(); + } + + public Set extractReferences(T key) { + return resolve(key).getReferences(); + } + + public String extractOverridden(T key) { + return resolve(key).getOverridden(); + } + + public String extractStatus(T element) { + Optional docCommentTree = getDocCommentTree(element); + if (docCommentTree.isPresent()) { + boolean isDeprecated = + docCommentTree.get().getBlockTags().stream() + .filter(docTree -> docTree.getKind().equals(DocTree.Kind.DEPRECATED)) + .findFirst() + .isPresent(); + if (isDeprecated) { + return DocTree.Kind.DEPRECATED.name().toLowerCase(); + } + } + return null; + } + + protected String determineType(T element) { + return elementKindLookup.get(element.getKind()); + } + + protected String determinePackageName(T element) { + return String.valueOf(environment.getElementUtils().getPackageOf(element)); + } + + protected String determineComment(T element) { + Optional docCommentTree = getDocCommentTree(element); + if (docCommentTree.isPresent()) { + String comment = + docCommentTree + .map(DocCommentTree::getFullBody) + .map(this::replaceLinksAndCodes) + .orElse(null); + return replaceBlockTags(docCommentTree.get(), comment); + } + return null; + } + + /** Provides support for deprecated and see tags */ + String replaceBlockTags(DocCommentTree docCommentTree, String comment) { + Set seeItems = new HashSet<>(); + String commentWithBlockTags = comment; + for (DocTree blockTag : docCommentTree.getBlockTags()) { + switch (blockTag.getKind()) { + case DEPRECATED: + commentWithBlockTags = getDeprecatedSummary((DeprecatedTree) blockTag).concat(comment); + break; + case SEE: + seeItems.add(getSeeTagRef((SeeTree) blockTag)); + break; + default: + } + } + if (!seeItems.isEmpty()) { + commentWithBlockTags = commentWithBlockTags.concat(getSeeAlsoSummary(seeItems)); + } + return commentWithBlockTags; + } + + /** + *
    + *
  • Replace @link and @linkplain with tags
  • + *
  • Replace @code with tags
  • + *
+ */ + String replaceLinksAndCodes(List items) { + return YamlUtil.cleanupHtml( + items.stream() + .map( + bodyItem -> { + switch (bodyItem.getKind()) { case LINK: case LINK_PLAIN: - return buildXrefTag((LinkTree) bodyItem); + return buildXrefTag((LinkTree) bodyItem); case CODE: - return buildCodeTag((LiteralTree) bodyItem); + return buildCodeTag((LiteralTree) bodyItem); case LITERAL: - return expandLiteralBody((LiteralTree) bodyItem); + return expandLiteralBody((LiteralTree) bodyItem); default: - return String.valueOf(StringEscapeUtils.unescapeJava(bodyItem.toString())); - } - } - ).collect(Collectors.joining())); - } - - /** - * By using this way of processing links we provide support of @links with label, like this: {@link List someLabel} - */ - String buildXrefTag(LinkTree linkTree) { - String signature = linkTree.getReference().getSignature(); - String label = linkTree.getLabel().stream().map(String::valueOf).collect(Collectors.joining(" ")); - if (StringUtils.isEmpty(label)) { - label = signature; - } - return String.format("%s", signature, label); - } - - String buildCodeTag(LiteralTree literalTree) { - return String.format("%s", StringEscapeUtils.unescapeJava(literalTree.getBody().toString())); - } - - String expandLiteralBody(LiteralTree bodyItem) { - return String.valueOf(StringEscapeUtils.unescapeJava(bodyItem.getBody().toString())); - } - - protected Optional getDocCommentTree(T element) { - return Optional.ofNullable(environment.getDocTrees().getDocCommentTree(element)); - } - - /** - * We make type shortening in assumption that package name doesn't contain uppercase characters - */ - public String makeTypeShort(String value) { - if (!value.contains(".")) { - return value; - } - return Stream.of(StringUtils.split(value, "<")) - .map(s -> RegExUtils.removeAll(s, "\\b[a-z0-9_.]+\\.")) - .collect(Collectors.joining("<")); - } - - private String getSeeAlsoSummary(Set seeItems) { - return String.format("\nSee Also: %s\n", String.join(", ", seeItems)); - } - - private String getDeprecatedSummary(DeprecatedTree deprecatedTree) { - return String.format("\nDeprecated. %s\n\n", - replaceLinksAndCodes(deprecatedTree.getBody())); - } - - private String getSeeTagRef(SeeTree seeTree) { - String ref = seeTree.getReference().stream() - .map(r -> String.valueOf(r)).collect(Collectors.joining("")); - // if it's already a tag, use that otherwise build xref tag - if (ref.matches("^<.+>(.|\n)*")) { - return ref.replaceAll("\n", "").replaceAll("( )+", " "); - } - return String.format("%1$s", ref); - } -} \ No newline at end of file + return String.valueOf(StringEscapeUtils.unescapeJava(bodyItem.toString())); + } + }) + .collect(Collectors.joining())); + } + + /** + * By using this way of processing links we provide support of @links with label, like this: + * {@link List someLabel} + */ + String buildXrefTag(LinkTree linkTree) { + String signature = linkTree.getReference().getSignature(); + String label = + linkTree.getLabel().stream().map(String::valueOf).collect(Collectors.joining(" ")); + if (StringUtils.isEmpty(label)) { + label = signature; + } + return String.format( + "%s", signature, label); + } + + String buildCodeTag(LiteralTree literalTree) { + return String.format( + "%s", StringEscapeUtils.unescapeJava(literalTree.getBody().toString())); + } + + String expandLiteralBody(LiteralTree bodyItem) { + return String.valueOf(StringEscapeUtils.unescapeJava(bodyItem.getBody().toString())); + } + + protected Optional getDocCommentTree(T element) { + return Optional.ofNullable(environment.getDocTrees().getDocCommentTree(element)); + } + + /** + * We make type shortening in assumption that package name doesn't contain uppercase characters + */ + public String makeTypeShort(String value) { + if (!value.contains(".")) { + return value; + } + return Stream.of(StringUtils.split(value, "<")) + .map(s -> RegExUtils.removeAll(s, "\\b[a-z0-9_.]+\\.")) + .collect(Collectors.joining("<")); + } + + private String getSeeAlsoSummary(Set seeItems) { + return String.format("\nSee Also: %s\n", String.join(", ", seeItems)); + } + + private String getDeprecatedSummary(DeprecatedTree deprecatedTree) { + return String.format( + "\nDeprecated. %s\n\n", + replaceLinksAndCodes(deprecatedTree.getBody())); + } + + private String getSeeTagRef(SeeTree seeTree) { + String ref = + seeTree.getReference().stream().map(r -> String.valueOf(r)).collect(Collectors.joining("")); + // if it's already a tag, use that otherwise build xref tag + if (ref.matches("^<.+>(.|\n)*")) { + return ref.replaceAll("\n", "").replaceAll("( )+", " "); + } + return String.format( + "%1$s", ref); + } +} diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/lookup/ClassItemsLookup.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/lookup/ClassItemsLookup.java index f2da89d6..ecb5ca2e 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/lookup/ClassItemsLookup.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/lookup/ClassItemsLookup.java @@ -13,8 +13,10 @@ import com.sun.source.doctree.ParamTree; import com.sun.source.doctree.ReturnTree; import com.sun.source.doctree.ThrowsTree; -import jdk.javadoc.doclet.DocletEnvironment; - +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; @@ -22,30 +24,30 @@ import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeKind; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; +import jdk.javadoc.doclet.DocletEnvironment; public class ClassItemsLookup extends BaseLookup { - private Utils utils; + private Utils utils; - public ClassItemsLookup(DocletEnvironment environment, ElementUtil elementUtil) { - super(environment); - utils = new Utils(environment, elementUtil); - } + public ClassItemsLookup(DocletEnvironment environment, ElementUtil elementUtil) { + super(environment); + utils = new Utils(environment, elementUtil); + } + + @Override + protected ExtendedMetadataFileItem buildMetadataFileItem(Element element) { + String packageName = determinePackageName(element); + TypeElement classElement = (TypeElement) element.getEnclosingElement(); + String classQName = String.valueOf(classElement.getQualifiedName()); + String elementQName = String.valueOf(element); + String classQNameWithGenericsSupport = String.valueOf(classElement.asType()); + String classSNameWithGenericsSupport = + classQNameWithGenericsSupport.replace(packageName.concat("."), ""); + String uid = String.format("%s.%s", classQName, elementQName); - @Override - protected ExtendedMetadataFileItem buildMetadataFileItem(Element element) { - String packageName = determinePackageName(element); - TypeElement classElement = (TypeElement) element.getEnclosingElement(); - String classQName = String.valueOf(classElement.getQualifiedName()); - String elementQName = String.valueOf(element); - String classQNameWithGenericsSupport = String.valueOf(classElement.asType()); - String classSNameWithGenericsSupport = classQNameWithGenericsSupport.replace(packageName.concat("."), ""); - String uid = String.format("%s.%s", classQName, elementQName); - - ExtendedMetadataFileItem result = new ExtendedMetadataFileItem(uid) {{ + ExtendedMetadataFileItem result = + new ExtendedMetadataFileItem(uid) { + { setId(elementQName); setParent(classQName); setHref(classQName + ".yml"); @@ -53,171 +55,202 @@ protected ExtendedMetadataFileItem buildMetadataFileItem(Element element) { setType(determineType(element)); setPackageName(packageName); setSummary(determineComment(element)); - }}; - - String modifiers = element.getModifiers().stream().map(String::valueOf).collect(Collectors.joining(" ")); - if (element instanceof ExecutableElement) { - ExecutableElement exeElement = (ExecutableElement) element; - List parameters = extractParameters(exeElement); - String paramsString = parameters.stream() - .map(parameter -> String.format("%s %s", makeTypeShort(parameter.getType()), parameter.getId())) - .collect(Collectors.joining(", ")); - String nameWithoutBrackets = elementQName.replaceAll("\\(.*\\)", ""); - String methodName = String.format("%s(%s)", nameWithoutBrackets, paramsString); - - result.setName(methodName); - result.setMethodContent(String.format("%s %s %s", modifiers, - makeTypeShort(String.valueOf(exeElement.getReturnType())), result.getName())); - result.setConstructorContent(String.format("%s %s", modifiers, result.getName())); - result.setParameters(parameters); - result.setExceptions(extractExceptions(exeElement)); - result.setReturn(extractReturn(exeElement)); - if (exeElement.getKind() == ElementKind.METHOD) { - result.setOverridden(extractOverriddenUid(utils.overriddenMethod(exeElement))); - result.setSummary(determineComment(exeElement)); - } - } - result.setNameWithType(String.format("%s.%s", classSNameWithGenericsSupport, result.getName())); - result.setFullName(String.format("%s.%s", classQNameWithGenericsSupport, result.getName())); - result.setOverload(convertFullNameToOverload(result.getFullName())); - - if (element instanceof VariableElement) { - String type = makeTypeShort(String.valueOf(element.asType())); - result.setFieldContent(String.format("%s %s %s", modifiers, type, elementQName)); - result.setReturn(extractReturn((VariableElement) element)); - } - - return result; - } + } + }; - List extractParameters(ExecutableElement element) { - return element.getParameters().stream().map(o -> { - String paramName = String.valueOf(o.getSimpleName()); - String paramType = String.valueOf(o.asType()); - return new MethodParameter(paramName, paramType, extractParameterDescription(element, paramName)); - }).collect(Collectors.toList()); - } + String modifiers = + element.getModifiers().stream().map(String::valueOf).collect(Collectors.joining(" ")); + if (element instanceof ExecutableElement) { + ExecutableElement exeElement = (ExecutableElement) element; + List parameters = extractParameters(exeElement); + String paramsString = + parameters.stream() + .map( + parameter -> + String.format("%s %s", makeTypeShort(parameter.getType()), parameter.getId())) + .collect(Collectors.joining(", ")); + String nameWithoutBrackets = elementQName.replaceAll("\\(.*\\)", ""); + String methodName = String.format("%s(%s)", nameWithoutBrackets, paramsString); - String extractParameterDescription(ExecutableElement method, String paramName) { - return getDocCommentTree(method).map(docTree -> docTree.getBlockTags().stream() - .filter(o -> o.getKind() == Kind.PARAM) - .map(o -> (ParamTree) o) - .filter(o -> paramName.equals(String.valueOf(o.getName()))) - .map(o -> replaceLinksAndCodes(o.getDescription())) - .findFirst().orElse(null) - ).orElse(null); + result.setName(methodName); + result.setMethodContent( + String.format( + "%s %s %s", + modifiers, + makeTypeShort(String.valueOf(exeElement.getReturnType())), + result.getName())); + result.setConstructorContent(String.format("%s %s", modifiers, result.getName())); + result.setParameters(parameters); + result.setExceptions(extractExceptions(exeElement)); + result.setReturn(extractReturn(exeElement)); + if (exeElement.getKind() == ElementKind.METHOD) { + result.setOverridden(extractOverriddenUid(utils.overriddenMethod(exeElement))); + result.setSummary(determineComment(exeElement)); + } } + result.setNameWithType(String.format("%s.%s", classSNameWithGenericsSupport, result.getName())); + result.setFullName(String.format("%s.%s", classQNameWithGenericsSupport, result.getName())); + result.setOverload(convertFullNameToOverload(result.getFullName())); - List extractExceptions(ExecutableElement methodElement) { - return methodElement.getThrownTypes().stream().map(o -> { - String exceptionType = String.valueOf(o); - return new ExceptionItem(exceptionType, extractExceptionDescription(methodElement)); - }).collect(Collectors.toList()); + if (element instanceof VariableElement) { + String type = makeTypeShort(String.valueOf(element.asType())); + result.setFieldContent(String.format("%s %s %s", modifiers, type, elementQName)); + result.setReturn(extractReturn((VariableElement) element)); } - String extractExceptionDescription(ExecutableElement methodElement) { - return getDocCommentTree(methodElement).map(docTree -> docTree.getBlockTags().stream() - .filter(o -> o.getKind() == Kind.THROWS) - .map(o -> (ThrowsTree) o) - .map(o -> replaceLinksAndCodes(o.getDescription())) - .findFirst().orElse(null) - ).orElse(null); - } + return result; + } - Return extractReturn(ExecutableElement methodElement) { - if (methodElement.getReturnType().getKind() == TypeKind.VOID) { - return null; - } - return new Return(String.valueOf(methodElement.getReturnType()), extractReturnDescription(methodElement)); - } + List extractParameters(ExecutableElement element) { + return element.getParameters().stream() + .map( + o -> { + String paramName = String.valueOf(o.getSimpleName()); + String paramType = String.valueOf(o.asType()); + return new MethodParameter( + paramName, paramType, extractParameterDescription(element, paramName)); + }) + .collect(Collectors.toList()); + } - String extractReturnDescription(ExecutableElement methodElement) { - return getDocCommentTree(methodElement).map(docTree -> docTree.getBlockTags().stream() - .filter(o -> o.getKind() == Kind.RETURN) - .map(o -> (ReturnTree) o) - .map(o -> replaceLinksAndCodes(o.getDescription())) - .findFirst().orElse(null) - ).orElse(null); - } + String extractParameterDescription(ExecutableElement method, String paramName) { + return getDocCommentTree(method) + .map( + docTree -> + docTree.getBlockTags().stream() + .filter(o -> o.getKind() == Kind.PARAM) + .map(o -> (ParamTree) o) + .filter(o -> paramName.equals(String.valueOf(o.getName()))) + .map(o -> replaceLinksAndCodes(o.getDescription())) + .findFirst() + .orElse(null)) + .orElse(null); + } + + List extractExceptions(ExecutableElement methodElement) { + return methodElement.getThrownTypes().stream() + .map( + o -> { + String exceptionType = String.valueOf(o); + return new ExceptionItem(exceptionType, extractExceptionDescription(methodElement)); + }) + .collect(Collectors.toList()); + } + + String extractExceptionDescription(ExecutableElement methodElement) { + return getDocCommentTree(methodElement) + .map( + docTree -> + docTree.getBlockTags().stream() + .filter(o -> o.getKind() == Kind.THROWS) + .map(o -> (ThrowsTree) o) + .map(o -> replaceLinksAndCodes(o.getDescription())) + .findFirst() + .orElse(null)) + .orElse(null); + } - Return extractReturn(VariableElement fieldElement) { - return new Return(String.valueOf(fieldElement.asType())); + Return extractReturn(ExecutableElement methodElement) { + if (methodElement.getReturnType().getKind() == TypeKind.VOID) { + return null; } + return new Return( + String.valueOf(methodElement.getReturnType()), extractReturnDescription(methodElement)); + } - String convertFullNameToOverload(String fullName) { - return fullName.replaceAll("\\(.*\\)", "*"); + String extractReturnDescription(ExecutableElement methodElement) { + return getDocCommentTree(methodElement) + .map( + docTree -> + docTree.getBlockTags().stream() + .filter(o -> o.getKind() == Kind.RETURN) + .map(o -> (ReturnTree) o) + .map(o -> replaceLinksAndCodes(o.getDescription())) + .findFirst() + .orElse(null)) + .orElse(null); + } + + Return extractReturn(VariableElement fieldElement) { + return new Return(String.valueOf(fieldElement.asType())); + } + + String convertFullNameToOverload(String fullName) { + return fullName.replaceAll("\\(.*\\)", "*"); + } + + String extractOverriddenUid(ExecutableElement ovr) { + if (ovr != null) { + TypeElement te = utils.getEnclosingTypeElement(ovr); + String uid = te.getQualifiedName().toString().concat(".") + String.valueOf(ovr); + return uid; } - String extractOverriddenUid(ExecutableElement ovr) { - if (ovr != null) { - TypeElement te = utils.getEnclosingTypeElement(ovr); - String uid = te.getQualifiedName().toString().concat(".") + String.valueOf(ovr); - return uid; - } + return ""; + } - return ""; + private String determineComment(ExecutableElement methodElement) { + String inheritedInlineComment = getInheritedInlineCommentString(methodElement); + Optional docCommentTree = getDocCommentTree(methodElement); + if (docCommentTree.isPresent()) { + return replaceBlockTags(docCommentTree.get(), inheritedInlineComment); } + return inheritedInlineComment; + } - private String determineComment(ExecutableElement methodElement) { - String inheritedInlineComment = getInheritedInlineCommentString(methodElement); - Optional docCommentTree = getDocCommentTree(methodElement); - if (docCommentTree.isPresent()) { - return replaceBlockTags(docCommentTree.get(), inheritedInlineComment); - } - return inheritedInlineComment; + /** + * If the item being inherited from is declared from external compiled package, or is declared in + * the packages like java.lang.Object, comments may be not available as doclet resolves from byte + * code. + */ + private String getInheritedInlineCommentString(ExecutableElement exeElement) { + CommentHelper ch = getInheritedInlineTags(new CommentHelper(exeElement, utils)); + // Remove unresolved "@inheritDoc" tag. + List dctree = utils.removeBlockTag(ch.inlineTags, DocTree.Kind.INHERIT_DOC); + return replaceLinksAndCodes(dctree); + } + + private CommentHelper getInheritedInlineTags(CommentHelper input) { + CommentHelper output = input.copy(); + if (!output.hasInheritDocTag() && !output.isSimpleOverride()) { + return output; } - /** - * If the item being inherited from is declared from external compiled package, - * or is declared in the packages like java.lang.Object, - * comments may be not available as doclet resolves from byte code. - */ - private String getInheritedInlineCommentString(ExecutableElement exeElement) { - CommentHelper ch = getInheritedInlineTags(new CommentHelper(exeElement, utils)); - // Remove unresolved "@inheritDoc" tag. - List dctree = utils.removeBlockTag(ch.inlineTags, DocTree.Kind.INHERIT_DOC); - return replaceLinksAndCodes(dctree); + CommentHelper inheritedSearchInput = input.copy(); + ExecutableElement overriddenMethod = utils.overriddenMethod((ExecutableElement) input.element); + + if (overriddenMethod != null) { + inheritedSearchInput.element = overriddenMethod; + CommentHelper ch = getInheritedInlineTags(inheritedSearchInput); + if (!ch.isSimpleOverride()) { + output = output.inherit(ch); + } } - private CommentHelper getInheritedInlineTags(CommentHelper input) { - CommentHelper output = input.copy(); - if (!output.hasInheritDocTag() && !output.isSimpleOverride()) { - return output; - } - - CommentHelper inheritedSearchInput = input.copy(); - ExecutableElement overriddenMethod = utils.overriddenMethod((ExecutableElement) input.element); - - if (overriddenMethod != null) { - inheritedSearchInput.element = overriddenMethod; - CommentHelper ch = getInheritedInlineTags(inheritedSearchInput); - if (!ch.isSimpleOverride()) { - output = output.inherit(ch); - } - } - - TypeElement encl = utils.getEnclosingTypeElement(input.element); - List implementedMethods = utils.getImplementedMethods(input.element.toString(), encl, new ArrayList()); - for (Element implementedMethod : implementedMethods) { - inheritedSearchInput.element = implementedMethod; - CommentHelper ch = getInheritedInlineTags(inheritedSearchInput); - if (!ch.isSimpleOverride()) { - output = output.inherit(ch); - } - } - - return output; + TypeElement encl = utils.getEnclosingTypeElement(input.element); + List implementedMethods = + utils.getImplementedMethods(input.element.toString(), encl, new ArrayList()); + for (Element implementedMethod : implementedMethods) { + inheritedSearchInput.element = implementedMethod; + CommentHelper ch = getInheritedInlineTags(inheritedSearchInput); + if (!ch.isSimpleOverride()) { + output = output.inherit(ch); + } } - public String extractJavaType(Element element) { - if (element.getModifiers().contains(Modifier.STATIC)) { - if (element.getKind().equals(ElementKind.METHOD)) { - return "static method"; - } - if (element.getKind().equals(ElementKind.FIELD) || element.getKind().equals(ElementKind.ENUM_CONSTANT)) { - return "static field"; - } - } - return null; + return output; + } + + public String extractJavaType(Element element) { + if (element.getModifiers().contains(Modifier.STATIC)) { + if (element.getKind().equals(ElementKind.METHOD)) { + return "static method"; + } + if (element.getKind().equals(ElementKind.FIELD) + || element.getKind().equals(ElementKind.ENUM_CONSTANT)) { + return "static field"; + } } + return null; + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/lookup/ClassLookup.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/lookup/ClassLookup.java index 3f1fcd9a..5d3889f3 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/lookup/ClassLookup.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/lookup/ClassLookup.java @@ -5,16 +5,6 @@ import com.microsoft.model.TypeParameter; import com.microsoft.util.ElementUtil; import com.microsoft.util.Utils; -import java.util.Collections; -import jdk.javadoc.doclet.DocletEnvironment; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; - -import javax.lang.model.element.Element; -import javax.lang.model.element.ElementKind; -import javax.lang.model.element.TypeElement; -import javax.lang.model.type.TypeKind; -import javax.lang.model.type.TypeMirror; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -22,199 +12,225 @@ import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; +import javax.lang.model.element.Element; +import javax.lang.model.element.ElementKind; +import javax.lang.model.element.TypeElement; +import javax.lang.model.type.TypeKind; +import javax.lang.model.type.TypeMirror; +import jdk.javadoc.doclet.DocletEnvironment; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; public class ClassLookup extends BaseLookup { - private static final String JAVA_LANG_OBJECT = "java.lang.Object"; - - private final ElementUtil elementUtil; - - public ClassLookup(DocletEnvironment environment, ElementUtil elementUtil) { - super(environment); - this.elementUtil = elementUtil; - } - - @Override - protected ExtendedMetadataFileItem buildMetadataFileItem(TypeElement classElement) { - List inheritedMethods = new ArrayList<>(); - - String packageName = determinePackageName(classElement); - String classQName = String.valueOf(classElement.getQualifiedName()); - String classSName = String.valueOf(classElement.getSimpleName()); - String classQNameWithGenericsSupport = String.valueOf(classElement.asType()); - String classSNameWithGenericsSupport = classQNameWithGenericsSupport.replace(packageName.concat("."), ""); - - ExtendedMetadataFileItem result = new ExtendedMetadataFileItem(classQName); - result.setId(classSName); - result.setParent(packageName); - result.setHref(classQName + ".yml"); - result.setName(classSNameWithGenericsSupport); - result.setNameWithType(classSNameWithGenericsSupport); - result.setFullName(classQNameWithGenericsSupport); - result.setType(determineType(classElement)); - result.setPackageName(packageName); - result.setSummary(determineComment(classElement)); - result.setSuperclass(determineNestedSuperclass(classElement, result, inheritedMethods)); - result.setTypeParameters(determineTypeParameters(classElement)); - result.setInheritedMethods(determineInheritedMembers(inheritedMethods)); - result.setJavaType(extractJavaType(classElement)); - populateContent(classElement, classSNameWithGenericsSupport, result); - result.setTocName(classQName.replace(packageName.concat("."), "")); - return result; - } - - void populateContent(TypeElement classElement, String shortNameWithGenericsSupport, - ExtendedMetadataFileItem container) { - String type = elementKindLookup.get(classElement.getKind()); - String result = String.format("%s %s %s", - classElement.getModifiers().stream().map(String::valueOf) + private static final String JAVA_LANG_OBJECT = "java.lang.Object"; + + private final ElementUtil elementUtil; + + public ClassLookup(DocletEnvironment environment, ElementUtil elementUtil) { + super(environment); + this.elementUtil = elementUtil; + } + + @Override + protected ExtendedMetadataFileItem buildMetadataFileItem(TypeElement classElement) { + List inheritedMethods = new ArrayList<>(); + + String packageName = determinePackageName(classElement); + String classQName = String.valueOf(classElement.getQualifiedName()); + String classSName = String.valueOf(classElement.getSimpleName()); + String classQNameWithGenericsSupport = String.valueOf(classElement.asType()); + String classSNameWithGenericsSupport = + classQNameWithGenericsSupport.replace(packageName.concat("."), ""); + + ExtendedMetadataFileItem result = new ExtendedMetadataFileItem(classQName); + result.setId(classSName); + result.setParent(packageName); + result.setHref(classQName + ".yml"); + result.setName(classSNameWithGenericsSupport); + result.setNameWithType(classSNameWithGenericsSupport); + result.setFullName(classQNameWithGenericsSupport); + result.setType(determineType(classElement)); + result.setPackageName(packageName); + result.setSummary(determineComment(classElement)); + result.setSuperclass(determineNestedSuperclass(classElement, result, inheritedMethods)); + result.setTypeParameters(determineTypeParameters(classElement)); + result.setInheritedMethods(determineInheritedMembers(inheritedMethods)); + result.setJavaType(extractJavaType(classElement)); + populateContent(classElement, classSNameWithGenericsSupport, result); + result.setTocName(classQName.replace(packageName.concat("."), "")); + return result; + } + + void populateContent( + TypeElement classElement, + String shortNameWithGenericsSupport, + ExtendedMetadataFileItem container) { + String type = elementKindLookup.get(classElement.getKind()); + String result = + String.format( + "%s %s %s", + classElement.getModifiers().stream() + .map(String::valueOf) .filter(modifier -> !("Interface".equals(type) && "abstract".equals(modifier))) - .filter(modifier -> !("Enum".equals(type) && ("static".equals(modifier) || "final".equals(modifier)))) + .filter( + modifier -> + !("Enum".equals(type) + && ("static".equals(modifier) || "final".equals(modifier)))) .collect(Collectors.joining(" ")), - StringUtils.lowerCase(type), shortNameWithGenericsSupport); + StringUtils.lowerCase(type), + shortNameWithGenericsSupport); - String superclass = determineSuperclass(classElement); - if (superclass != null && !JAVA_LANG_OBJECT.equals(superclass)) { - result += " extends " + makeTypeShort(superclass); + String superclass = determineSuperclass(classElement); + if (superclass != null && !JAVA_LANG_OBJECT.equals(superclass)) { + result += " extends " + makeTypeShort(superclass); - addSuperclassToReferencesMap(superclass, container); - } - - List interfaces = classElement.getInterfaces(); - if (CollectionUtils.isNotEmpty(interfaces)) { - String prefix = (classElement.getKind() == ElementKind.INTERFACE) ? " extends " : " implements "; - result += prefix + interfaces.stream().map(String::valueOf).map(this::makeTypeShort) - .collect(Collectors.joining(", ")); - - container.setInterfaces(interfaces.stream() - .map(String::valueOf) - .collect(Collectors.toList())); - - addInterfacesToReferencesMap(interfaces, container); - - } - addInheritedMethodsToReferencesMap(container); - container.setContent(result); + addSuperclassToReferencesMap(superclass, container); } - void addSuperclassToReferencesMap(String superclass, ExtendedMetadataFileItem container) { - container.addReferences(Set.of(new MetadataFileItem(superclass, makeTypeShort(superclass), false))); + List interfaces = classElement.getInterfaces(); + if (CollectionUtils.isNotEmpty(interfaces)) { + String prefix = + (classElement.getKind() == ElementKind.INTERFACE) ? " extends " : " implements "; + result += + prefix + + interfaces.stream() + .map(String::valueOf) + .map(this::makeTypeShort) + .collect(Collectors.joining(", ")); + + container.setInterfaces( + interfaces.stream().map(String::valueOf).collect(Collectors.toList())); + + addInterfacesToReferencesMap(interfaces, container); } - - void addInheritedMethodsToReferencesMap(ExtendedMetadataFileItem container) { - container.addReferences(container.getInheritedMethods().stream() + addInheritedMethodsToReferencesMap(container); + container.setContent(result); + } + + void addSuperclassToReferencesMap(String superclass, ExtendedMetadataFileItem container) { + container.addReferences( + Set.of(new MetadataFileItem(superclass, makeTypeShort(superclass), false))); + } + + void addInheritedMethodsToReferencesMap(ExtendedMetadataFileItem container) { + container.addReferences( + container.getInheritedMethods().stream() .map(o -> new MetadataFileItem(o, makeTypeShort(o), false)) - .collect(Collectors.toSet()) - ); - } + .collect(Collectors.toSet())); + } - void addInterfacesToReferencesMap(List interfaces, ExtendedMetadataFileItem container) { - container.addReferences(interfaces.stream() + void addInterfacesToReferencesMap( + List interfaces, ExtendedMetadataFileItem container) { + container.addReferences( + interfaces.stream() .map(String::valueOf) .map(o -> new MetadataFileItem(o, makeTypeShort(o), false)) - .collect(Collectors.toSet()) - ); - } + .collect(Collectors.toSet())); + } - String determineSuperclass(TypeElement classElement) { - TypeMirror superclass = classElement.getSuperclass(); - if (superclass.getKind() == TypeKind.NONE) { - return null; - } - return String.valueOf(superclass); + String determineSuperclass(TypeElement classElement) { + TypeMirror superclass = classElement.getSuperclass(); + if (superclass.getKind() == TypeKind.NONE) { + return null; } + return String.valueOf(superclass); + } - List determineNestedSuperclass(TypeElement classElement, ExtendedMetadataFileItem result, List inheritedMethods) { - List nestedList = new ArrayList<>(); + List determineNestedSuperclass( + TypeElement classElement, + ExtendedMetadataFileItem result, + List inheritedMethods) { + List nestedList = new ArrayList<>(); - if (result.getSuperclass() != null) { - nestedList = result.getSuperclass(); - } + if (result.getSuperclass() != null) { + nestedList = result.getSuperclass(); + } - TypeMirror superclass = classElement.getSuperclass(); - if (superclass.getKind() != TypeKind.NONE) { - TypeElement superClassElement = (TypeElement) environment.getTypeUtils().asElement(superclass); + TypeMirror superclass = classElement.getSuperclass(); + if (superclass.getKind() != TypeKind.NONE) { + TypeElement superClassElement = + (TypeElement) environment.getTypeUtils().asElement(superclass); - nestedList.add(superClassElement.getQualifiedName().toString()); - result.setSuperclass(nestedList); - appendInheritedMethods(superClassElement, inheritedMethods); + nestedList.add(superClassElement.getQualifiedName().toString()); + result.setSuperclass(nestedList); + appendInheritedMethods(superClassElement, inheritedMethods); - determineNestedSuperclass(superClassElement, result, inheritedMethods); - } - return nestedList; + determineNestedSuperclass(superClassElement, result, inheritedMethods); } - - List determineTypeParameters(TypeElement element) { - return element.getTypeParameters().stream() - .map(typeParameter -> new TypeParameter(String.valueOf(typeParameter))) - .collect(Collectors.toList()); + return nestedList; + } + + List determineTypeParameters(TypeElement element) { + return element.getTypeParameters().stream() + .map(typeParameter -> new TypeParameter(String.valueOf(typeParameter))) + .collect(Collectors.toList()); + } + + void appendInheritedMethods( + TypeElement element, List inheritedMethods) { + List members = elementUtil.getEnclosedElements(element); + Integer level = Optional.ofNullable(getMaxNestedLevel(inheritedMethods)).orElse(0); + + for (Element m : members) { + if (m.getKind() == ElementKind.METHOD && !Utils.isPrivateOrPackagePrivate(m)) { + String uid = element.getQualifiedName().toString().concat(".") + String.valueOf(m); + + ExtendedMetadataFileItem item = new ExtendedMetadataFileItem(uid); + item.setName(String.valueOf(m)); + item.setNestedLevel(level + 1); + + inheritedMethods.add(item); + } } + } - void appendInheritedMethods(TypeElement element, List inheritedMethods) { - List members = elementUtil.getEnclosedElements(element); - Integer level = Optional.ofNullable(getMaxNestedLevel(inheritedMethods)) - .orElse(0); - - for (Element m : members) { - if (m.getKind() == ElementKind.METHOD && !Utils.isPrivateOrPackagePrivate(m)) { - String uid = element.getQualifiedName().toString().concat(".") + String.valueOf(m); + Integer getMaxNestedLevel(List inheritedMethods) { + Integer level = 0; - ExtendedMetadataFileItem item = new ExtendedMetadataFileItem(uid); - item.setName(String.valueOf(m)); - item.setNestedLevel(level + 1); - - inheritedMethods.add(item); - } - } + if (inheritedMethods.size() > 0) { + level = + inheritedMethods.stream() + .mapToInt(v -> v.getNestedLevel()) + .max() + .orElseThrow(NoSuchElementException::new); } - - Integer getMaxNestedLevel(List inheritedMethods) { - Integer level = 0; - - if (inheritedMethods.size() > 0) { - level = inheritedMethods - .stream() - .mapToInt(v -> v.getNestedLevel()) - .max().orElseThrow(NoSuchElementException::new); + return level; + } + + List determineInheritedMembers(List inheritedMethods) { + + if (inheritedMethods.size() > 0) { + HashMap map = new HashMap<>(); + for (ExtendedMetadataFileItem item : inheritedMethods) { + String key = item.getName(); + + if (map.containsKey(key) && map.get(key).getNestedLevel() > item.getNestedLevel()) { + // child class will have smaller than superclass, we only need the nearest methods + // inherited with same signature + map.put(key, item); + } else if (!map.containsKey(key)) { + map.put(key, item); } - return level; - } + } + List methods = + map.values().stream().map(x -> x.getUid()).collect(Collectors.toList()); - List determineInheritedMembers(List inheritedMethods) { - - if (inheritedMethods.size() > 0) { - HashMap map = new HashMap<>(); - for (ExtendedMetadataFileItem item : inheritedMethods - ) { - String key = item.getName(); - - if (map.containsKey(key) && map.get(key).getNestedLevel() > item.getNestedLevel()) { - // child class will have smaller than superclass, we only need the nearest methods inherited with same signature - map.put(key, item); - } else if (!map.containsKey(key)) { - map.put(key, item); - } - } - List methods = map.values() - .stream() - .map(x -> x.getUid()) - .collect(Collectors.toList()); - - return methods; - } - return new ArrayList<>(); + return methods; } + return new ArrayList<>(); + } - public String extractJavaType(TypeElement element) { - String superClass = determineSuperclass(element); - if (superClass != null && superClass.contains("Exception")) { - return "exception"; - } + public String extractJavaType(TypeElement element) { + String superClass = determineSuperclass(element); + if (superClass != null && superClass.contains("Exception")) { + return "exception"; + } - String javatype = element.getKind().name().toLowerCase().replaceAll("_",""); - if (javatype.equals("annotationtype")){ - return javatype; - } - return null; + String javatype = element.getKind().name().toLowerCase().replaceAll("_", ""); + if (javatype.equals("annotationtype")) { + return javatype; } -} \ No newline at end of file + return null; + } +} diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/lookup/PackageLookup.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/lookup/PackageLookup.java index 8f939d49..a5953895 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/lookup/PackageLookup.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/lookup/PackageLookup.java @@ -2,54 +2,53 @@ import com.microsoft.lookup.model.ExtendedMetadataFileItem; import com.microsoft.model.Status; -import jdk.javadoc.doclet.DocletEnvironment; - import javax.lang.model.element.PackageElement; +import jdk.javadoc.doclet.DocletEnvironment; public class PackageLookup extends BaseLookup { - public PackageLookup(DocletEnvironment environment) { - super(environment); + public PackageLookup(DocletEnvironment environment) { + super(environment); + } + + @Override + protected ExtendedMetadataFileItem buildMetadataFileItem(PackageElement packageElement) { + String qName = String.valueOf(packageElement.getQualifiedName()); + String sName = String.valueOf(packageElement.getSimpleName()); + + ExtendedMetadataFileItem result = new ExtendedMetadataFileItem(qName); + result.setId(sName); + result.setHref(qName + ".yml"); + result.setName(qName); + result.setNameWithType(qName); + result.setFullName(qName); + result.setType(determineType(packageElement)); + result.setJavaType(extractJavaType(packageElement)); + result.setSummary(determineComment(packageElement)); + result.setContent(determinePackageContent(packageElement)); + return result; + } + + public String extractStatus(PackageElement packageElement) { + String name = String.valueOf(packageElement.getQualifiedName()); + if (name.contains(Status.ALPHA.toString())) { + return Status.ALPHA.toString(); } - - @Override - protected ExtendedMetadataFileItem buildMetadataFileItem(PackageElement packageElement) { - String qName = String.valueOf(packageElement.getQualifiedName()); - String sName = String.valueOf(packageElement.getSimpleName()); - - ExtendedMetadataFileItem result = new ExtendedMetadataFileItem(qName); - result.setId(sName); - result.setHref(qName + ".yml"); - result.setName(qName); - result.setNameWithType(qName); - result.setFullName(qName); - result.setType(determineType(packageElement)); - result.setJavaType(extractJavaType(packageElement)); - result.setSummary(determineComment(packageElement)); - result.setContent(determinePackageContent(packageElement)); - return result; + if (name.contains(Status.BETA.toString())) { + return Status.BETA.toString(); } + return null; + } - public String extractStatus(PackageElement packageElement) { - String name = String.valueOf(packageElement.getQualifiedName()); - if (name.contains(Status.ALPHA.toString())) { - return Status.ALPHA.toString(); - } - if (name.contains(Status.BETA.toString())) { - return Status.BETA.toString(); - } - return null; - } - - String determinePackageContent(PackageElement packageElement) { - return "package " + packageElement.getQualifiedName(); - } + String determinePackageContent(PackageElement packageElement) { + return "package " + packageElement.getQualifiedName(); + } - public String extractJavaType(PackageElement element) { - String javaType = element.getKind().name().toLowerCase(); - if (javaType.equals("package")) { - return javaType; - } - return null; + public String extractJavaType(PackageElement element) { + String javaType = element.getKind().name().toLowerCase(); + if (javaType.equals("package")) { + return javaType; } + return null; + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/lookup/model/ExtendedMetadataFileItem.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/lookup/model/ExtendedMetadataFileItem.java index dea5e61a..c4238280 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/lookup/model/ExtendedMetadataFileItem.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/lookup/model/ExtendedMetadataFileItem.java @@ -8,112 +8,114 @@ import java.util.List; import java.util.Set; -/** - * Just container to keep cached precalculated values for lookup - */ +/** Just container to keep cached precalculated values for lookup */ public class ExtendedMetadataFileItem extends MetadataFileItem { - private String methodContent; - private String fieldContent; - private String constructorContent; - private List parameters; - private Return returnValue; - private String content; - private List typeParameters; - private List superclass; - private String tocName; - private Set references = new LinkedHashSet<>(); - private Integer nestedLevel; - - public ExtendedMetadataFileItem(String uid) { - super(uid); - } - - public String getMethodContent() { - return methodContent; - } - - public void setMethodContent(String methodContent) { - this.methodContent = methodContent; - } - - public String getFieldContent() { - return fieldContent; - } - - public void setFieldContent(String fieldContent) { - this.fieldContent = fieldContent; - } - - public String getConstructorContent() { - return constructorContent; - } - - public void setConstructorContent(String constructorContent) { - this.constructorContent = constructorContent; - } - - public List getParameters() { - return parameters; - } - - public Integer getNestedLevel() {return nestedLevel;} - - public void setNestedLevel(Integer level) {this.nestedLevel = level;} - - @Override - public void setParameters(List parameters) { - this.parameters = parameters; - } - - public Return getReturn() { - return returnValue; - } - - @Override - public void setReturn(Return returnValue) { - this.returnValue = returnValue; - } - - public String getContent() { - return content; - } - - @Override - public void setContent(String content) { - this.content = content; - } - - public List getTypeParameters() { - return typeParameters; - } - - @Override - public void setTypeParameters(List typeParameters) { - this.typeParameters = typeParameters; - } - - public List getSuperclass() { - return superclass; - } - - public void setSuperclass(List superclass) { - this.superclass = superclass; - } - - public void setTocName(String tocName) { - this.tocName = tocName; - } - - public String getTocName() { - return tocName; - } - - public void addReferences(Set references) { - this.references.addAll(references); - } - - public Set getReferences() { - return references; - } + private String methodContent; + private String fieldContent; + private String constructorContent; + private List parameters; + private Return returnValue; + private String content; + private List typeParameters; + private List superclass; + private String tocName; + private Set references = new LinkedHashSet<>(); + private Integer nestedLevel; + + public ExtendedMetadataFileItem(String uid) { + super(uid); + } + + public String getMethodContent() { + return methodContent; + } + + public void setMethodContent(String methodContent) { + this.methodContent = methodContent; + } + + public String getFieldContent() { + return fieldContent; + } + + public void setFieldContent(String fieldContent) { + this.fieldContent = fieldContent; + } + + public String getConstructorContent() { + return constructorContent; + } + + public void setConstructorContent(String constructorContent) { + this.constructorContent = constructorContent; + } + + public List getParameters() { + return parameters; + } + + public Integer getNestedLevel() { + return nestedLevel; + } + + public void setNestedLevel(Integer level) { + this.nestedLevel = level; + } + + @Override + public void setParameters(List parameters) { + this.parameters = parameters; + } + + public Return getReturn() { + return returnValue; + } + + @Override + public void setReturn(Return returnValue) { + this.returnValue = returnValue; + } + + public String getContent() { + return content; + } + + @Override + public void setContent(String content) { + this.content = content; + } + + public List getTypeParameters() { + return typeParameters; + } + + @Override + public void setTypeParameters(List typeParameters) { + this.typeParameters = typeParameters; + } + + public List getSuperclass() { + return superclass; + } + + public void setSuperclass(List superclass) { + this.superclass = superclass; + } + + public void setTocName(String tocName) { + this.tocName = tocName; + } + + public String getTocName() { + return tocName; + } + + public void addReferences(Set references) { + this.references.addAll(references); + } + + public Set getReferences() { + return references; + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/ExceptionItem.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/ExceptionItem.java index b833f6bd..2fda6b0f 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/ExceptionItem.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/ExceptionItem.java @@ -2,19 +2,19 @@ public class ExceptionItem { - private final String type; - private final String description; + private final String type; + private final String description; - public ExceptionItem(String type, String description) { - this.type = type; - this.description = description; - } + public ExceptionItem(String type, String description) { + this.type = type; + this.description = description; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/Guide.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/Guide.java index 55708f69..ebd071ce 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/Guide.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/Guide.java @@ -24,19 +24,19 @@ // name: name, // uid: package.name,...]] public class Guide { - private final String name; - private final String href; + private final String name; + private final String href; - public Guide(String name, String href) { - this.name = name; - this.href = href; - } + public Guide(String name, String href) { + this.name = name; + this.href = href; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public String getHref() { - return href; - } -} \ No newline at end of file + public String getHref() { + return href; + } +} diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/KindTitle.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/KindTitle.java index b098336c..65f438a7 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/KindTitle.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/KindTitle.java @@ -16,13 +16,19 @@ package com.microsoft.model; public class KindTitle { - private final String elementKind; - private final String title; + private final String elementKind; + private final String title; - public KindTitle(String elementKind, String title) { - this.elementKind = elementKind; - this.title = title; - } - public String getElementKind() { return elementKind; } - public String getTitle() { return title; } + public KindTitle(String elementKind, String title) { + this.elementKind = elementKind; + this.title = title; + } + + public String getElementKind() { + return elementKind; + } + + public String getTitle() { + return title; + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/MetadataFile.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/MetadataFile.java index 15e7ebe6..c47de634 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/MetadataFile.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/MetadataFile.java @@ -2,7 +2,6 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.microsoft.util.YamlUtil; - import java.io.File; import java.util.LinkedHashSet; import java.util.Set; @@ -10,45 +9,45 @@ public class MetadataFile implements YmlFile { - private final static String METADATA_FILE_HEADER = "### YamlMime:ManagedReference\n"; - private final String outputPath; - private String fileName; - private Set items = new LinkedHashSet<>(); - private Set references = new LinkedHashSet<>(); - - public MetadataFile(String outputPath, String fileName) { - this.outputPath = outputPath; - this.fileName = fileName; - } - - public Set getItems() { - return items; - } - - public Set getReferences() { - return references; - } - - @JsonIgnore - @Override - public String getFileContent() { - Set sortedSet = new TreeSet<>(this.items); - this.items = sortedSet; - return METADATA_FILE_HEADER + YamlUtil.objectToYamlString(this); - } - - @JsonIgnore - @Override - public String getFileNameWithPath() { - return outputPath + File.separator + fileName; - } - - @JsonIgnore - public String getFileName() { - return fileName; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } + private static final String METADATA_FILE_HEADER = "### YamlMime:ManagedReference\n"; + private final String outputPath; + private String fileName; + private Set items = new LinkedHashSet<>(); + private Set references = new LinkedHashSet<>(); + + public MetadataFile(String outputPath, String fileName) { + this.outputPath = outputPath; + this.fileName = fileName; + } + + public Set getItems() { + return items; + } + + public Set getReferences() { + return references; + } + + @JsonIgnore + @Override + public String getFileContent() { + Set sortedSet = new TreeSet<>(this.items); + this.items = sortedSet; + return METADATA_FILE_HEADER + YamlUtil.objectToYamlString(this); + } + + @JsonIgnore + @Override + public String getFileNameWithPath() { + return outputPath + File.separator + fileName; + } + + @JsonIgnore + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/MetadataFileItem.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/MetadataFileItem.java index a608148c..90192004 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/MetadataFileItem.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/MetadataFileItem.java @@ -2,282 +2,318 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.apache.commons.lang3.RegExUtils; - import java.util.ArrayList; import java.util.Collections; import java.util.List; +import org.apache.commons.lang3.RegExUtils; -@JsonPropertyOrder({"uid", "id", "parent", "children", "href", "langs", "isExternal", "name", "nameWithType", - "fullName", "overload", "overridden", "type", "javatype", "package", "summary", "syntax", "inheritance", "implements", "exceptions", - "spec.java", "inheritedMembers", "status"}) +@JsonPropertyOrder({ + "uid", + "id", + "parent", + "children", + "href", + "langs", + "isExternal", + "name", + "nameWithType", + "fullName", + "overload", + "overridden", + "type", + "javatype", + "package", + "summary", + "syntax", + "inheritance", + "implements", + "exceptions", + "spec.java", + "inheritedMembers", + "status" +}) public class MetadataFileItem implements Comparable { - private final String uid; - private String id; - private String parent; - private List children = new ArrayList<>(); - private String href; - private String[] langs; - private String name; - private String nameWithType; - private String fullName; - private String overload; - private String overridden; - private String type; - private String javatype; - @JsonProperty("package") - private String packageName; - private String summary; - private Syntax syntax; - private List inheritance; - @JsonProperty("implements") - private List interfaces; - private List exceptions; - private boolean isExternal; - @JsonProperty("spec.java") - private List specForJava = new ArrayList<>(); - @JsonProperty("inheritedMembers") - private List inheritedMethods = new ArrayList<>(); - private String status; - - @Override - public int compareTo(MetadataFileItem item) { - return this.getUid().compareTo(item.getUid()); - } + private final String uid; + private String id; + private String parent; + private List children = new ArrayList<>(); + private String href; + private String[] langs; + private String name; + private String nameWithType; + private String fullName; + private String overload; + private String overridden; + private String type; + private String javatype; + + @JsonProperty("package") + private String packageName; + + private String summary; + private Syntax syntax; + private List inheritance; + + @JsonProperty("implements") + private List interfaces; + + private List exceptions; + private boolean isExternal; + + @JsonProperty("spec.java") + private List specForJava = new ArrayList<>(); + + @JsonProperty("inheritedMembers") + private List inheritedMethods = new ArrayList<>(); + + private String status; + + @Override + public int compareTo(MetadataFileItem item) { + return this.getUid().compareTo(item.getUid()); + } + + public MetadataFileItem(String[] langs, String uid) { + this(uid); + this.langs = langs; + } + + public MetadataFileItem(String uid) { + this.uid = uid; + } + + public MetadataFileItem(String uid, String name, boolean isExternal) { + this(uid); + this.name = name; + this.nameWithType = name; + this.fullName = uid; + this.isExternal = isExternal; + } + + public MetadataFileItem(String uid, List specs) { + this(uid); + this.specForJava = specs; + } + + public String getUid() { + return uid; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getParent() { + return parent; + } + + public void setParent(String parent) { + this.parent = parent; + } + + public List getChildren() { + Collections.sort(children); + return children; + } + + public String getHref() { + return href; + } + + public void setHref(String href) { + this.href = href; + } + + public String[] getLangs() { + return langs; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getNameWithType() { + return nameWithType; + } - public MetadataFileItem(String[] langs, String uid) { - this(uid); - this.langs = langs; - } + public void setNameWithType(String nameWithType) { + this.nameWithType = nameWithType; + } - public MetadataFileItem(String uid) { - this.uid = uid; - } + public String getFullName() { + return fullName; + } - public MetadataFileItem(String uid, String name, boolean isExternal) { - this(uid); - this.name = name; - this.nameWithType = name; - this.fullName = uid; - this.isExternal = isExternal; - } + public void setFullName(String fullName) { + this.fullName = fullName; + } - public MetadataFileItem(String uid, List specs) { - this(uid); - this.specForJava = specs; - } + public String getOverload() { + return overload; + } - public String getUid() { - return uid; - } + public void setOverload(String overload) { + this.overload = handleGenericForOverLoad(overload); + } + + public String getType() { + return type; + } - public String getId() { - return id; - } + public String getJavaType() { + return javatype; + } - public void setId(String id) { - this.id = id; - } + public void setType(String type) { + this.type = type; + } - public String getParent() { - return parent; - } + public void setJavaType(String javaType) { + this.javatype = javaType; + } + + public String getPackageName() { + return packageName; + } - public void setParent(String parent) { - this.parent = parent; - } + public void setPackageName(String packageName) { + this.packageName = packageName; + } - public List getChildren() { - Collections.sort(children); - return children; - } + public String getSummary() { + return summary; + } - public String getHref() { - return href; - } + public void setSummary(String summary) { + this.summary = summary; + } - public void setHref(String href) { - this.href = href; - } + public Syntax getSyntax() { + return syntax; + } - public String[] getLangs() { - return langs; - } + public void setSyntax(Syntax syntax) { + this.syntax = syntax; + } - public String getName() { - return name; - } + public List getInheritance() { + return inheritance; + } - public void setName(String name) { - this.name = name; - } + public void setInheritance(List superclass) { + this.inheritance = (superclass == null) ? null : superclass; + } - public String getNameWithType() { - return nameWithType; - } + public List getInterfaces() { + return interfaces; + } - public void setNameWithType(String nameWithType) { - this.nameWithType = nameWithType; - } + public void setInheritedMethods(List inheritedMethods) { + this.inheritedMethods = (inheritedMethods == null) ? null : inheritedMethods; + } - public String getFullName() { - return fullName; - } + public List getInheritedMethods() { + return inheritedMethods; + } - public void setFullName(String fullName) { - this.fullName = fullName; - } + public List getSpecForJava() { + return specForJava; + } - public String getOverload() { - return overload; - } + public void setInterfaces(List interfaces) { + this.interfaces = interfaces; + } - public void setOverload(String overload) { - this.overload = handleGenericForOverLoad(overload); - } + public List getExceptions() { + return exceptions; + } - public String getType() { - return type; - } + public void setExceptions(List exceptions) { + this.exceptions = exceptions; + } - public String getJavaType() { - return javatype; + public void setContent(String content) { + if (syntax == null) { + syntax = new Syntax(); } + syntax.setContent(content); + } - public void setType(String type) { - this.type = type; + public void setTypeParameters(List typeParameters) { + if (syntax == null) { + syntax = new Syntax(); } + syntax.setTypeParameters(typeParameters); + } - public void setJavaType(String javaType) { - this.javatype = javaType; + public void setParameters(List parameters) { + if (syntax == null) { + syntax = new Syntax(); } + syntax.setParameters(parameters); + } - public String getPackageName() { - return packageName; + public void setReturn(Return returnValue) { + if (syntax == null) { + syntax = new Syntax(); } + syntax.setReturnValue(returnValue); + } - public void setPackageName(String packageName) { - this.packageName = packageName; - } + public void setOverridden(String overridden) { + this.overridden = overridden; + } - public String getSummary() { - return summary; - } + public String getOverridden() { + return overridden; + } - public void setSummary(String summary) { - this.summary = summary; + @Override + public boolean equals(Object o) { + if (this == o) { + return true; } - public Syntax getSyntax() { - return syntax; + if (o == null || getClass() != o.getClass()) { + return false; } - public void setSyntax(Syntax syntax) { - this.syntax = syntax; - } + MetadataFileItem that = (MetadataFileItem) o; - public List getInheritance() { - return inheritance; - } + return uid.equals(that.uid); + } - public void setInheritance(List superclass) { - this.inheritance = (superclass == null) ? null : superclass; - } + @Override + public int hashCode() { + return uid.hashCode(); + } - public List getInterfaces() { - return interfaces; - } + public Boolean getIsExternal() { + return isExternal ? true : null; + } - public void setInheritedMethods(List inheritedMethods) { - this.inheritedMethods = (inheritedMethods == null) ? null : inheritedMethods; - } + public void setIsExternal(boolean external) { + isExternal = external; + } - public List getInheritedMethods() { - return inheritedMethods; - } - - public List getSpecForJava() { - return specForJava; - } - - public void setInterfaces(List interfaces) { - this.interfaces = interfaces; - } - - public List getExceptions() { - return exceptions; - } - - public void setExceptions(List exceptions) { - this.exceptions = exceptions; - } - - public void setContent(String content) { - if (syntax == null) { - syntax = new Syntax(); - } - syntax.setContent(content); - } - - public void setTypeParameters(List typeParameters) { - if (syntax == null) { - syntax = new Syntax(); - } - syntax.setTypeParameters(typeParameters); - } - - public void setParameters(List parameters) { - if (syntax == null) { - syntax = new Syntax(); - } - syntax.setParameters(parameters); - } - - public void setReturn(Return returnValue) { - if (syntax == null) { - syntax = new Syntax(); - } - syntax.setReturnValue(returnValue); - } - - public void setOverridden(String overridden) { - this.overridden = overridden; - } - - public String getOverridden() { - return overridden; - } - - @Override - public boolean equals(Object o) { - if (this == o) { return true; } - - if (o == null || getClass() != o.getClass()) { return false; } - - MetadataFileItem that = (MetadataFileItem) o; - - return uid.equals(that.uid); - } - - @Override - public int hashCode() { - return uid.hashCode(); - } - - public Boolean getIsExternal() { - return isExternal ? true : null; - } - - public void setIsExternal(boolean external) { - isExternal = external; - } - - public String handleGenericForOverLoad(String value) { - return RegExUtils.removeAll(value, "<\\w+(,\\s*\\w+)*>"); - } + public String handleGenericForOverLoad(String value) { + return RegExUtils.removeAll(value, "<\\w+(,\\s*\\w+)*>"); + } - public String getStatus() { return status; } + public String getStatus() { + return status; + } - public void setStatus(String status) { this.status = status; } + public void setStatus(String status) { + this.status = status; + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/MethodParameter.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/MethodParameter.java index 2c6d5c05..981805a0 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/MethodParameter.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/MethodParameter.java @@ -2,29 +2,29 @@ public class MethodParameter { - private final String id; - private final String type; - private String description; + private final String id; + private final String type; + private String description; - public MethodParameter(String id, String type, String description) { - this.id = id; - this.type = type; - this.description = description; - } + public MethodParameter(String id, String type, String description) { + this.id = id; + this.type = type; + this.description = description; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/ProjectContents.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/ProjectContents.java index 629110ff..b2263df4 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/ProjectContents.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/ProjectContents.java @@ -21,19 +21,19 @@ // wraps guides + tocItems with product name hierarchy // [name: project-name, [items: [...]]] public class ProjectContents { - private final String name; - private final List items; + private final String name; + private final List items; - public ProjectContents(String name, List items) { - this.name = name; - this.items = items; - } + public ProjectContents(String name, List items) { + this.name = name; + this.items = items; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public List getItems() { - return items; - } -} \ No newline at end of file + public List getItems() { + return items; + } +} diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/Return.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/Return.java index 712c2828..7872bc0b 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/Return.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/Return.java @@ -4,29 +4,30 @@ public class Return { - @JsonProperty("type") - private final String returnType; - @JsonProperty("description") - private String returnDescription; - - public Return(String returnType, String returnDescription) { - this.returnType = returnType; - this.returnDescription = returnDescription; - } - - public Return(String returnType) { - this.returnType = returnType; - } - - public String getReturnType() { - return returnType; - } - - public String getReturnDescription() { - return returnDescription; - } - - public void setReturnDescription(String returnDescription) { - this.returnDescription = returnDescription; - } + @JsonProperty("type") + private final String returnType; + + @JsonProperty("description") + private String returnDescription; + + public Return(String returnType, String returnDescription) { + this.returnType = returnType; + this.returnDescription = returnDescription; + } + + public Return(String returnType) { + this.returnType = returnType; + } + + public String getReturnType() { + return returnType; + } + + public String getReturnDescription() { + return returnDescription; + } + + public void setReturnDescription(String returnDescription) { + this.returnDescription = returnDescription; + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/SpecViewModel.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/SpecViewModel.java index 999e642c..654d4cb1 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/SpecViewModel.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/SpecViewModel.java @@ -1,64 +1,63 @@ package com.microsoft.model; import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.apache.commons.lang3.StringUtils; - import java.util.*; +import org.apache.commons.lang3.StringUtils; @JsonPropertyOrder({"uid", "name", "fullName", "isExternal", "href"}) public class SpecViewModel { - private String uid; - private String name; - private String fullName; - private boolean isExternal; - private String href; - - public SpecViewModel(String uid, String fullName) { - this.uid = uid; - this.name = getShortName(fullName); - this.fullName = fullName; - } - - public String getUid() { - return uid; - } - - public String getName() { - return name; - } - - public String getFullName() { - return fullName; - } - - String getShortName(String fullName) { - - StringBuilder singleValue = new StringBuilder(); - Optional.ofNullable(fullName).ifPresent( - Param -> { - List strList = new ArrayList<>(); - strList = Arrays.asList(StringUtils.split(Param, ".")); - Collections.reverse(strList); - singleValue.append(strList.get(0)); - } - ); - return singleValue.toString(); - } - - public void setIsExternal(boolean isExternal) { - this.isExternal = isExternal; - } - - public boolean getIsExternal() { - return isExternal; - } - - public void setHref(String href) { - this.href = href; - } - - public String getHref() { - return href; - } + private String uid; + private String name; + private String fullName; + private boolean isExternal; + private String href; + + public SpecViewModel(String uid, String fullName) { + this.uid = uid; + this.name = getShortName(fullName); + this.fullName = fullName; + } + + public String getUid() { + return uid; + } + + public String getName() { + return name; + } + + public String getFullName() { + return fullName; + } + + String getShortName(String fullName) { + + StringBuilder singleValue = new StringBuilder(); + Optional.ofNullable(fullName) + .ifPresent( + Param -> { + List strList = new ArrayList<>(); + strList = Arrays.asList(StringUtils.split(Param, ".")); + Collections.reverse(strList); + singleValue.append(strList.get(0)); + }); + return singleValue.toString(); + } + + public void setIsExternal(boolean isExternal) { + this.isExternal = isExternal; + } + + public boolean getIsExternal() { + return isExternal; + } + + public void setHref(String href) { + this.href = href; + } + + public String getHref() { + return href; + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/Status.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/Status.java index c70600dd..1ca7ea0e 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/Status.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/Status.java @@ -17,10 +17,12 @@ package com.microsoft.model; public enum Status { - DEPRECATED, ALPHA, BETA; + DEPRECATED, + ALPHA, + BETA; - @Override - public String toString() { - return name().toLowerCase(); - } + @Override + public String toString() { + return name().toLowerCase(); + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/Syntax.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/Syntax.java index d7a84acc..f5bfcf04 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/Syntax.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/Syntax.java @@ -1,46 +1,47 @@ package com.microsoft.model; import com.fasterxml.jackson.annotation.JsonProperty; - import java.util.List; public class Syntax { - private String content; - private List parameters; - @JsonProperty("return") - private Return returnValue; - private List typeParameters; + private String content; + private List parameters; + + @JsonProperty("return") + private Return returnValue; + + private List typeParameters; - public String getContent() { - return content; - } + public String getContent() { + return content; + } - public void setContent(String content) { - this.content = content; - } + public void setContent(String content) { + this.content = content; + } - public List getParameters() { - return parameters; - } + public List getParameters() { + return parameters; + } - public void setParameters(List parameters) { - this.parameters = parameters; - } + public void setParameters(List parameters) { + this.parameters = parameters; + } - public Return getReturnValue() { - return returnValue; - } + public Return getReturnValue() { + return returnValue; + } - public void setReturnValue(Return returnValue) { - this.returnValue = returnValue; - } + public void setReturnValue(Return returnValue) { + this.returnValue = returnValue; + } - public List getTypeParameters() { - return typeParameters; - } + public List getTypeParameters() { + return typeParameters; + } - public void setTypeParameters(List typeParameters) { - this.typeParameters = typeParameters; - } + public void setTypeParameters(List typeParameters) { + this.typeParameters = typeParameters; + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/TocContents.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/TocContents.java index cd8e4ceb..eaeb01fa 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/TocContents.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/TocContents.java @@ -20,37 +20,38 @@ import java.util.List; public class TocContents { - private final String projectName; - private final List contents = new ArrayList<>(); - - public TocContents(String projectName, boolean disableChangelog, List items) { - this.projectName = projectName; - - if (projectName == null || projectName.equals("")) { - contents.addAll(items); - } else { - // only include product hierarchy and guides if projectName included - createTocContents(projectName, disableChangelog, items); - } - } + private final String projectName; + private final List contents = new ArrayList<>(); - private void createTocContents(String projectName, boolean disableChangelog, List items) { - List tocItems = new ArrayList<>(); - // combine guides and tocItems - tocItems.add(new Guide("Overview", "overview.html")); - if (!disableChangelog) { - tocItems.add(new Guide("Version history", "history.md")); - } - tocItems.addAll(items); - // wrap guides + tocItems with product hierarchy - contents.add(new ProjectContents(projectName, tocItems)); - } + public TocContents(String projectName, boolean disableChangelog, List items) { + this.projectName = projectName; - public List getContents() { - return contents; + if (projectName == null || projectName.equals("")) { + contents.addAll(items); + } else { + // only include product hierarchy and guides if projectName included + createTocContents(projectName, disableChangelog, items); } - - public String getProjectName() { - return projectName; + } + + private void createTocContents( + String projectName, boolean disableChangelog, List items) { + List tocItems = new ArrayList<>(); + // combine guides and tocItems + tocItems.add(new Guide("Overview", "overview.html")); + if (!disableChangelog) { + tocItems.add(new Guide("Version history", "history.md")); } -} \ No newline at end of file + tocItems.addAll(items); + // wrap guides + tocItems with product hierarchy + contents.add(new ProjectContents(projectName, tocItems)); + } + + public List getContents() { + return contents; + } + + public String getProjectName() { + return projectName; + } +} diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/TocFile.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/TocFile.java index e32af29b..765c015a 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/TocFile.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/TocFile.java @@ -1,7 +1,6 @@ package com.microsoft.model; import com.microsoft.util.YamlUtil; - import java.io.File; import java.util.ArrayList; import java.util.Collections; @@ -10,35 +9,35 @@ public class TocFile extends ArrayList implements YmlFile { - private final static String TOC_FILE_HEADER = "### YamlMime:TableOfContent\n"; - private final static String TOC_FILE_NAME = "toc.yml"; - private final String outputPath; - private final String projectName; - private final boolean disableChangelog; - - public TocFile(String outputPath, String projectName, boolean disableChangelog) { - this.outputPath = outputPath; - this.projectName = projectName; - this.disableChangelog = disableChangelog; - } - - public void addTocItem(TocItem packageTocItem) { - add(packageTocItem); - } - - protected void sortByUid() { - Collections.sort(this, Comparator.comparing(TocItem::getUid)); - } - - @Override - public String getFileContent() { - sortByUid(); - List tocContents = new TocContents(projectName, disableChangelog, this).getContents(); - return TOC_FILE_HEADER + YamlUtil.objectToYamlString(tocContents); - } - - @Override - public String getFileNameWithPath() { - return outputPath + File.separator + TOC_FILE_NAME; - } + private static final String TOC_FILE_HEADER = "### YamlMime:TableOfContent\n"; + private static final String TOC_FILE_NAME = "toc.yml"; + private final String outputPath; + private final String projectName; + private final boolean disableChangelog; + + public TocFile(String outputPath, String projectName, boolean disableChangelog) { + this.outputPath = outputPath; + this.projectName = projectName; + this.disableChangelog = disableChangelog; + } + + public void addTocItem(TocItem packageTocItem) { + add(packageTocItem); + } + + protected void sortByUid() { + Collections.sort(this, Comparator.comparing(TocItem::getUid)); + } + + @Override + public String getFileContent() { + sortByUid(); + List tocContents = new TocContents(projectName, disableChangelog, this).getContents(); + return TOC_FILE_HEADER + YamlUtil.objectToYamlString(tocContents); + } + + @Override + public String getFileNameWithPath() { + return outputPath + File.separator + TOC_FILE_NAME; + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/TocItem.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/TocItem.java index bdbd3b43..948503e7 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/TocItem.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/TocItem.java @@ -5,41 +5,44 @@ public class TocItem { - private String uid; - private String name; - private String status; - private String heading; - private List items = new ArrayList<>(); - - - public TocItem(String uid, String name) { - this.uid = uid; - this.name = name; - } - - public TocItem(String uid, String name, String status) { - this.uid = uid; - this.name = name; - this.status = status; - } - - public TocItem(String heading) { - this.heading = heading; - } - - public String getUid() { - return uid; - } - - public String getName() { - return name; - } - - public List getItems() { - return items; - } - - public String getStatus() { return status; } - - public String getHeading() { return heading; } + private String uid; + private String name; + private String status; + private String heading; + private List items = new ArrayList<>(); + + public TocItem(String uid, String name) { + this.uid = uid; + this.name = name; + } + + public TocItem(String uid, String name, String status) { + this.uid = uid; + this.name = name; + this.status = status; + } + + public TocItem(String heading) { + this.heading = heading; + } + + public String getUid() { + return uid; + } + + public String getName() { + return name; + } + + public List getItems() { + return items; + } + + public String getStatus() { + return status; + } + + public String getHeading() { + return heading; + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/TocTypeMap.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/TocTypeMap.java index 55c470d6..7e8b9869 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/TocTypeMap.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/TocTypeMap.java @@ -15,29 +15,27 @@ */ package com.microsoft.model; -import org.apache.commons.lang3.tuple.Pair; - -import javax.lang.model.element.ElementKind; import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import javax.lang.model.element.ElementKind; public class TocTypeMap extends HashMap> { - public TocTypeMap() { - this.put(ElementKind.CLASS.name(), new ArrayList<>()); - this.put(ElementKind.INTERFACE.name(), new ArrayList<>()); - this.put(ElementKind.ENUM.name(), new ArrayList<>()); - this.put(ElementKind.ANNOTATION_TYPE.name(), new ArrayList<>()); - this.put("EXCEPTION", new ArrayList<>()); - } + public TocTypeMap() { + this.put(ElementKind.CLASS.name(), new ArrayList<>()); + this.put(ElementKind.INTERFACE.name(), new ArrayList<>()); + this.put(ElementKind.ENUM.name(), new ArrayList<>()); + this.put(ElementKind.ANNOTATION_TYPE.name(), new ArrayList<>()); + this.put("EXCEPTION", new ArrayList<>()); + } - public List getTitleList() { - return List.of( - new KindTitle(ElementKind.INTERFACE.name(), "Interfaces"), - new KindTitle(ElementKind.CLASS.name(), "Classes"), - new KindTitle(ElementKind.ENUM.name(), "Enums"), - new KindTitle(ElementKind.ANNOTATION_TYPE.name(),"Annotation Types"), - new KindTitle("EXCEPTION", "Exceptions")); - } + public List getTitleList() { + return List.of( + new KindTitle(ElementKind.INTERFACE.name(), "Interfaces"), + new KindTitle(ElementKind.CLASS.name(), "Classes"), + new KindTitle(ElementKind.ENUM.name(), "Enums"), + new KindTitle(ElementKind.ANNOTATION_TYPE.name(), "Annotation Types"), + new KindTitle("EXCEPTION", "Exceptions")); + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/TypeParameter.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/TypeParameter.java index df2a5a3c..557c61b1 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/TypeParameter.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/TypeParameter.java @@ -2,13 +2,13 @@ public class TypeParameter { - private final String id; + private final String id; - public TypeParameter(String id) { - this.id = id; - } + public TypeParameter(String id) { + this.id = id; + } - public String getId() { - return id; - } + public String getId() { + return id; + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/YmlFile.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/YmlFile.java index 63c7554d..6743acc7 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/YmlFile.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/YmlFile.java @@ -2,7 +2,7 @@ public interface YmlFile { - String getFileContent(); + String getFileContent(); - String getFileNameWithPath(); + String getFileNameWithPath(); } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/CommentHelper.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/CommentHelper.java index f5dc9fed..eac5d636 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/CommentHelper.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/CommentHelper.java @@ -1,88 +1,86 @@ package com.microsoft.util; import com.sun.source.doctree.DocTree; - -import javax.lang.model.element.Element; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; +import javax.lang.model.element.Element; public class CommentHelper { - public Element element; - public List inlineTags = Collections.emptyList(); - private Utils utils; - private boolean hasInheritDocTag = false; - - public CommentHelper(Element element, Utils utils) { - this.element = element; - this.utils = utils; - this.inlineTags = utils.getFullBody(element); - this.hasInheritDocTag = utils.hasInlineTag(inlineTags, DocTree.Kind.INHERIT_DOC); + public Element element; + public List inlineTags = Collections.emptyList(); + private Utils utils; + private boolean hasInheritDocTag = false; + + public CommentHelper(Element element, Utils utils) { + this.element = element; + this.utils = utils; + this.inlineTags = utils.getFullBody(element); + this.hasInheritDocTag = utils.hasInlineTag(inlineTags, DocTree.Kind.INHERIT_DOC); + } + + public CommentHelper(Element element, Utils utils, List inlineTags) { + this.element = element; + this.utils = utils; + this.inlineTags = inlineTags; + this.hasInheritDocTag = utils.hasInlineTag(inlineTags, DocTree.Kind.INHERIT_DOC); + } + + /** + * Returns true if the method has no comments, or a lone @inheritDoc. + * + * @return true if there are no comments, false otherwise + */ + public boolean isSimpleOverride() { + return inlineTags.isEmpty() || (inlineTags.size() == 1 && hasInheritDocTag); + } + + public boolean hasInheritDocTag() { + return this.hasInheritDocTag; + } + + public CommentHelper copy() { + if (this.element == null) { + throw new NullPointerException(); } + CommentHelper clone = new CommentHelper(this.element, this.utils); + return clone; + } - public CommentHelper(Element element, Utils utils, List inlineTags) { - this.element = element; - this.utils = utils; - this.inlineTags = inlineTags; - this.hasInheritDocTag = utils.hasInlineTag(inlineTags, DocTree.Kind.INHERIT_DOC); - } + public CommentHelper inherit(CommentHelper chInheritFrom) { + List mergedTags = new ArrayList<>(); - /** - * Returns true if the method has no comments, or a lone @inheritDoc. - * - * @return true if there are no comments, false otherwise - */ - public boolean isSimpleOverride() { - return inlineTags.isEmpty() || - (inlineTags.size() == 1 && hasInheritDocTag); + if (this.isSimpleOverride()) mergedTags = chInheritFrom.inlineTags; + else { + mergedTags = inheritInlineTags(this, chInheritFrom); } - public boolean hasInheritDocTag() { - return this.hasInheritDocTag; - } + return new CommentHelper(this.element, this.utils, mergedTags); + } - public CommentHelper copy() { - if (this.element == null) { - throw new NullPointerException(); - } - CommentHelper clone = new CommentHelper(this.element, this.utils); - return clone; + List inheritInlineTags(CommentHelper origin, CommentHelper chInheritFrom) { + List mergedTags = new ArrayList<>(); + if (!origin.isSimpleOverride() && !origin.hasInheritDocTag) { + return origin.inlineTags; } - public CommentHelper inherit(CommentHelper chInheritFrom) { - List mergedTags = new ArrayList<>(); + // Get the index of "{@inheritedDoc}". + int index = + origin.inlineTags.stream() + .map(e -> e.getKind()) + .collect(Collectors.toList()) + .indexOf(DocTree.Kind.INHERIT_DOC); - if (this.isSimpleOverride()) - mergedTags = chInheritFrom.inlineTags; - else { - mergedTags = inheritInlineTags(this, chInheritFrom); - } + // Replace the "{@inheritedDoc}" with inherited inlineTags. + mergedTags = origin.inlineTags.stream().collect(Collectors.toList()); + mergedTags.remove(index); - return new CommentHelper(this.element, this.utils, mergedTags); + for (DocTree d : chInheritFrom.inlineTags) { + mergedTags.add(index, d); + index++; } - List inheritInlineTags(CommentHelper origin, CommentHelper chInheritFrom) { - List mergedTags = new ArrayList<>(); - if (!origin.isSimpleOverride() && !origin.hasInheritDocTag) { - return origin.inlineTags; - } - - // Get the index of "{@inheritedDoc}". - int index = origin.inlineTags.stream().map(e -> e.getKind()) - .collect(Collectors.toList()) - .indexOf(DocTree.Kind.INHERIT_DOC); - - // Replace the "{@inheritedDoc}" with inherited inlineTags. - mergedTags = origin.inlineTags.stream().collect(Collectors.toList()); - mergedTags.remove(index); - - for (DocTree d : chInheritFrom.inlineTags - ) { - mergedTags.add(index, d); - index++; - } - - return mergedTags; - } + return mergedTags; + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/ElementUtil.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/ElementUtil.java index d594ba4f..1212ce08 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/ElementUtil.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/ElementUtil.java @@ -1,78 +1,82 @@ package com.microsoft.util; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import org.apache.commons.lang3.StringUtils; - -import javax.lang.model.element.Element; -import javax.lang.model.element.PackageElement; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.ElementFilter; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; +import javax.lang.model.element.Element; +import javax.lang.model.element.PackageElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.util.ElementFilter; +import org.apache.commons.lang3.StringUtils; public class ElementUtil { - private static final int INITIAL_CAPACITY = 1000000; - private final Set excludePackages = new HashSet<>(); - private final Set excludeClasses = new HashSet<>(); + private static final int INITIAL_CAPACITY = 1000000; + private final Set excludePackages = new HashSet<>(); + private final Set excludeClasses = new HashSet<>(); - private final Map> elementMap; - private final Map> elementSortedMap; + private final Map> elementMap; + private final Map> elementSortedMap; - public ElementUtil(String[] excludePackages, String[] excludeClasses) { - this.excludePackages.addAll(Stream.of(excludePackages) - .map(o -> Pattern.compile(o)).collect(Collectors.toSet())); - this.excludeClasses.addAll(Stream.of(excludeClasses) - .map(o -> Pattern.compile(o)).collect(Collectors.toSet())); - this.elementMap = new ConcurrentHashMap<>(INITIAL_CAPACITY); - this.elementSortedMap = new ConcurrentHashMap<>(INITIAL_CAPACITY); - } + public ElementUtil(String[] excludePackages, String[] excludeClasses) { + this.excludePackages.addAll( + Stream.of(excludePackages).map(o -> Pattern.compile(o)).collect(Collectors.toSet())); + this.excludeClasses.addAll( + Stream.of(excludeClasses).map(o -> Pattern.compile(o)).collect(Collectors.toSet())); + this.elementMap = new ConcurrentHashMap<>(INITIAL_CAPACITY); + this.elementSortedMap = new ConcurrentHashMap<>(INITIAL_CAPACITY); + } - public List extractSortedElements(Element element) { - elementSortedMap.computeIfAbsent(element, this::extractSortedElementsInternal); - return elementSortedMap.get(element); - } + public List extractSortedElements(Element element) { + elementSortedMap.computeIfAbsent(element, this::extractSortedElementsInternal); + return elementSortedMap.get(element); + } - private List extractSortedElementsInternal(Element element) { - // Need to apply sorting, because order of result items for Element.getEnclosedElements() depend on JDK implementation - // By default, exclude private and package-private items - // todo allow pass parameter for filter items by access modifiers - return ElementFilter.typesIn(getEnclosedElements(element)).stream() - .filter(o -> !Utils.isPrivateOrPackagePrivate(o)) - .filter(o -> !matchAnyPattern(excludeClasses, String.valueOf(o.getQualifiedName()))) - .sorted((o1, o2) -> - StringUtils.compare(String.valueOf(o1.getSimpleName()), String.valueOf(o2.getSimpleName())) - ).collect(Collectors.toList()); - } + private List extractSortedElementsInternal(Element element) { + // Need to apply sorting, because order of result items for Element.getEnclosedElements() depend + // on JDK implementation + // By default, exclude private and package-private items + // todo allow pass parameter for filter items by access modifiers + return ElementFilter.typesIn(getEnclosedElements(element)).stream() + .filter(o -> !Utils.isPrivateOrPackagePrivate(o)) + .filter(o -> !matchAnyPattern(excludeClasses, String.valueOf(o.getQualifiedName()))) + .sorted( + (o1, o2) -> + StringUtils.compare( + String.valueOf(o1.getSimpleName()), String.valueOf(o2.getSimpleName()))) + .collect(Collectors.toList()); + } - public List getEnclosedElements(Element element) { - elementMap.computeIfAbsent(element, this::getEnclosedElementsInternal); - return elementMap.get(element); - } + public List getEnclosedElements(Element element) { + elementMap.computeIfAbsent(element, this::getEnclosedElementsInternal); + return elementMap.get(element); + } - private List getEnclosedElementsInternal(Element element) { - return element.getEnclosedElements(); - } + private List getEnclosedElementsInternal(Element element) { + return element.getEnclosedElements(); + } - public List extractPackageElements(Set elements) { - return ElementFilter.packagesIn(elements).stream() - .filter(o -> !matchAnyPattern(excludePackages, String.valueOf(o))) - .sorted((o1, o2) -> - StringUtils.compare(String.valueOf(o1.getSimpleName()), String.valueOf(o2.getSimpleName())) - ).collect(Collectors.toList()); - } + public List extractPackageElements(Set elements) { + return ElementFilter.packagesIn(elements).stream() + .filter(o -> !matchAnyPattern(excludePackages, String.valueOf(o))) + .sorted( + (o1, o2) -> + StringUtils.compare( + String.valueOf(o1.getSimpleName()), String.valueOf(o2.getSimpleName()))) + .collect(Collectors.toList()); + } - boolean matchAnyPattern(Set patterns, String stringToCheck) { - for (Pattern pattern : patterns) { - if (pattern.matcher(stringToCheck).matches()) { - return true; - } - } - return false; + boolean matchAnyPattern(Set patterns, String stringToCheck) { + for (Pattern pattern : patterns) { + if (pattern.matcher(stringToCheck).matches()) { + return true; + } } -} \ No newline at end of file + return false; + } +} diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/FileUtil.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/FileUtil.java index cbad4f7e..9f416219 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/FileUtil.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/FileUtil.java @@ -1,7 +1,6 @@ package com.microsoft.util; import com.microsoft.model.YmlFile; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -9,21 +8,19 @@ public class FileUtil { - /** - * Dump string to file. Create required folders when needed - */ - public static void dumpToFile(String content, String fileName) { + /** Dump string to file. Create required folders when needed */ + public static void dumpToFile(String content, String fileName) { - try { - Path path = Paths.get(fileName); - Files.createDirectories(path.getParent()); - Files.write(path, content.getBytes()); - } catch (IOException ioe) { - throw new RuntimeException("Error during dump to file", ioe); - } + try { + Path path = Paths.get(fileName); + Files.createDirectories(path.getParent()); + Files.write(path, content.getBytes()); + } catch (IOException ioe) { + throw new RuntimeException("Error during dump to file", ioe); } + } - public static void dumpToFile(YmlFile ymlFile) { - dumpToFile(ymlFile.getFileContent(), ymlFile.getFileNameWithPath()); - } + public static void dumpToFile(YmlFile ymlFile) { + dumpToFile(ymlFile.getFileContent(), ymlFile.getFileNameWithPath()); + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/OptionsFileUtil.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/OptionsFileUtil.java index 6a9554e2..2605f2bc 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/OptionsFileUtil.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/OptionsFileUtil.java @@ -9,32 +9,32 @@ public class OptionsFileUtil { - public static List processOptionsFile(String filename) { - List jargs = new ArrayList<>(); + public static List processOptionsFile(String filename) { + List jargs = new ArrayList<>(); - String options = readOptionsFromFile(filename); - StringTokenizer tokens = new StringTokenizer(options); - while (tokens.hasMoreTokens()) { - jargs.add(tokens.nextToken()); - } - - return jargs; + String options = readOptionsFromFile(filename); + StringTokenizer tokens = new StringTokenizer(options); + while (tokens.hasMoreTokens()) { + jargs.add(tokens.nextToken()); } - private static String readOptionsFromFile(String filename) { - StringBuffer buffer = new StringBuffer(); - try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filename))) { - String line; - while ((line = bufferedReader.readLine()) != null) { - // remove single quote at the head and tail - String trimmedLine = line.replaceAll("^'|'$", ""); - buffer.append(trimmedLine).append("\n"); - } - } catch (IOException ioe) { - buffer.setLength(0); - throw new RuntimeException("Error during reading options from file", ioe); - } + return jargs; + } - return buffer.toString(); + private static String readOptionsFromFile(String filename) { + StringBuffer buffer = new StringBuffer(); + try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filename))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + // remove single quote at the head and tail + String trimmedLine = line.replaceAll("^'|'$", ""); + buffer.append(trimmedLine).append("\n"); + } + } catch (IOException ioe) { + buffer.setLength(0); + throw new RuntimeException("Error during reading options from file", ioe); } + + return buffer.toString(); + } } diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/Utils.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/Utils.java index e901651f..ebc67ef3 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/Utils.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/Utils.java @@ -1,263 +1,253 @@ package com.microsoft.util; +import static com.sun.source.doctree.DocTree.Kind.ERRONEOUS; +import static javax.lang.model.type.TypeKind.DECLARED; + import com.sun.source.doctree.DocCommentTree; import com.sun.source.doctree.DocTree; -import jdk.javadoc.doclet.DocletEnvironment; - -import javax.lang.model.element.*; -import javax.lang.model.type.TypeKind; -import javax.lang.model.type.TypeMirror; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; - -import static com.sun.source.doctree.DocTree.Kind.ERRONEOUS; -import static javax.lang.model.type.TypeKind.DECLARED; +import javax.lang.model.element.*; +import javax.lang.model.type.TypeKind; +import javax.lang.model.type.TypeMirror; +import javax.lang.model.util.Elements; +import javax.lang.model.util.Types; +import jdk.javadoc.doclet.DocletEnvironment; public class Utils { - public final DocletEnvironment docletEnvironment; - public final Elements elements; - public final Types typeUtils; - private final ElementUtil elementUtil; - - public Utils(DocletEnvironment docEnv, ElementUtil elementUtil) { - this.docletEnvironment = docEnv; - this.elements = docEnv.getElementUtils(); - this.typeUtils = docEnv.getTypeUtils(); - this.elementUtil = elementUtil; - } - - public static boolean isPackagePrivate(Element e) { - return !(isPublic(e) || isPrivate(e) || isProtected(e)); - } - - public static boolean isPrivate(Element e) { - return e.getModifiers().contains(Modifier.PRIVATE); - } - - public static boolean isProtected(Element e) { - return e.getModifiers().contains(Modifier.PROTECTED); - } - - public static boolean isPublic(Element e) { - return e.getModifiers().contains(Modifier.PUBLIC); - } - - public static boolean isPrivateOrPackagePrivate(Element e) { - return isPrivate(e) || isPackagePrivate(e); - } - - public static boolean isNoType(TypeMirror t) { - return t.getKind() == TypeKind.NONE; - } - - public boolean isStatic(Element e) { - return e.getModifiers().contains(Modifier.STATIC); - } - - /** - * Returns true if the method has no comments, or a lone @inheritDoc. - * - * @param m a method - * @return true if there are no comments, false otherwise - */ - public boolean isSimpleOverride(ExecutableElement m) { - - if (!getBlockTags(m).isEmpty()) - return false; - - List fullBody = getFullBody(m); - return fullBody.isEmpty() || - (fullBody.size() == 1 && fullBody.get(0).getKind().equals(DocTree.Kind.INHERIT_DOC)); - } - - public boolean hasInlineTag(List inlineTags, DocTree.Kind kind) { - for (DocTree dt : inlineTags) { - if (dt.getKind() == kind) { - return true; - } - } - return false; - } - - public Element getMemberBySignature(TypeElement te, ElementKind kind, String signature) { - return getMembers(te, kind).stream() - .filter(e -> e.toString().equals(signature)) - .findFirst().orElse(null); - } - - public TypeElement getObjectType() { - return elements.getTypeElement("java.lang.Object"); - } - - /** - * Return the element of given type. - */ - public TypeElement asTypeElement(TypeMirror t) { - if (t.getKind() != TypeKind.NONE) { - TypeElement element = (TypeElement) docletEnvironment.getTypeUtils().asElement(t); - return element; - } else return null; - } - - /** - * Return the lexically enclosing element for a nested type. - * The inherited items will not be listed. - */ - public TypeElement getEnclosingTypeElement(Element e) { - if (e.getKind() == ElementKind.PACKAGE) - return null; - Element encl = e.getEnclosingElement(); - ElementKind kind = encl.getKind(); - if (kind == ElementKind.PACKAGE) - return null; - while (!(kind.isClass() || kind.isInterface())) { - encl = encl.getEnclosingElement(); - kind = encl.getKind(); - } - return (TypeElement) encl; - } - - /** - * Follow the same behavior with Standard doclet. - * Return the ExecutableElement being overridden by given method, - * when a method in a class overrides a method in a superclass. - * For following cases, they will be marked as "Specified by": - *
    - *
  • a method in an interface overrides a method in a superinterface
  • - *
  • a method in a class implements a method in an interface
  • - *
- * todo add "Specified by" to yaml. - */ - public ExecutableElement overriddenMethod(ExecutableElement method) { - if (isStatic(method)) { - return null; - } - final TypeElement origin = getEnclosingTypeElement(method); - for (TypeMirror t = getSuperType(origin); - t.getKind() == DECLARED; - t = getSuperType(asTypeElement(t))) { - TypeElement te = asTypeElement(t); - if (te == null) { - return null; - } - - for (Element e : getMembers(te, ElementKind.METHOD)) { - ExecutableElement ee = (ExecutableElement) e; - if (elements.overrides(method, ee, origin) - ) { - return ee; - } - } - if (t.equals(getObjectType().asType())) - return null; - } + public final DocletEnvironment docletEnvironment; + public final Elements elements; + public final Types typeUtils; + private final ElementUtil elementUtil; + + public Utils(DocletEnvironment docEnv, ElementUtil elementUtil) { + this.docletEnvironment = docEnv; + this.elements = docEnv.getElementUtils(); + this.typeUtils = docEnv.getTypeUtils(); + this.elementUtil = elementUtil; + } + + public static boolean isPackagePrivate(Element e) { + return !(isPublic(e) || isPrivate(e) || isProtected(e)); + } + + public static boolean isPrivate(Element e) { + return e.getModifiers().contains(Modifier.PRIVATE); + } + + public static boolean isProtected(Element e) { + return e.getModifiers().contains(Modifier.PROTECTED); + } + + public static boolean isPublic(Element e) { + return e.getModifiers().contains(Modifier.PUBLIC); + } + + public static boolean isPrivateOrPackagePrivate(Element e) { + return isPrivate(e) || isPackagePrivate(e); + } + + public static boolean isNoType(TypeMirror t) { + return t.getKind() == TypeKind.NONE; + } + + public boolean isStatic(Element e) { + return e.getModifiers().contains(Modifier.STATIC); + } + + /** + * Returns true if the method has no comments, or a lone @inheritDoc. + * + * @param m a method + * @return true if there are no comments, false otherwise + */ + public boolean isSimpleOverride(ExecutableElement m) { + + if (!getBlockTags(m).isEmpty()) return false; + + List fullBody = getFullBody(m); + return fullBody.isEmpty() + || (fullBody.size() == 1 && fullBody.get(0).getKind().equals(DocTree.Kind.INHERIT_DOC)); + } + + public boolean hasInlineTag(List inlineTags, DocTree.Kind kind) { + for (DocTree dt : inlineTags) { + if (dt.getKind() == kind) { + return true; + } + } + return false; + } + + public Element getMemberBySignature(TypeElement te, ElementKind kind, String signature) { + return getMembers(te, kind).stream() + .filter(e -> e.toString().equals(signature)) + .findFirst() + .orElse(null); + } + + public TypeElement getObjectType() { + return elements.getTypeElement("java.lang.Object"); + } + + /** Return the element of given type. */ + public TypeElement asTypeElement(TypeMirror t) { + if (t.getKind() != TypeKind.NONE) { + TypeElement element = (TypeElement) docletEnvironment.getTypeUtils().asElement(t); + return element; + } else return null; + } + + /** + * Return the lexically enclosing element for a nested type. The inherited items will not be + * listed. + */ + public TypeElement getEnclosingTypeElement(Element e) { + if (e.getKind() == ElementKind.PACKAGE) return null; + Element encl = e.getEnclosingElement(); + ElementKind kind = encl.getKind(); + if (kind == ElementKind.PACKAGE) return null; + while (!(kind.isClass() || kind.isInterface())) { + encl = encl.getEnclosingElement(); + kind = encl.getKind(); + } + return (TypeElement) encl; + } + + /** + * Follow the same behavior with Standard doclet. Return the ExecutableElement being overridden by + * given method, when a method in a class overrides a method in a superclass. For following cases, + * they will be marked as "Specified by": + * + *
    + *
  • a method in an interface overrides a method in a superinterface + *
  • a method in a class implements a method in an interface + *
+ * + * todo add "Specified by" to yaml. + */ + public ExecutableElement overriddenMethod(ExecutableElement method) { + if (isStatic(method)) { + return null; + } + final TypeElement origin = getEnclosingTypeElement(method); + for (TypeMirror t = getSuperType(origin); + t.getKind() == DECLARED; + t = getSuperType(asTypeElement(t))) { + TypeElement te = asTypeElement(t); + if (te == null) { return null; - } + } - public TypeMirror getSuperType(TypeElement te) { - TypeMirror t = te.getSuperclass(); - return getType(t); - } - - private TypeMirror getType(TypeMirror t) { - return (isNoType(t)) ? getObjectType().asType() : t; - } - - public Optional getDocCommentTree(Element element) { - return Optional.ofNullable(docletEnvironment.getDocTrees().getDocCommentTree(element)); - } - - protected List getFullBody(Element element) { - return getDocCommentTree(element) - .map(DocCommentTree::getFullBody) - .orElse(Collections.emptyList()); - } - - public static List filteredList(List dlist, DocTree.Kind... select) { - List list = new ArrayList<>(); - if (select == null) - return dlist; - for (DocTree dt : dlist) { - if (dt.getKind() != ERRONEOUS) { - for (DocTree.Kind kind : select) { - if (dt.getKind() == kind) { - list.add(dt); - } - } - } + for (Element e : getMembers(te, ElementKind.METHOD)) { + ExecutableElement ee = (ExecutableElement) e; + if (elements.overrides(method, ee, origin)) { + return ee; } - return list; - } - - private List getBlockTags0(Element element, DocTree.Kind... kinds) { - Optional dcTree = getDocCommentTree(element); - if (dcTree.isEmpty()) - return Collections.emptyList(); - - return filteredList(dcTree.get().getBlockTags(), kinds); - } - - public List getBlockTags(Element element) { - return getBlockTags0(element, (DocTree.Kind[]) null); - } - - public List removeBlockTag(List dctree, DocTree.Kind kind) { - return dctree.stream() - .filter(dc -> !dc.getKind().equals(kind)) - .collect(Collectors.toList()); - } - - /** - * Returns a list of visible enclosed members of given kind, - * declared in this type element, and does not include - * any inherited members or extra members. - * - * @return a list of visible enclosed members in this type - */ - public List getMembers(TypeElement te, ElementKind kind) { - return elementUtil.getEnclosedElements(te).stream() - .filter(e -> e.getKind() == kind && !isPrivateOrPackagePrivate(e)) - .collect(Collectors.toList()); - } - - /** - * Returns a list of methods being implemented by given method. - * When a method in an interface overrides a method its superinterface, - * it will be considered as "implemented", instead of "overridden". - * - * @return a list of implemented methods - */ - public List getImplementedMethods(String signature, TypeElement encl, List implementedMethods) { - if (encl == null) { - return implementedMethods; + } + if (t.equals(getObjectType().asType())) return null; + } + return null; + } + + public TypeMirror getSuperType(TypeElement te) { + TypeMirror t = te.getSuperclass(); + return getType(t); + } + + private TypeMirror getType(TypeMirror t) { + return (isNoType(t)) ? getObjectType().asType() : t; + } + + public Optional getDocCommentTree(Element element) { + return Optional.ofNullable(docletEnvironment.getDocTrees().getDocCommentTree(element)); + } + + protected List getFullBody(Element element) { + return getDocCommentTree(element) + .map(DocCommentTree::getFullBody) + .orElse(Collections.emptyList()); + } + + public static List filteredList( + List dlist, DocTree.Kind... select) { + List list = new ArrayList<>(); + if (select == null) return dlist; + for (DocTree dt : dlist) { + if (dt.getKind() != ERRONEOUS) { + for (DocTree.Kind kind : select) { + if (dt.getKind() == kind) { + list.add(dt); + } } - - for (TypeElement interfaceType : getImplementedInterfaces(encl)) { - Element implementedMethod = getMemberBySignature(interfaceType, ElementKind.METHOD, signature); - if (implementedMethod != null) { - implementedMethods.add(implementedMethod); - } - // We need to search every implemented interface of the Inheritance chain. - getImplementedMethods(signature, interfaceType, implementedMethods); - } - return implementedMethods; - } - - /** - * Returns a list of implemented interface type elements of given type element. - * Follow Standard doclet, search in the order of appearance following the word implements in declaration. - * - * @return a list of implemented interfaces - */ - public List getImplementedInterfaces(TypeElement element) { - return element.getInterfaces().stream() - .map(e -> asTypeElement(e)) - .collect(Collectors.toList()); - } -} \ No newline at end of file + } + } + return list; + } + + private List getBlockTags0(Element element, DocTree.Kind... kinds) { + Optional dcTree = getDocCommentTree(element); + if (dcTree.isEmpty()) return Collections.emptyList(); + + return filteredList(dcTree.get().getBlockTags(), kinds); + } + + public List getBlockTags(Element element) { + return getBlockTags0(element, (DocTree.Kind[]) null); + } + + public List removeBlockTag(List dctree, DocTree.Kind kind) { + return dctree.stream().filter(dc -> !dc.getKind().equals(kind)).collect(Collectors.toList()); + } + + /** + * Returns a list of visible enclosed members of given kind, declared in this type element, and + * does not include any inherited members or extra members. + * + * @return a list of visible enclosed members in this type + */ + public List getMembers(TypeElement te, ElementKind kind) { + return elementUtil.getEnclosedElements(te).stream() + .filter(e -> e.getKind() == kind && !isPrivateOrPackagePrivate(e)) + .collect(Collectors.toList()); + } + + /** + * Returns a list of methods being implemented by given method. When a method in an interface + * overrides a method its superinterface, it will be considered as "implemented", instead of + * "overridden". + * + * @return a list of implemented methods + */ + public List getImplementedMethods( + String signature, TypeElement encl, List implementedMethods) { + if (encl == null) { + return implementedMethods; + } + + for (TypeElement interfaceType : getImplementedInterfaces(encl)) { + Element implementedMethod = + getMemberBySignature(interfaceType, ElementKind.METHOD, signature); + if (implementedMethod != null) { + implementedMethods.add(implementedMethod); + } + // We need to search every implemented interface of the Inheritance chain. + getImplementedMethods(signature, interfaceType, implementedMethods); + } + return implementedMethods; + } + + /** + * Returns a list of implemented interface type elements of given type element. Follow Standard + * doclet, search in the order of appearance following the word implements in declaration. + * + * @return a list of implemented interfaces + */ + public List getImplementedInterfaces(TypeElement element) { + return element.getInterfaces().stream().map(e -> asTypeElement(e)).collect(Collectors.toList()); + } +} diff --git a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/YamlUtil.java b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/YamlUtil.java index 7fd6bbf6..5a4f8f0f 100644 --- a/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/YamlUtil.java +++ b/third_party/docfx-doclet-143274/src/main/java/com/microsoft/util/YamlUtil.java @@ -8,33 +8,38 @@ import org.apache.commons.lang3.StringUtils; public class YamlUtil { - private static final ObjectMapper mapper = new ObjectMapper(new YAMLFactory() - .disable(Feature.WRITE_DOC_START_MARKER) - .disable(Feature.SPLIT_LINES) - ) - .setSerializationInclusion(Include.NON_NULL) - .setSerializationInclusion(Include.NON_EMPTY); + private static final ObjectMapper mapper = + new ObjectMapper( + new YAMLFactory() + .disable(Feature.WRITE_DOC_START_MARKER) + .disable(Feature.SPLIT_LINES)) + .setSerializationInclusion(Include.NON_NULL) + .setSerializationInclusion(Include.NON_EMPTY); - public static String objectToYamlString(Object object) { - try { - return mapper.writeValueAsString(object); - } catch (JsonProcessingException jpe) { - throw new RuntimeException("Could not serialize object to yaml string", jpe); - } + public static String objectToYamlString(Object object) { + try { + return mapper.writeValueAsString(object); + } catch (JsonProcessingException jpe) { + throw new RuntimeException("Could not serialize object to yaml string", jpe); } + } - public static String cleanupHtml(String text) { - if (StringUtils.isBlank(text)) { - return text; - } - return text.replaceAll("
([^<]+)
","$1") - .replaceAll("
", "
")
-                .replaceAll("<([A-Z][^<]+||)>", "<$1>")
-                .replaceAll("`([^`]+)`", "$1")
-                .replaceAll("\\[([^]]+)]\\(([^)]+)\\)", "$1")
-                .replaceAll("\\{@link *\"([^\\{]+)\" *\\}", "$1")
-                .replaceAll("\\[([^]]+)]\\[([^]]+)\\]", "$1")
-                .replaceAll("\\{@link *([^\\{\"]+) *\\}", "$1")
-                .replaceAll("=======================([^=]+)=======================", "

$1

"); + public static String cleanupHtml(String text) { + if (StringUtils.isBlank(text)) { + return text; } + return text.replaceAll("
([^<]+)
", "$1") + .replaceAll("
", "
")
+        .replaceAll("<([A-Z][^<]+||)>", "<$1>")
+        .replaceAll("`([^`]+)`", "$1")
+        .replaceAll("\\[([^]]+)]\\(([^)]+)\\)", "$1")
+        .replaceAll("\\{@link *\"([^\\{]+)\" *\\}", "$1")
+        .replaceAll(
+            "\\[([^]]+)]\\[([^]]+)\\]",
+            "$1")
+        .replaceAll(
+            "\\{@link *([^\\{\"]+) *\\}",
+            "$1")
+        .replaceAll("=======================([^=]+)=======================", "

$1

"); + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/BuilderUtilTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/BuilderUtilTest.java index 03bdda31..b64e5fc7 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/BuilderUtilTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/BuilderUtilTest.java @@ -15,99 +15,126 @@ */ package com.microsoft.build; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import com.microsoft.model.MetadataFile; import com.microsoft.model.MetadataFileItem; import com.microsoft.model.MethodParameter; import com.microsoft.model.Syntax; -import org.junit.Test; - import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.Test; public class BuilderUtilTest { - @Test - public void populateUidValues() { - MetadataFile classMetadataFile = new MetadataFile("output", "name"); - - MetadataFileItem ownerClassItem = buildMetadataFileItem("a.b.OwnerClass", "Not important summary value"); - ownerClassItem.setNameWithType("OwnerClass"); - MetadataFileItem item1 = buildMetadataFileItem("UID unknown class", "UnknownClass"); - populateSyntax(item1, "SomeClass#someMethod(String param)"); - MetadataFileItem item2 = buildMetadataFileItem("UID known class", "SomeClass#someMethod(String param)"); - MetadataFileItem item3 = buildMetadataFileItem("UID method only", "#someMethod2(String p1, String p2)"); - classMetadataFile.getItems().addAll(Arrays.asList(ownerClassItem, item1, item2, item3)); - - MetadataFileItem reference1 = new MetadataFileItem("a.b.SomeClass.someMethod(String param)"); - reference1.setNameWithType("SomeClass.someMethod(String param)"); - MetadataFileItem reference2 = new MetadataFileItem("a.b.OwnerClass.someMethod2(String p1, String p2)"); - reference2.setNameWithType("OwnerClass.someMethod2(String p1, String p2)"); - classMetadataFile.getReferences().addAll(Arrays.asList(reference1, reference2)); - - BuilderUtil.populateUidValues(Collections.emptyList(), Arrays.asList(classMetadataFile)); - - assertEquals("Wrong summary for unknown class", item1.getSummary(), - "Bla bla UnknownClass bla"); - assertEquals("Wrong syntax description", item1.getSyntax().getParameters().get(0).getDescription(), - "One two SomeClass#someMethod(String param) three"); - assertEquals("Wrong summary for known class", item2.getSummary(), - "Bla bla SomeClass#someMethod(String param) bla"); - assertEquals("Wrong summary for method", item3.getSummary(), - "Bla bla #someMethod2(String p1, String p2) bla"); - - } - - private MetadataFileItem buildMetadataFileItem(String uid, String value) { - MetadataFileItem item = new MetadataFileItem(uid); - item.setSummary( - String.format("Bla bla %s bla", value, value)); - return item; - } - - private void populateSyntax(MetadataFileItem item, String value) { - Syntax syntax = new Syntax(); - String methodParamDescription = String - .format("One two %s three", value, value); - syntax.setParameters( - Arrays.asList(new MethodParameter("method param id", "method param type", methodParamDescription))); - item.setSyntax(syntax); - } - - @Test - public void determineUidByLinkContent() { - Map lookup = new HashMap<>() {{ + @Test + public void populateUidValues() { + MetadataFile classMetadataFile = new MetadataFile("output", "name"); + + MetadataFileItem ownerClassItem = + buildMetadataFileItem("a.b.OwnerClass", "Not important summary value"); + ownerClassItem.setNameWithType("OwnerClass"); + MetadataFileItem item1 = buildMetadataFileItem("UID unknown class", "UnknownClass"); + populateSyntax(item1, "SomeClass#someMethod(String param)"); + MetadataFileItem item2 = + buildMetadataFileItem("UID known class", "SomeClass#someMethod(String param)"); + MetadataFileItem item3 = + buildMetadataFileItem("UID method only", "#someMethod2(String p1, String p2)"); + classMetadataFile.getItems().addAll(Arrays.asList(ownerClassItem, item1, item2, item3)); + + MetadataFileItem reference1 = new MetadataFileItem("a.b.SomeClass.someMethod(String param)"); + reference1.setNameWithType("SomeClass.someMethod(String param)"); + MetadataFileItem reference2 = + new MetadataFileItem("a.b.OwnerClass.someMethod2(String p1, String p2)"); + reference2.setNameWithType("OwnerClass.someMethod2(String p1, String p2)"); + classMetadataFile.getReferences().addAll(Arrays.asList(reference1, reference2)); + + BuilderUtil.populateUidValues(Collections.emptyList(), Arrays.asList(classMetadataFile)); + + assertEquals( + "Wrong summary for unknown class", + item1.getSummary(), + "Bla bla UnknownClass bla"); + assertEquals( + "Wrong syntax description", + item1.getSyntax().getParameters().get(0).getDescription(), + "One two SomeClass#someMethod(String param) three"); + assertEquals( + "Wrong summary for known class", + item2.getSummary(), + "Bla bla SomeClass#someMethod(String param) bla"); + assertEquals( + "Wrong summary for method", + item3.getSummary(), + "Bla bla #someMethod2(String p1, String p2) bla"); + } + + private MetadataFileItem buildMetadataFileItem(String uid, String value) { + MetadataFileItem item = new MetadataFileItem(uid); + item.setSummary( + String.format( + "Bla bla %s bla", + value, value)); + return item; + } + + private void populateSyntax(MetadataFileItem item, String value) { + Syntax syntax = new Syntax(); + String methodParamDescription = + String.format( + "One two %s three", + value, value); + syntax.setParameters( + Arrays.asList( + new MethodParameter("method param id", "method param type", methodParamDescription))); + item.setSyntax(syntax); + } + + @Test + public void determineUidByLinkContent() { + Map lookup = + new HashMap<>() { + { put("SomeClass", "a.b.c.SomeClass"); put("SomeClass.someMethod()", "a.b.c.SomeClass.someMethod()"); put("SomeClass.someMethod(String param)", "a.b.c.SomeClass.someMethod(String param)"); - }}; - - LookupContext lookupContext = new LookupContext(lookup, lookup); - assertEquals("Wrong result for class", BuilderUtil. - resolveUidByLookup("SomeClass", lookupContext), "a.b.c.SomeClass"); - assertEquals("Wrong result for method", BuilderUtil. - resolveUidFromLinkContent("SomeClass#someMethod()", lookupContext), "a.b.c.SomeClass.someMethod()"); - assertEquals("Wrong result for method with param", BuilderUtil. - resolveUidFromLinkContent("SomeClass#someMethod(String param)", lookupContext), - "a.b.c.SomeClass.someMethod(String param)"); - - assertEquals("Wrong result for unknown class", BuilderUtil. - resolveUidByLookup("UnknownClass", lookupContext), ""); - assertEquals("Wrong result for null", BuilderUtil.resolveUidByLookup(null, lookupContext), ""); - assertEquals("Wrong result for whitespace", BuilderUtil.resolveUidByLookup(" ", lookupContext), ""); - } - - @Test - public void splitUidWithGenericsIntoClassNames() { - List result = BuilderUtil.splitUidWithGenericsIntoClassNames("a.b.c.List>"); - - assertEquals("Wrong result list size", result.size(), 3); - assertTrue("Wrong result list content", result.contains("a.b.c.List")); - assertTrue("Wrong result list content", result.contains("df.mn.ClassOne")); - assertTrue("Wrong result list content", result.contains("tr.T")); - } + } + }; + + LookupContext lookupContext = new LookupContext(lookup, lookup); + assertEquals( + "Wrong result for class", + BuilderUtil.resolveUidByLookup("SomeClass", lookupContext), + "a.b.c.SomeClass"); + assertEquals( + "Wrong result for method", + BuilderUtil.resolveUidFromLinkContent("SomeClass#someMethod()", lookupContext), + "a.b.c.SomeClass.someMethod()"); + assertEquals( + "Wrong result for method with param", + BuilderUtil.resolveUidFromLinkContent("SomeClass#someMethod(String param)", lookupContext), + "a.b.c.SomeClass.someMethod(String param)"); + + assertEquals( + "Wrong result for unknown class", + BuilderUtil.resolveUidByLookup("UnknownClass", lookupContext), + ""); + assertEquals("Wrong result for null", BuilderUtil.resolveUidByLookup(null, lookupContext), ""); + assertEquals( + "Wrong result for whitespace", BuilderUtil.resolveUidByLookup(" ", lookupContext), ""); + } + + @Test + public void splitUidWithGenericsIntoClassNames() { + List result = + BuilderUtil.splitUidWithGenericsIntoClassNames("a.b.c.List>"); + + assertEquals("Wrong result list size", result.size(), 3); + assertTrue("Wrong result list content", result.contains("a.b.c.List")); + assertTrue("Wrong result list content", result.contains("df.mn.ClassOne")); + assertTrue("Wrong result list content", result.contains("tr.T")); + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/ClassBuilderTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/ClassBuilderTest.java index cc170b23..9b8cbe97 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/ClassBuilderTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/ClassBuilderTest.java @@ -15,6 +15,9 @@ */ package com.microsoft.build; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + import com.google.testing.compile.CompilationRule; import com.microsoft.lookup.ClassItemsLookup; import com.microsoft.lookup.ClassLookup; @@ -22,66 +25,65 @@ import com.microsoft.model.MetadataFileItem; import com.microsoft.util.ElementUtil; import com.sun.source.util.DocTrees; +import java.io.File; +import java.util.Collection; +import javax.lang.model.element.TypeElement; +import javax.lang.model.util.Elements; import jdk.javadoc.doclet.DocletEnvironment; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import java.io.File; -import java.util.Collection; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; - public class ClassBuilderTest { - @Rule - public CompilationRule rule = new CompilationRule(); - private Elements elements; - private ClassBuilder classBuilder; - private DocletEnvironment environment; - private DocTrees docTrees; + @Rule public CompilationRule rule = new CompilationRule(); + private Elements elements; + private ClassBuilder classBuilder; + private DocletEnvironment environment; + private DocTrees docTrees; - @Before - public void setup() { - elements = rule.getElements(); - environment = Mockito.mock(DocletEnvironment.class); - docTrees = Mockito.mock(DocTrees.class); - ElementUtil elementUtil = new ElementUtil(new String[0], new String[0]); - ClassLookup classLookup = new ClassLookup(environment, elementUtil); - classBuilder = new ClassBuilder( + @Before + public void setup() { + elements = rule.getElements(); + environment = Mockito.mock(DocletEnvironment.class); + docTrees = Mockito.mock(DocTrees.class); + ElementUtil elementUtil = new ElementUtil(new String[0], new String[0]); + ClassLookup classLookup = new ClassLookup(environment, elementUtil); + classBuilder = + new ClassBuilder( elementUtil, classLookup, new ClassItemsLookup(environment, elementUtil), "./target", new ReferenceBuilder(environment, classLookup, elementUtil)); - } - @Test - public void addConstructorsInfoWhenOnlyDefaultConstructor() { - TypeElement element = elements.getTypeElement("com.microsoft.samples.subpackage.Person"); - MetadataFile container = new MetadataFile("output", "name"); - when(environment.getElementUtils()).thenReturn(elements); - when(environment.getDocTrees()).thenReturn(docTrees); + } + + @Test + public void addConstructorsInfoWhenOnlyDefaultConstructor() { + TypeElement element = elements.getTypeElement("com.microsoft.samples.subpackage.Person"); + MetadataFile container = new MetadataFile("output", "name"); + when(environment.getElementUtils()).thenReturn(elements); + when(environment.getDocTrees()).thenReturn(docTrees); - classBuilder.addConstructorsInfo(element, container); + classBuilder.addConstructorsInfo(element, container); - assertEquals("Wrong file name", container.getFileNameWithPath(), "output" + File.separator + "name"); - assertEquals("Container should contain constructor item", container.getItems().size(), 1); - } + assertEquals( + "Wrong file name", container.getFileNameWithPath(), "output" + File.separator + "name"); + assertEquals("Container should contain constructor item", container.getItems().size(), 1); + } - @Test - public void addConstructorsInfo() { - TypeElement element = elements.getTypeElement("com.microsoft.samples.SuperHero"); - MetadataFile container = new MetadataFile("output", "name"); - when(environment.getElementUtils()).thenReturn(elements); - when(environment.getDocTrees()).thenReturn(docTrees); + @Test + public void addConstructorsInfo() { + TypeElement element = elements.getTypeElement("com.microsoft.samples.SuperHero"); + MetadataFile container = new MetadataFile("output", "name"); + when(environment.getElementUtils()).thenReturn(elements); + when(environment.getDocTrees()).thenReturn(docTrees); - classBuilder.addConstructorsInfo(element, container); + classBuilder.addConstructorsInfo(element, container); - assertEquals("Wrong file name", container.getFileNameWithPath(), "output" + File.separator + "name"); - Collection constructorItems = container.getItems(); - assertEquals("Container should contain 2 constructor items", constructorItems.size(), 2); - } -} \ No newline at end of file + assertEquals( + "Wrong file name", container.getFileNameWithPath(), "output" + File.separator + "name"); + Collection constructorItems = container.getItems(); + assertEquals("Container should contain 2 constructor items", constructorItems.size(), 2); + } +} diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/LookupContextTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/LookupContextTest.java index 1c8872b3..b634e355 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/LookupContextTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/LookupContextTest.java @@ -1,52 +1,53 @@ package com.microsoft.build; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.*; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; - -import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; public class LookupContextTest { - private LookupContext lookupContext; - private Map globalLookup = new HashMap<>(); - private Map localLookup = new LinkedHashMap<>(); - private String[] localKeys = {"local key 1", "local key 2"}; - private String[] localValues = {"local value 1", "local value 2"}; - private String globalKey = "global key"; - private String globalValue = "global value"; - private String unknownKey = "unknown key"; - - @Before - public void setUp() { - localLookup.put(localKeys[0], localValues[0]); - localLookup.put(localKeys[1], localValues[1]); - globalLookup.put(globalKey, globalValue); - globalLookup.putAll(localLookup); - lookupContext = new LookupContext(globalLookup, localLookup); - } - - @Test - public void resolve() { - assertEquals("Wrong value for global key", lookupContext.resolve(globalKey), globalValue); - assertEquals("Wrong value for local key 1", lookupContext.resolve(localKeys[0]), localValues[0]); - assertEquals("Wrong value for local key 2", lookupContext.resolve(localKeys[1]), localValues[1]); - assertNull("Wrong value for unknown key", lookupContext.resolve(unknownKey)); - } - - @Test - public void getOwnerUid() { - assertEquals("Wrong ownerUid", lookupContext.getOwnerUid(), localKeys[0]); - } - - @Test - public void containsKey() { - assertTrue("Wrong value for global key", lookupContext.containsKey(globalKey)); - assertTrue("Wrong value for local key 1", lookupContext.containsKey(localKeys[0])); - assertTrue("Wrong value for local key 2", lookupContext.containsKey(localKeys[1])); - assertFalse("Wrong value for unknown key", lookupContext.containsKey(unknownKey)); - } + private LookupContext lookupContext; + private Map globalLookup = new HashMap<>(); + private Map localLookup = new LinkedHashMap<>(); + private String[] localKeys = {"local key 1", "local key 2"}; + private String[] localValues = {"local value 1", "local value 2"}; + private String globalKey = "global key"; + private String globalValue = "global value"; + private String unknownKey = "unknown key"; + + @Before + public void setUp() { + localLookup.put(localKeys[0], localValues[0]); + localLookup.put(localKeys[1], localValues[1]); + globalLookup.put(globalKey, globalValue); + globalLookup.putAll(localLookup); + lookupContext = new LookupContext(globalLookup, localLookup); + } + + @Test + public void resolve() { + assertEquals("Wrong value for global key", lookupContext.resolve(globalKey), globalValue); + assertEquals( + "Wrong value for local key 1", lookupContext.resolve(localKeys[0]), localValues[0]); + assertEquals( + "Wrong value for local key 2", lookupContext.resolve(localKeys[1]), localValues[1]); + assertNull("Wrong value for unknown key", lookupContext.resolve(unknownKey)); + } + + @Test + public void getOwnerUid() { + assertEquals("Wrong ownerUid", lookupContext.getOwnerUid(), localKeys[0]); + } + + @Test + public void containsKey() { + assertTrue("Wrong value for global key", lookupContext.containsKey(globalKey)); + assertTrue("Wrong value for local key 1", lookupContext.containsKey(localKeys[0])); + assertTrue("Wrong value for local key 2", lookupContext.containsKey(localKeys[1])); + assertFalse("Wrong value for unknown key", lookupContext.containsKey(unknownKey)); + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/LookupTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/LookupTest.java index a3e85226..60de26bc 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/LookupTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/LookupTest.java @@ -1,84 +1,93 @@ package com.microsoft.build; +import static org.junit.Assert.*; + import com.microsoft.model.MetadataFile; import com.microsoft.model.MetadataFileItem; -import org.junit.Before; -import org.junit.Test; - import java.util.ArrayList; import java.util.List; - -import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; public class LookupTest { - private Lookup lookup; - private String packageUid = "package uid"; - private String packageNameWithType = "package name with type"; - private String classUid = "com.microsoft.samples.subpackage.Person.setFirstName(java.lang.String,boolean)"; - private String classNameWithType = "Person.setFirstName(String firstName, boolean flag)"; + private Lookup lookup; + private String packageUid = "package uid"; + private String packageNameWithType = "package name with type"; + private String classUid = + "com.microsoft.samples.subpackage.Person.setFirstName(java.lang.String,boolean)"; + private String classNameWithType = "Person.setFirstName(String firstName, boolean flag)"; - private List packageFiles = new ArrayList<>() {{ - MetadataFile packageFile = new MetadataFile("package path", "package name"); - packageFile.getItems().add(buildMetadataFileItem(packageUid, packageNameWithType)); - add(packageFile); - }}; - private List classFiles = new ArrayList<>() {{ - MetadataFile classFile = new MetadataFile("class path", "class name"); - classFile.getItems().add(buildMetadataFileItem(classUid, classNameWithType)); - add(classFile); - }}; + private List packageFiles = + new ArrayList<>() { + { + MetadataFile packageFile = new MetadataFile("package path", "package name"); + packageFile.getItems().add(buildMetadataFileItem(packageUid, packageNameWithType)); + add(packageFile); + } + }; + private List classFiles = + new ArrayList<>() { + { + MetadataFile classFile = new MetadataFile("class path", "class name"); + classFile.getItems().add(buildMetadataFileItem(classUid, classNameWithType)); + add(classFile); + } + }; - @Before - public void setUp() { - lookup = new Lookup(packageFiles, classFiles); - } + @Before + public void setUp() { + lookup = new Lookup(packageFiles, classFiles); + } - @Test - public void buildContext() { - LookupContext context = lookup.buildContext(classFiles.get(0)); + @Test + public void buildContext() { + LookupContext context = lookup.buildContext(classFiles.get(0)); - String[] localKeys = { - // Uid as is - "com.microsoft.samples.subpackage.Person.setFirstName(java.lang.String,boolean)", - // Uid as is with spaces between params - "com.microsoft.samples.subpackage.Person.setFirstName(java.lang.String, boolean)", - // Uid with param types without package - "com.microsoft.samples.subpackage.Person.setFirstName(String,boolean)", - // Uid with param types without package with spaces between params - "com.microsoft.samples.subpackage.Person.setFirstName(String, boolean)", - // Uid without package - "Person.setFirstName(java.lang.String,boolean)", - // Uid without package with spaces between params - "Person.setFirstName(java.lang.String, boolean)", + String[] localKeys = { + // Uid as is + "com.microsoft.samples.subpackage.Person.setFirstName(java.lang.String,boolean)", + // Uid as is with spaces between params + "com.microsoft.samples.subpackage.Person.setFirstName(java.lang.String, boolean)", + // Uid with param types without package + "com.microsoft.samples.subpackage.Person.setFirstName(String,boolean)", + // Uid with param types without package with spaces between params + "com.microsoft.samples.subpackage.Person.setFirstName(String, boolean)", + // Uid without package + "Person.setFirstName(java.lang.String,boolean)", + // Uid without package with spaces between params + "Person.setFirstName(java.lang.String, boolean)", - // Name with type as is - "Person.setFirstName(String, boolean)", - // Name with type without generics - "Person.setFirstName(String firstName, boolean flag)", - // Name with type without generics and param names - "Person.setFirstName(String, boolean)", - // Name with type without generics and param names without spaces between params - "Person.setFirstName(String,boolean)" - }; - assertEquals("Wrong owner uid", context.getOwnerUid(), "Person.setFirstName(String firstName, boolean flag)"); + // Name with type as is + "Person.setFirstName(String, boolean)", + // Name with type without generics + "Person.setFirstName(String firstName, boolean flag)", + // Name with type without generics and param names + "Person.setFirstName(String, boolean)", + // Name with type without generics and param names without spaces between params + "Person.setFirstName(String,boolean)" + }; + assertEquals( + "Wrong owner uid", + context.getOwnerUid(), + "Person.setFirstName(String firstName, boolean flag)"); - for (String localKey : localKeys) { - assertTrue("Context should contain local key=" + localKey, context.containsKey(localKey)); - assertEquals("Wrong value for local key=" + localKey, context.resolve(localKey), classUid); - } + for (String localKey : localKeys) { + assertTrue("Context should contain local key=" + localKey, context.containsKey(localKey)); + assertEquals("Wrong value for local key=" + localKey, context.resolve(localKey), classUid); + } - assertTrue("Context should contain global key", context.containsKey(packageNameWithType)); - assertTrue("Context should contain global value as a key", context.containsKey(packageUid)); - assertEquals("Wrong value for global key", context.resolve(packageNameWithType), packageUid); - assertEquals("Wrong value for local value as a key", context.resolve(packageUid), packageUid); + assertTrue("Context should contain global key", context.containsKey(packageNameWithType)); + assertTrue("Context should contain global value as a key", context.containsKey(packageUid)); + assertEquals("Wrong value for global key", context.resolve(packageNameWithType), packageUid); + assertEquals("Wrong value for local value as a key", context.resolve(packageUid), packageUid); - assertFalse("Context shouldn't contain unknown key", context.containsKey("unknown key")); - } + assertFalse("Context shouldn't contain unknown key", context.containsKey("unknown key")); + } - private MetadataFileItem buildMetadataFileItem(String uid, String nameWithType) { - MetadataFileItem result = new MetadataFileItem(uid); - result.setNameWithType(nameWithType); - return result; - } + private MetadataFileItem buildMetadataFileItem(String uid, String nameWithType) { + MetadataFileItem result = new MetadataFileItem(uid); + result.setNameWithType(nameWithType); + return result; + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/ReferenceBuilderTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/ReferenceBuilderTest.java index b4509a2f..71354f42 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/ReferenceBuilderTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/ReferenceBuilderTest.java @@ -15,99 +15,110 @@ */ package com.microsoft.build; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import com.microsoft.lookup.ClassLookup; import com.microsoft.model.MetadataFile; import com.microsoft.model.MetadataFileItem; import com.microsoft.util.ElementUtil; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; import jdk.javadoc.doclet.DocletEnvironment; import org.apache.commons.lang3.RegExUtils; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - public class ReferenceBuilderTest { - private ReferenceBuilder referenceBuilder; - - @Before - public void setup() { - DocletEnvironment environment = Mockito.mock(DocletEnvironment.class); - ElementUtil elementUtil = new ElementUtil(new String[0], new String[0]); - ClassLookup classLookup = new ClassLookup(environment, elementUtil); - referenceBuilder = new ReferenceBuilder(environment, classLookup, elementUtil); - } - - @Test - public void expandComplexGenericsInReferences() { - MetadataFile classMetadataFile = new MetadataFile("path", "name"); - MetadataFileItem referenceItem = new MetadataFileItem("a.b.c.List>"); - Set references = classMetadataFile.getReferences(); - references.add(referenceItem); - - referenceBuilder.expandComplexGenericsInReferences(classMetadataFile); - - assertEquals("Wrong references amount", references.size(), 4); - - List content = references.stream().map(MetadataFileItem::getUid).collect(Collectors.toList()); - assertTrue("Wrong references content", content.contains("a.b.c.List")); - assertTrue("Wrong references content", content.contains("df.mn.ClassOne")); - assertTrue("Wrong references content", content.contains("tr.T")); - assertTrue("Wrong references content", content.contains("a.b.c.List>")); - } - - //todo add test case to cover reference item with in package - @Test - public void buildRefItem() { - buildRefItemAndCheckAssertions("java.lang.Some.String", "java.lang.Some.String", "String"); - buildRefItemAndCheckAssertions("java.lang.Some.String[]", "java.lang.Some.String[]", "String"); - } - - private void buildRefItemAndCheckAssertions(String initialValue, String expectedUid, String expectedName) { - MetadataFileItem result = referenceBuilder.buildRefItem(initialValue); - - assertEquals("Wrong uid", result.getUid(), expectedUid); - assertEquals("Wrong name", result.getSpecForJava().iterator().next().getUid(), RegExUtils.removeAll(expectedUid, "\\[\\]$")); - assertEquals("Wrong name", result.getSpecForJava().iterator().next().getName(), expectedName); - assertEquals("Wrong fullName", result.getSpecForJava().iterator().next().getFullName(), RegExUtils.removeAll(expectedUid, "\\[\\]$")); - } - - @Test - public void getJavaReferenceHref() { - String result1 = referenceBuilder.getJavaReferenceHref("java.lang.Object"); - String result2 = referenceBuilder.getJavaReferenceHref("java.lang.Object.equals(java.lang.Object)"); - String result3 = referenceBuilder.getJavaReferenceHref("java.lang.Object.notify()"); - String result4 = referenceBuilder.getJavaReferenceHref("java.util.List"); - String result5 = referenceBuilder.getJavaReferenceHref("java.lang.Object.wait(long,int)"); - String result6 = referenceBuilder.getJavaReferenceHref("java.lang.Object.getClass()"); - String result7 = referenceBuilder.getJavaReferenceHref("java.io.IOException"); - String result8 = referenceBuilder.getJavaReferenceHref("java.io.InputStream"); - String result9 = referenceBuilder.getJavaReferenceHref("java.lang.Enum.hashCode()"); - String result10 = referenceBuilder.getJavaReferenceHref("java.nio.ByteBuffer"); - String result11 = referenceBuilder.getJavaReferenceHref("java.lang.Enum.valueOf(java.lang.Class,java.lang.String)"); - String result12 = referenceBuilder.getJavaReferenceHref(""); - String result13 = referenceBuilder.getJavaReferenceHref(null); - - String baseURL = "https://docs.oracle.com/javase/8/docs/api/"; - - assertEquals(baseURL + "java/lang/Object.html", result1); - assertEquals(baseURL + "java/lang/Object.html#equals-java.lang.Object-", result2); - assertEquals(baseURL + "java/lang/Object.html#notify--", result3); - assertEquals(baseURL + "java/util/List.html", result4); - assertEquals(baseURL + "java/lang/Object.html#wait-long-int-", result5); - assertEquals(baseURL + "java/lang/Object.html#getClass--", result6); - assertEquals(baseURL + "java/io/IOException.html", result7); - assertEquals(baseURL + "java/io/InputStream.html", result8); - assertEquals(baseURL + "java/lang/Enum.html#hashCode--", result9); - assertEquals(baseURL + "java/nio/ByteBuffer.html", result10); - assertEquals(baseURL + "java/lang/Enum.html#valueOf-java.lang.Class-java.lang.String-", result11); - assertEquals(baseURL, result12); - assertEquals(baseURL, result13); - } -} \ No newline at end of file + private ReferenceBuilder referenceBuilder; + + @Before + public void setup() { + DocletEnvironment environment = Mockito.mock(DocletEnvironment.class); + ElementUtil elementUtil = new ElementUtil(new String[0], new String[0]); + ClassLookup classLookup = new ClassLookup(environment, elementUtil); + referenceBuilder = new ReferenceBuilder(environment, classLookup, elementUtil); + } + + @Test + public void expandComplexGenericsInReferences() { + MetadataFile classMetadataFile = new MetadataFile("path", "name"); + MetadataFileItem referenceItem = new MetadataFileItem("a.b.c.List>"); + Set references = classMetadataFile.getReferences(); + references.add(referenceItem); + + referenceBuilder.expandComplexGenericsInReferences(classMetadataFile); + + assertEquals("Wrong references amount", references.size(), 4); + + List content = + references.stream().map(MetadataFileItem::getUid).collect(Collectors.toList()); + assertTrue("Wrong references content", content.contains("a.b.c.List")); + assertTrue("Wrong references content", content.contains("df.mn.ClassOne")); + assertTrue("Wrong references content", content.contains("tr.T")); + assertTrue("Wrong references content", content.contains("a.b.c.List>")); + } + + // todo add test case to cover reference item with in package + @Test + public void buildRefItem() { + buildRefItemAndCheckAssertions("java.lang.Some.String", "java.lang.Some.String", "String"); + buildRefItemAndCheckAssertions("java.lang.Some.String[]", "java.lang.Some.String[]", "String"); + } + + private void buildRefItemAndCheckAssertions( + String initialValue, String expectedUid, String expectedName) { + MetadataFileItem result = referenceBuilder.buildRefItem(initialValue); + + assertEquals("Wrong uid", result.getUid(), expectedUid); + assertEquals( + "Wrong name", + result.getSpecForJava().iterator().next().getUid(), + RegExUtils.removeAll(expectedUid, "\\[\\]$")); + assertEquals("Wrong name", result.getSpecForJava().iterator().next().getName(), expectedName); + assertEquals( + "Wrong fullName", + result.getSpecForJava().iterator().next().getFullName(), + RegExUtils.removeAll(expectedUid, "\\[\\]$")); + } + + @Test + public void getJavaReferenceHref() { + String result1 = referenceBuilder.getJavaReferenceHref("java.lang.Object"); + String result2 = + referenceBuilder.getJavaReferenceHref("java.lang.Object.equals(java.lang.Object)"); + String result3 = referenceBuilder.getJavaReferenceHref("java.lang.Object.notify()"); + String result4 = referenceBuilder.getJavaReferenceHref("java.util.List"); + String result5 = referenceBuilder.getJavaReferenceHref("java.lang.Object.wait(long,int)"); + String result6 = referenceBuilder.getJavaReferenceHref("java.lang.Object.getClass()"); + String result7 = referenceBuilder.getJavaReferenceHref("java.io.IOException"); + String result8 = referenceBuilder.getJavaReferenceHref("java.io.InputStream"); + String result9 = referenceBuilder.getJavaReferenceHref("java.lang.Enum.hashCode()"); + String result10 = referenceBuilder.getJavaReferenceHref("java.nio.ByteBuffer"); + String result11 = + referenceBuilder.getJavaReferenceHref( + "java.lang.Enum.valueOf(java.lang.Class,java.lang.String)"); + String result12 = referenceBuilder.getJavaReferenceHref(""); + String result13 = referenceBuilder.getJavaReferenceHref(null); + + String baseURL = "https://docs.oracle.com/javase/8/docs/api/"; + + assertEquals(baseURL + "java/lang/Object.html", result1); + assertEquals(baseURL + "java/lang/Object.html#equals-java.lang.Object-", result2); + assertEquals(baseURL + "java/lang/Object.html#notify--", result3); + assertEquals(baseURL + "java/util/List.html", result4); + assertEquals(baseURL + "java/lang/Object.html#wait-long-int-", result5); + assertEquals(baseURL + "java/lang/Object.html#getClass--", result6); + assertEquals(baseURL + "java/io/IOException.html", result7); + assertEquals(baseURL + "java/io/InputStream.html", result8); + assertEquals(baseURL + "java/lang/Enum.html#hashCode--", result9); + assertEquals(baseURL + "java/nio/ByteBuffer.html", result10); + assertEquals( + baseURL + "java/lang/Enum.html#valueOf-java.lang.Class-java.lang.String-", result11); + assertEquals(baseURL, result12); + assertEquals(baseURL, result13); + } +} diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/YmlFilesBuilderTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/YmlFilesBuilderTest.java index f5905351..bbfbf423 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/YmlFilesBuilderTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/build/YmlFilesBuilderTest.java @@ -1,7 +1,11 @@ package com.microsoft.build; +import static org.junit.Assert.assertEquals; + import com.microsoft.model.TocItem; import com.microsoft.model.TocTypeMap; +import java.util.List; +import javax.lang.model.element.ElementKind; import jdk.javadoc.doclet.DocletEnvironment; import org.junit.Before; import org.junit.Test; @@ -9,53 +13,55 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; -import javax.lang.model.element.ElementKind; -import java.util.List; - -import static org.junit.Assert.assertEquals; - @RunWith(MockitoJUnitRunner.class) public class YmlFilesBuilderTest { - private YmlFilesBuilder ymlFilesBuilder; - private DocletEnvironment environment; + private YmlFilesBuilder ymlFilesBuilder; + private DocletEnvironment environment; - @Before - public void setup() { - environment = Mockito.mock(DocletEnvironment.class); - ymlFilesBuilder = new YmlFilesBuilder(environment, "./target", new String[]{}, new String[]{}, "google-cloud-product", false); - } + @Before + public void setup() { + environment = Mockito.mock(DocletEnvironment.class); + ymlFilesBuilder = + new YmlFilesBuilder( + environment, + "./target", + new String[] {}, + new String[] {}, + "google-cloud-product", + false); + } - @Test - public void joinTocTypeItems(){ - TocTypeMap typeMap = new TocTypeMap(); - TocItem classToc = new TocItem("uid1", "name1"); - TocItem interfaceToc = new TocItem("uid2", "name2"); - TocItem enumToc = new TocItem("uid3", "name3"); - TocItem annotationToc = new TocItem("uid4", "name4"); - TocItem exceptionToc = new TocItem("uid5", "name5"); + @Test + public void joinTocTypeItems() { + TocTypeMap typeMap = new TocTypeMap(); + TocItem classToc = new TocItem("uid1", "name1"); + TocItem interfaceToc = new TocItem("uid2", "name2"); + TocItem enumToc = new TocItem("uid3", "name3"); + TocItem annotationToc = new TocItem("uid4", "name4"); + TocItem exceptionToc = new TocItem("uid5", "name5"); - typeMap.get(ElementKind.CLASS.name()).add(classToc); - typeMap.get(ElementKind.INTERFACE.name()).add(interfaceToc); - typeMap.get(ElementKind.ENUM.name()).add(enumToc); - typeMap.get(ElementKind.ANNOTATION_TYPE.name()).add(annotationToc); - typeMap.get("EXCEPTION").add(exceptionToc); + typeMap.get(ElementKind.CLASS.name()).add(classToc); + typeMap.get(ElementKind.INTERFACE.name()).add(interfaceToc); + typeMap.get(ElementKind.ENUM.name()).add(enumToc); + typeMap.get(ElementKind.ANNOTATION_TYPE.name()).add(annotationToc); + typeMap.get("EXCEPTION").add(exceptionToc); - List tocItems = ymlFilesBuilder.joinTocTypeItems(typeMap); + List tocItems = ymlFilesBuilder.joinTocTypeItems(typeMap); - assertEquals("Interfaces", tocItems.get(0).getHeading()); - assertEquals(interfaceToc, tocItems.get(1)); + assertEquals("Interfaces", tocItems.get(0).getHeading()); + assertEquals(interfaceToc, tocItems.get(1)); - assertEquals("Classes", tocItems.get(2).getHeading()); - assertEquals(classToc, tocItems.get(3)); + assertEquals("Classes", tocItems.get(2).getHeading()); + assertEquals(classToc, tocItems.get(3)); - assertEquals("Enums", tocItems.get(4).getHeading()); - assertEquals(enumToc, tocItems.get(5)); + assertEquals("Enums", tocItems.get(4).getHeading()); + assertEquals(enumToc, tocItems.get(5)); - assertEquals("Annotation Types", tocItems.get(6).getHeading()); - assertEquals(annotationToc, tocItems.get(7)); + assertEquals("Annotation Types", tocItems.get(6).getHeading()); + assertEquals(annotationToc, tocItems.get(7)); - assertEquals("Exceptions", tocItems.get(8).getHeading()); - assertEquals(exceptionToc, tocItems.get(9)); - } -} \ No newline at end of file + assertEquals("Exceptions", tocItems.get(8).getHeading()); + assertEquals(exceptionToc, tocItems.get(9)); + } +} diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/doclet/DocFxDocletTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/doclet/DocFxDocletTest.java index 47caf06d..d342f780 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/doclet/DocFxDocletTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/doclet/DocFxDocletTest.java @@ -1,65 +1,65 @@ package com.microsoft.doclet; +import static org.junit.Assert.assertEquals; + import com.microsoft.doclet.DocFxDoclet.CustomOption; import com.microsoft.doclet.DocFxDoclet.FakeOptionForCompatibilityWithStandardDoclet; +import java.util.Arrays; +import java.util.List; +import javax.lang.model.SourceVersion; import jdk.javadoc.doclet.Doclet.Option.Kind; import org.junit.Before; import org.junit.Test; -import javax.lang.model.SourceVersion; -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.assertEquals; - public class DocFxDocletTest { - private DocFxDoclet doclet; + private DocFxDoclet doclet; - @Before - public void setup() { - doclet = new DocFxDoclet(); - } + @Before + public void setup() { + doclet = new DocFxDoclet(); + } - @Test - public void getSupportedSourceVersion() { - assertEquals("Wrong version used", doclet.getSupportedSourceVersion(), SourceVersion.latest()); - } + @Test + public void getSupportedSourceVersion() { + assertEquals("Wrong version used", doclet.getSupportedSourceVersion(), SourceVersion.latest()); + } - @Test - public void getDocletName() { - assertEquals("Wrong doclet name", doclet.getName(), "DocFxDoclet"); - } + @Test + public void getDocletName() { + assertEquals("Wrong doclet name", doclet.getName(), "DocFxDoclet"); + } - @Test - public void testCustomOptionCreation() { - String description = "Some desc"; - List names = Arrays.asList("name 1", "name 2"); - String params = "Some params"; + @Test + public void testCustomOptionCreation() { + String description = "Some desc"; + List names = Arrays.asList("name 1", "name 2"); + String params = "Some params"; - CustomOption option = new CustomOption(description, names, params) { - @Override - public boolean process(String option, List arguments) { - return false; - } + CustomOption option = + new CustomOption(description, names, params) { + @Override + public boolean process(String option, List arguments) { + return false; + } }; - assertEquals("Wrong args count", option.getArgumentCount(), 1); - assertEquals("Wrong description", option.getDescription(), description); - assertEquals("Wrong kind", option.getKind(), Kind.STANDARD); - assertEquals("Wrong names", option.getNames(), names); - assertEquals("Wrong params", option.getParameters(), params); - } + assertEquals("Wrong args count", option.getArgumentCount(), 1); + assertEquals("Wrong description", option.getDescription(), description); + assertEquals("Wrong kind", option.getKind(), Kind.STANDARD); + assertEquals("Wrong names", option.getNames(), names); + assertEquals("Wrong params", option.getParameters(), params); + } - @Test - public void testFakeOptionCreation() { - FakeOptionForCompatibilityWithStandardDoclet option = - new FakeOptionForCompatibilityWithStandardDoclet("Some description", "title"); + @Test + public void testFakeOptionCreation() { + FakeOptionForCompatibilityWithStandardDoclet option = + new FakeOptionForCompatibilityWithStandardDoclet("Some description", "title"); - assertEquals("Wrong args count", option.getArgumentCount(), 1); - assertEquals("Wrong description", option.getDescription(), "Some description"); - assertEquals("Wrong kind", option.getKind(), Kind.STANDARD); - assertEquals("Wrong names", option.getNames(), Arrays.asList("title")); - assertEquals("Wrong params", option.getParameters(), "none"); - } + assertEquals("Wrong args count", option.getArgumentCount(), 1); + assertEquals("Wrong description", option.getDescription(), "Some description"); + assertEquals("Wrong kind", option.getKind(), Kind.STANDARD); + assertEquals("Wrong names", option.getNames(), Arrays.asList("title")); + assertEquals("Wrong params", option.getParameters(), "none"); + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/doclet/DocletRunnerTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/doclet/DocletRunnerTest.java index 0a4ac777..1974c5cb 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/doclet/DocletRunnerTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/doclet/DocletRunnerTest.java @@ -1,10 +1,9 @@ package com.microsoft.doclet; -import com.microsoft.util.FileUtilTest; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import com.microsoft.util.FileUtilTest; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; @@ -12,78 +11,87 @@ import java.nio.file.Path; import java.util.List; import java.util.stream.Collectors; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; public class DocletRunnerTest { - private final String PARAMS_DIR = "src/test/resources/test-doclet-params.txt"; - private final String EXPECTED_GENERATED_FILES_DIR = "src/test/resources/expected-generated-files"; - private final String OUTPUT_DIR = "target/test-out"; - - private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); - private final PrintStream originalOut = System.out; - private final PrintStream originalErr = System.err; - - @Before - public void cleanup() throws IOException { - FileUtilTest.deleteDirectory(OUTPUT_DIR); - - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - } - - @After - public void restoreStreams() { - System.setOut(originalOut); - System.setErr(originalErr); - } - - @Test - public void testFilesGenerationWhenNoParams() { - DocletRunner.main(new String[]{}); - - assertEquals("Wrong System.err content", - errContent.toString().trim(), "Usage: java DocletRunner "); - } - - @Test - public void testFilesGenerationWhenTargetFileDoesNotExist() { - try { - DocletRunner.main(new String[]{"some-name.txt"}); - fail(); - } catch (RuntimeException ex) { - assertEquals("Wrong System.err content", - errContent.toString().trim(), "File 'some-name.txt' does not exist"); - } + private final String PARAMS_DIR = "src/test/resources/test-doclet-params.txt"; + private final String EXPECTED_GENERATED_FILES_DIR = "src/test/resources/expected-generated-files"; + private final String OUTPUT_DIR = "target/test-out"; + + private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); + private final PrintStream originalOut = System.out; + private final PrintStream originalErr = System.err; + + @Before + public void cleanup() throws IOException { + FileUtilTest.deleteDirectory(OUTPUT_DIR); + + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + } + + @After + public void restoreStreams() { + System.setOut(originalOut); + System.setErr(originalErr); + } + + @Test + public void testFilesGenerationWhenNoParams() { + DocletRunner.main(new String[] {}); + + assertEquals( + "Wrong System.err content", + errContent.toString().trim(), + "Usage: java DocletRunner "); + } + + @Test + public void testFilesGenerationWhenTargetFileDoesNotExist() { + try { + DocletRunner.main(new String[] {"some-name.txt"}); + fail(); + } catch (RuntimeException ex) { + assertEquals( + "Wrong System.err content", + errContent.toString().trim(), + "File 'some-name.txt' does not exist"); } + } - @Test - public void testFilesGeneration() throws IOException { - DocletRunner.main(new String[]{PARAMS_DIR}); + @Test + public void testFilesGeneration() throws IOException { + DocletRunner.main(new String[] {PARAMS_DIR}); - List expectedFilePaths = Files.list(Path.of(EXPECTED_GENERATED_FILES_DIR)).collect(Collectors.toList()); - List generatedFilePaths = Files.list(Path.of(OUTPUT_DIR)).collect(Collectors.toList()); - assertEquals("Wrong files count", generatedFilePaths.size(), expectedFilePaths.size()); + List expectedFilePaths = + Files.list(Path.of(EXPECTED_GENERATED_FILES_DIR)).collect(Collectors.toList()); + List generatedFilePaths = Files.list(Path.of(OUTPUT_DIR)).collect(Collectors.toList()); + assertEquals("Wrong files count", generatedFilePaths.size(), expectedFilePaths.size()); - for (Path expectedFilePath : expectedFilePaths) { - Path generatedFilePath = Path.of(OUTPUT_DIR, expectedFilePath.getFileName().toString()); + for (Path expectedFilePath : expectedFilePaths) { + Path generatedFilePath = Path.of(OUTPUT_DIR, expectedFilePath.getFileName().toString()); - String generatedFileContent = Files.readString(generatedFilePath); - String expectedFileContent = Files.readString(expectedFilePath); + String generatedFileContent = Files.readString(generatedFilePath); + String expectedFileContent = Files.readString(expectedFilePath); - String[] generatedFileLines = generatedFileContent.split("\n"); - String[] expectedFileLines = expectedFileContent.split("\n"); + String[] generatedFileLines = generatedFileContent.split("\n"); + String[] expectedFileLines = expectedFileContent.split("\n"); - assertEquals("Unexpected amount of lines in file " + generatedFilePath, generatedFileLines.length, - expectedFileLines.length); + assertEquals( + "Unexpected amount of lines in file " + generatedFilePath, + generatedFileLines.length, + expectedFileLines.length); - for (int i = 0; i < generatedFileLines.length; i++) { - assertEquals("Wrong file content for file " + generatedFilePath, - generatedFileLines[i], expectedFileLines[i]); - } - } + for (int i = 0; i < generatedFileLines.length; i++) { + assertEquals( + "Wrong file content for file " + generatedFilePath, + generatedFileLines[i], + expectedFileLines[i]); + } } + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/lookup/BaseLookupTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/lookup/BaseLookupTest.java index 4078facd..f53a7594 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/lookup/BaseLookupTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/lookup/BaseLookupTest.java @@ -1,11 +1,21 @@ package com.microsoft.lookup; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.mockito.Mockito.*; + import com.google.testing.compile.CompilationRule; import com.microsoft.lookup.model.ExtendedMetadataFileItem; import com.microsoft.model.*; import com.sun.source.doctree.*; import com.sun.source.doctree.DocTree.Kind; import com.sun.source.util.DocTrees; +import java.util.Arrays; +import java.util.Collections; +import java.util.Set; +import javax.lang.model.element.Element; +import javax.lang.model.element.TypeElement; +import javax.lang.model.util.Elements; import jdk.javadoc.doclet.DocletEnvironment; import org.junit.Before; import org.junit.Rule; @@ -14,245 +24,285 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; -import javax.lang.model.element.Element; -import javax.lang.model.element.ElementKind; -import javax.lang.model.element.PackageElement; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.Set; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.mockito.Mockito.*; - @RunWith(MockitoJUnitRunner.class) public class BaseLookupTest { - @Rule - public CompilationRule rule = new CompilationRule(); - private Elements elements; - private DocletEnvironment environment; - private DocTrees docTrees; - private DocCommentTree docCommentTree; - private TextTree textTree; - private LinkTree linkTree; - private ReferenceTree referenceTree; - private LiteralTree literalTree; - private TypeElement typeElement; - private BaseLookup baseLookup; - private ExtendedMetadataFileItem lastBuiltItem; - - @Before - public void setup() { - elements = rule.getElements(); - environment = Mockito.mock(DocletEnvironment.class); - docTrees = Mockito.mock(DocTrees.class); - docCommentTree = Mockito.mock(DocCommentTree.class); - textTree = Mockito.mock(TextTree.class); - linkTree = Mockito.mock(LinkTree.class); - referenceTree = Mockito.mock(ReferenceTree.class); - literalTree = Mockito.mock(LiteralTree.class); - typeElement = Mockito.mock(TypeElement.class); - - baseLookup = new BaseLookup<>(environment) { - @Override - protected ExtendedMetadataFileItem buildMetadataFileItem(Element element) { - lastBuiltItem = buildExtendedMetadataFileItem(element); - return lastBuiltItem; - } + @Rule public CompilationRule rule = new CompilationRule(); + private Elements elements; + private DocletEnvironment environment; + private DocTrees docTrees; + private DocCommentTree docCommentTree; + private TextTree textTree; + private LinkTree linkTree; + private ReferenceTree referenceTree; + private LiteralTree literalTree; + private TypeElement typeElement; + private BaseLookup baseLookup; + private ExtendedMetadataFileItem lastBuiltItem; + + @Before + public void setup() { + elements = rule.getElements(); + environment = Mockito.mock(DocletEnvironment.class); + docTrees = Mockito.mock(DocTrees.class); + docCommentTree = Mockito.mock(DocCommentTree.class); + textTree = Mockito.mock(TextTree.class); + linkTree = Mockito.mock(LinkTree.class); + referenceTree = Mockito.mock(ReferenceTree.class); + literalTree = Mockito.mock(LiteralTree.class); + typeElement = Mockito.mock(TypeElement.class); + + baseLookup = + new BaseLookup<>(environment) { + @Override + protected ExtendedMetadataFileItem buildMetadataFileItem(Element element) { + lastBuiltItem = buildExtendedMetadataFileItem(element); + return lastBuiltItem; + } }; - } - - @Test - public void determineComment() { - TypeElement element = elements.getTypeElement("com.microsoft.samples.subpackage.Person"); - when(environment.getDocTrees()).thenReturn(docTrees); - when(docTrees.getDocCommentTree(element)).thenReturn(docCommentTree); - doReturn(Arrays.asList(textTree, linkTree)).when(docCommentTree).getFullBody(); - when(textTree.getKind()).thenReturn(Kind.TEXT); - when(linkTree.getKind()).thenReturn(Kind.LINK); - when(linkTree.getReference()).thenReturn(referenceTree); - when(referenceTree.getSignature()).thenReturn("Some#signature"); - when(textTree.toString()).thenReturn("Some text 1"); - - String result = baseLookup.determineComment(element); - - verify(environment).getDocTrees(); - verify(docTrees).getDocCommentTree(element); - verify(docCommentTree).getFullBody(); - verify(textTree).getKind(); - verify(linkTree).getKind(); - verify(linkTree).getReference(); - verify(linkTree).getLabel(); - assertEquals("Wrong result", result, "Some text 1Some#signature"); - } - - @Test - public void makeTypeShort() { - assertEquals("Wrong result for primitive type", baseLookup.makeTypeShort("int"), "int"); - assertEquals("Wrong result", baseLookup.makeTypeShort("java.lang.String"), "String"); - assertEquals("Wrong result for inner class", - baseLookup.makeTypeShort("org.apache.commons.lang3.arch.Processor.Arch"), "Processor.Arch"); - assertEquals("Wrong result for class with generic", - baseLookup.makeTypeShort("java.util.List"), "List"); - assertEquals("Wrong result for inner class with generic", - baseLookup.makeTypeShort("java.util.List.Custom"), "List.Custom"); - assertEquals("Wrong result for inner class with complex generic", - baseLookup.makeTypeShort("a.b.c.D.E.G>>"), "D.E.G>>"); - assertEquals("Wrong result for inner class with generic & inheritance", - baseLookup.makeTypeShort("a.b.G"), "G"); - } - - @Test - public void buildXrefTag() { - when(linkTree.getReference()).thenReturn(referenceTree); - when(referenceTree.getSignature()).thenReturn("Some#signature"); - when(linkTree.getLabel()).thenReturn(Collections.emptyList()); - - String result = baseLookup.buildXrefTag(linkTree); - - assertEquals("Wrong result", result, - "Some#signature"); - } - - @Test - public void buildXrefTagWhenLabelPresents() { - when(linkTree.getReference()).thenReturn(referenceTree); - when(referenceTree.getSignature()).thenReturn("Some#signature"); - doReturn(Arrays.asList(textTree)).when(linkTree).getLabel(); - String labelValue = "IamLabel"; - when(textTree.toString()).thenReturn(labelValue); - - String result = baseLookup.buildXrefTag(linkTree); - - assertEquals("Wrong result", result, - "" + labelValue + ""); - } - - @Test - public void buildCodeTag() { - String tagContent = "Some text ≤"; - when(literalTree.getBody()).thenReturn(textTree); - when(textTree.toString()).thenReturn(tagContent); - - String result = baseLookup.buildCodeTag(literalTree); - - assertEquals("Wrong result", result, "" + tagContent + ""); - } - - @Test - public void expandLiteralBody() { - String tagContent = "Some text ≤ \u2264"; - when(literalTree.getBody()).thenReturn(textTree); - when(textTree.toString()).thenReturn(tagContent); - - String result = baseLookup.expandLiteralBody(literalTree); - String expected = "Some text ≤ ≤"; - - assertEquals("Wrong result", result, expected); - } - - @Test - public void replaceLinksAndCodes() { - when(linkTree.getReference()).thenReturn(referenceTree); - when(referenceTree.getSignature()).thenReturn("Some#signature"); - when(linkTree.getLabel()).thenReturn(Collections.emptyList()); - String textTreeContent = "Some text content ≤ \u2264"; - when(literalTree.getBody()).thenReturn(textTree); - when(textTree.toString()).thenReturn(textTreeContent); - when(linkTree.getKind()).thenReturn(Kind.LINK); - when(literalTree.getKind()).thenReturn(Kind.CODE); - when(textTree.getKind()).thenReturn(Kind.TEXT); - - String result = baseLookup.replaceLinksAndCodes(Arrays.asList(linkTree, literalTree, textTree)); - - assertEquals("Wrong result", result, "" - + "Some#signatureSome text content ≤ ≤" + textTreeContent); - } - - @Test - public void resolve() { - TypeElement element1 = elements.getTypeElement("com.microsoft.samples.subpackage.Person"); - TypeElement element2 = elements.getTypeElement("com.microsoft.samples.subpackage.Display"); - - ExtendedMetadataFileItem resultForKey1 = baseLookup.resolve(element1); - ExtendedMetadataFileItem resultForKey2 = baseLookup.resolve(element2); - ExtendedMetadataFileItem consequenceCallResultForKey1 = baseLookup.resolve(element1); - - assertEquals("Consequence call should return same instance", resultForKey1, consequenceCallResultForKey1); - assertNotEquals("Resolve for another key should return another instance", resultForKey2, resultForKey1); - } - - @Test - public void testExtractMethods() { - TypeElement element = elements.getTypeElement("com.microsoft.samples.subpackage.Person"); - - assertEquals("Wrong packageName", baseLookup.extractPackageName(element), lastBuiltItem.getPackageName()); - assertEquals("Wrong fullName", baseLookup.extractFullName(element), lastBuiltItem.getFullName()); - assertEquals("Wrong name", baseLookup.extractName(element), lastBuiltItem.getName()); - assertEquals("Wrong href", baseLookup.extractHref(element), lastBuiltItem.getHref()); - assertEquals("Wrong parent", baseLookup.extractParent(element), lastBuiltItem.getParent()); - assertEquals("Wrong id", baseLookup.extractId(element), lastBuiltItem.getId()); - assertEquals("Wrong uid", baseLookup.extractUid(element), lastBuiltItem.getUid()); - assertEquals("Wrong nameWithType", baseLookup.extractNameWithType(element), lastBuiltItem.getNameWithType()); - assertEquals("Wrong methodContent", baseLookup.extractMethodContent(element), - lastBuiltItem.getMethodContent()); - assertEquals("Wrong fieldContent", baseLookup.extractFieldContent(element), lastBuiltItem.getFieldContent()); - assertEquals("Wrong constructorContent", baseLookup.extractConstructorContent(element), - lastBuiltItem.getConstructorContent()); - assertEquals("Wrong overload", baseLookup.extractOverload(element), lastBuiltItem.getOverload()); - assertEquals("Wrong parameters", baseLookup.extractParameters(element), lastBuiltItem.getParameters()); - assertEquals("Wrong exceptions", baseLookup.extractExceptions(element), lastBuiltItem.getExceptions()); - - assertEquals("Wrong return", baseLookup.extractReturn(element).getReturnType(), - lastBuiltItem.getReturn().getReturnType()); - assertEquals("Wrong return", baseLookup.extractReturn(element).getReturnDescription(), - lastBuiltItem.getReturn().getReturnDescription()); - - assertEquals("Wrong summary", baseLookup.extractSummary(element), lastBuiltItem.getSummary()); - assertEquals("Wrong type", baseLookup.extractType(element), lastBuiltItem.getType()); - assertEquals("Wrong content", baseLookup.extractContent(element), lastBuiltItem.getContent()); - assertEquals("Wrong typeParameters", baseLookup.extractTypeParameters(element), - lastBuiltItem.getTypeParameters()); - assertEquals("Wrong superclass", baseLookup.extractSuperclass(element), lastBuiltItem.getSuperclass()); - assertEquals("Wrong interfaces", baseLookup.extractInterfaces(element), lastBuiltItem.getInterfaces()); - assertEquals("Wrong tocName", baseLookup.extractTocName(element), lastBuiltItem.getTocName()); - assertEquals("Wrong references", baseLookup.extractReferences(element), lastBuiltItem.getReferences()); - } - - private ExtendedMetadataFileItem buildExtendedMetadataFileItem(Element element) { - ExtendedMetadataFileItem result = new ExtendedMetadataFileItem(String.valueOf(element)); - result.setPackageName("Some package name"); - result.setFullName("Some full name"); - result.setName("Some name"); - result.setHref("Some href"); - result.setParent("Some parent"); - result.setId("Some id"); - result.setNameWithType("Some name with type"); - result.setMethodContent("Some method content"); - result.setFieldContent("Some field content"); - result.setConstructorContent("Some constructor content"); - result.setOverload("Some overload"); - result.setParameters(Arrays.asList(new MethodParameter("method id", "method type", "method desc"))); - result.setExceptions(Arrays.asList(new ExceptionItem("ex type", "ex desc"))); - result.setReturn(new Return("return type", "return desc")); - result.setSummary("Some summary"); - result.setType("Some type"); - result.setJavaType("Some type"); - result.setContent("Some content"); - result.setTypeParameters(Arrays.asList(new TypeParameter("type param id"))); - result.setSuperclass(Arrays.asList("Some ")); - result.setInterfaces(Arrays.asList("Some interface")); - result.setTocName("Some toc name"); - result.addReferences(Set.of(new MetadataFileItem("ref uid"))); - return result; - } - - @Test - public void testExtractJavaType() { - assertEquals("Wrong javaType", baseLookup.extractJavaType(typeElement), null); - } + } + + @Test + public void determineComment() { + TypeElement element = elements.getTypeElement("com.microsoft.samples.subpackage.Person"); + when(environment.getDocTrees()).thenReturn(docTrees); + when(docTrees.getDocCommentTree(element)).thenReturn(docCommentTree); + doReturn(Arrays.asList(textTree, linkTree)).when(docCommentTree).getFullBody(); + when(textTree.getKind()).thenReturn(Kind.TEXT); + when(linkTree.getKind()).thenReturn(Kind.LINK); + when(linkTree.getReference()).thenReturn(referenceTree); + when(referenceTree.getSignature()).thenReturn("Some#signature"); + when(textTree.toString()).thenReturn("Some text 1"); + + String result = baseLookup.determineComment(element); + + verify(environment).getDocTrees(); + verify(docTrees).getDocCommentTree(element); + verify(docCommentTree).getFullBody(); + verify(textTree).getKind(); + verify(linkTree).getKind(); + verify(linkTree).getReference(); + verify(linkTree).getLabel(); + assertEquals( + "Wrong result", + result, + "Some text 1Some#signature"); + } + + @Test + public void makeTypeShort() { + assertEquals("Wrong result for primitive type", baseLookup.makeTypeShort("int"), "int"); + assertEquals("Wrong result", baseLookup.makeTypeShort("java.lang.String"), "String"); + assertEquals( + "Wrong result for inner class", + baseLookup.makeTypeShort("org.apache.commons.lang3.arch.Processor.Arch"), + "Processor.Arch"); + assertEquals( + "Wrong result for class with generic", + baseLookup.makeTypeShort("java.util.List"), + "List"); + assertEquals( + "Wrong result for inner class with generic", + baseLookup.makeTypeShort("java.util.List.Custom"), + "List.Custom"); + assertEquals( + "Wrong result for inner class with complex generic", + baseLookup.makeTypeShort("a.b.c.D.E.G>>"), + "D.E.G>>"); + assertEquals( + "Wrong result for inner class with generic & inheritance", + baseLookup.makeTypeShort("a.b.G"), + "G"); + } + + @Test + public void buildXrefTag() { + when(linkTree.getReference()).thenReturn(referenceTree); + when(referenceTree.getSignature()).thenReturn("Some#signature"); + when(linkTree.getLabel()).thenReturn(Collections.emptyList()); + + String result = baseLookup.buildXrefTag(linkTree); + + assertEquals( + "Wrong result", + result, + "Some#signature"); + } + + @Test + public void buildXrefTagWhenLabelPresents() { + when(linkTree.getReference()).thenReturn(referenceTree); + when(referenceTree.getSignature()).thenReturn("Some#signature"); + doReturn(Arrays.asList(textTree)).when(linkTree).getLabel(); + String labelValue = "IamLabel"; + when(textTree.toString()).thenReturn(labelValue); + + String result = baseLookup.buildXrefTag(linkTree); + + assertEquals( + "Wrong result", + result, + "" + + labelValue + + ""); + } + + @Test + public void buildCodeTag() { + String tagContent = "Some text ≤"; + when(literalTree.getBody()).thenReturn(textTree); + when(textTree.toString()).thenReturn(tagContent); + + String result = baseLookup.buildCodeTag(literalTree); + + assertEquals("Wrong result", result, "" + tagContent + ""); + } + + @Test + public void expandLiteralBody() { + String tagContent = "Some text ≤ \u2264"; + when(literalTree.getBody()).thenReturn(textTree); + when(textTree.toString()).thenReturn(tagContent); + + String result = baseLookup.expandLiteralBody(literalTree); + String expected = "Some text ≤ ≤"; + + assertEquals("Wrong result", result, expected); + } + + @Test + public void replaceLinksAndCodes() { + when(linkTree.getReference()).thenReturn(referenceTree); + when(referenceTree.getSignature()).thenReturn("Some#signature"); + when(linkTree.getLabel()).thenReturn(Collections.emptyList()); + String textTreeContent = "Some text content ≤ \u2264"; + when(literalTree.getBody()).thenReturn(textTree); + when(textTree.toString()).thenReturn(textTreeContent); + when(linkTree.getKind()).thenReturn(Kind.LINK); + when(literalTree.getKind()).thenReturn(Kind.CODE); + when(textTree.getKind()).thenReturn(Kind.TEXT); + + String result = baseLookup.replaceLinksAndCodes(Arrays.asList(linkTree, literalTree, textTree)); + + assertEquals( + "Wrong result", + result, + "" + + "Some#signatureSome text content ≤ ≤" + + textTreeContent); + } + + @Test + public void resolve() { + TypeElement element1 = elements.getTypeElement("com.microsoft.samples.subpackage.Person"); + TypeElement element2 = elements.getTypeElement("com.microsoft.samples.subpackage.Display"); + + ExtendedMetadataFileItem resultForKey1 = baseLookup.resolve(element1); + ExtendedMetadataFileItem resultForKey2 = baseLookup.resolve(element2); + ExtendedMetadataFileItem consequenceCallResultForKey1 = baseLookup.resolve(element1); + + assertEquals( + "Consequence call should return same instance", + resultForKey1, + consequenceCallResultForKey1); + assertNotEquals( + "Resolve for another key should return another instance", resultForKey2, resultForKey1); + } + + @Test + public void testExtractMethods() { + TypeElement element = elements.getTypeElement("com.microsoft.samples.subpackage.Person"); + + assertEquals( + "Wrong packageName", + baseLookup.extractPackageName(element), + lastBuiltItem.getPackageName()); + assertEquals( + "Wrong fullName", baseLookup.extractFullName(element), lastBuiltItem.getFullName()); + assertEquals("Wrong name", baseLookup.extractName(element), lastBuiltItem.getName()); + assertEquals("Wrong href", baseLookup.extractHref(element), lastBuiltItem.getHref()); + assertEquals("Wrong parent", baseLookup.extractParent(element), lastBuiltItem.getParent()); + assertEquals("Wrong id", baseLookup.extractId(element), lastBuiltItem.getId()); + assertEquals("Wrong uid", baseLookup.extractUid(element), lastBuiltItem.getUid()); + assertEquals( + "Wrong nameWithType", + baseLookup.extractNameWithType(element), + lastBuiltItem.getNameWithType()); + assertEquals( + "Wrong methodContent", + baseLookup.extractMethodContent(element), + lastBuiltItem.getMethodContent()); + assertEquals( + "Wrong fieldContent", + baseLookup.extractFieldContent(element), + lastBuiltItem.getFieldContent()); + assertEquals( + "Wrong constructorContent", + baseLookup.extractConstructorContent(element), + lastBuiltItem.getConstructorContent()); + assertEquals( + "Wrong overload", baseLookup.extractOverload(element), lastBuiltItem.getOverload()); + assertEquals( + "Wrong parameters", baseLookup.extractParameters(element), lastBuiltItem.getParameters()); + assertEquals( + "Wrong exceptions", baseLookup.extractExceptions(element), lastBuiltItem.getExceptions()); + + assertEquals( + "Wrong return", + baseLookup.extractReturn(element).getReturnType(), + lastBuiltItem.getReturn().getReturnType()); + assertEquals( + "Wrong return", + baseLookup.extractReturn(element).getReturnDescription(), + lastBuiltItem.getReturn().getReturnDescription()); + + assertEquals("Wrong summary", baseLookup.extractSummary(element), lastBuiltItem.getSummary()); + assertEquals("Wrong type", baseLookup.extractType(element), lastBuiltItem.getType()); + assertEquals("Wrong content", baseLookup.extractContent(element), lastBuiltItem.getContent()); + assertEquals( + "Wrong typeParameters", + baseLookup.extractTypeParameters(element), + lastBuiltItem.getTypeParameters()); + assertEquals( + "Wrong superclass", baseLookup.extractSuperclass(element), lastBuiltItem.getSuperclass()); + assertEquals( + "Wrong interfaces", baseLookup.extractInterfaces(element), lastBuiltItem.getInterfaces()); + assertEquals("Wrong tocName", baseLookup.extractTocName(element), lastBuiltItem.getTocName()); + assertEquals( + "Wrong references", baseLookup.extractReferences(element), lastBuiltItem.getReferences()); + } + + private ExtendedMetadataFileItem buildExtendedMetadataFileItem(Element element) { + ExtendedMetadataFileItem result = new ExtendedMetadataFileItem(String.valueOf(element)); + result.setPackageName("Some package name"); + result.setFullName("Some full name"); + result.setName("Some name"); + result.setHref("Some href"); + result.setParent("Some parent"); + result.setId("Some id"); + result.setNameWithType("Some name with type"); + result.setMethodContent("Some method content"); + result.setFieldContent("Some field content"); + result.setConstructorContent("Some constructor content"); + result.setOverload("Some overload"); + result.setParameters( + Arrays.asList(new MethodParameter("method id", "method type", "method desc"))); + result.setExceptions(Arrays.asList(new ExceptionItem("ex type", "ex desc"))); + result.setReturn(new Return("return type", "return desc")); + result.setSummary("Some summary"); + result.setType("Some type"); + result.setJavaType("Some type"); + result.setContent("Some content"); + result.setTypeParameters(Arrays.asList(new TypeParameter("type param id"))); + result.setSuperclass(Arrays.asList("Some ")); + result.setInterfaces(Arrays.asList("Some interface")); + result.setTocName("Some toc name"); + result.addReferences(Set.of(new MetadataFileItem("ref uid"))); + return result; + } + + @Test + public void testExtractJavaType() { + assertEquals("Wrong javaType", baseLookup.extractJavaType(typeElement), null); + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/lookup/ClassItemsLookupTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/lookup/ClassItemsLookupTest.java index 54cfac2b..950987d4 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/lookup/ClassItemsLookupTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/lookup/ClassItemsLookupTest.java @@ -1,5 +1,12 @@ package com.microsoft.lookup; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.google.testing.compile.CompilationRule; import com.microsoft.model.ExceptionItem; import com.microsoft.model.MethodParameter; @@ -14,6 +21,15 @@ import com.sun.source.doctree.TextTree; import com.sun.source.doctree.ThrowsTree; import com.sun.source.util.DocTrees; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import javax.lang.model.element.Element; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import javax.lang.model.util.ElementFilter; +import javax.lang.model.util.Elements; import jdk.javadoc.doclet.DocletEnvironment; import org.junit.Before; import org.junit.Rule; @@ -22,294 +38,291 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; -import javax.lang.model.element.Element; -import javax.lang.model.element.ExecutableElement; -import javax.lang.model.element.TypeElement; -import javax.lang.model.element.VariableElement; -import javax.lang.model.util.ElementFilter; -import javax.lang.model.util.Elements; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - @RunWith(MockitoJUnitRunner.class) public class ClassItemsLookupTest { - @Rule - public CompilationRule rule = new CompilationRule(); - private Elements elements; - private List allGenderElements; - private List allPersonElements; - private DocletEnvironment environment; - private DocTrees docTrees; - private DocCommentTree docCommentTree; - private ParamTree paramTree; - private ThrowsTree throwsTree; - private ReturnTree returnTree; - private DeprecatedTree deprecatedTree; - private TextTree textTree; - private IdentifierTree identifierTree; - private ClassItemsLookup classItemsLookup; - - @Before - public void setup() { - elements = rule.getElements(); - allGenderElements = elements.getTypeElement("com.microsoft.samples.subpackage.Person.IdentificationInfo.Gender") - .getEnclosedElements().stream().collect(Collectors.toList()); - allPersonElements = elements.getTypeElement("com.microsoft.samples.subpackage.Person") - .getEnclosedElements().stream().collect(Collectors.toList()); - environment = Mockito.mock(DocletEnvironment.class); - docTrees = Mockito.mock(DocTrees.class); - docCommentTree = Mockito.mock(DocCommentTree.class); - paramTree = Mockito.mock(ParamTree.class); - throwsTree = Mockito.mock(ThrowsTree.class); - returnTree = Mockito.mock(ReturnTree.class); - deprecatedTree = Mockito.mock(DeprecatedTree.class); - textTree = Mockito.mock(TextTree.class); - identifierTree = Mockito.mock(IdentifierTree.class); - classItemsLookup = new ClassItemsLookup(environment, Mockito.mock(ElementUtil.class)); - } - - @Test - public void extractParameters() { - TypeElement element = elements.getTypeElement("com.microsoft.samples.SuperHero"); - ExecutableElement method = ElementFilter.methodsIn(element.getEnclosedElements()).get(0); - - when(environment.getDocTrees()).thenReturn(docTrees); - when(docTrees.getDocCommentTree(method)).thenReturn(docCommentTree); - doReturn(Arrays.asList(paramTree)).when(docCommentTree).getBlockTags(); - when(paramTree.getKind()).thenReturn(Kind.PARAM); - when(textTree.getKind()).thenReturn(Kind.TEXT); - when(paramTree.getName()).thenReturn(identifierTree); - doReturn(Arrays.asList(textTree)).when(paramTree).getDescription(); - when(textTree.toString()).thenReturn("some text bla", "some text bla-bla"); - when(identifierTree.toString()).thenReturn("incomingDamage", "damageType"); - - List result = classItemsLookup.extractParameters(method); - - verify(environment, times(2)).getDocTrees(); - verify(docTrees, times(2)).getDocCommentTree(method); - verify(docCommentTree, times(2)).getBlockTags(); - assertEquals("Wrong parameters count", result.size(), 2); - - assertEquals("Wrong first param id", result.get(0).getId(), "incomingDamage"); - assertEquals("Wrong first param type", result.get(0).getType(), "int"); - assertEquals("Wrong first param description", result.get(0).getDescription(), "some text bla"); - - assertEquals("Wrong second param id", result.get(1).getId(), "damageType"); - assertEquals("Wrong second param type", result.get(1).getType(), "java.lang.String"); - assertEquals("Wrong second param description", result.get(1).getDescription(), "some text bla-bla"); - } - - @Test - public void extractParameterDescription() { - TypeElement element = elements.getTypeElement("com.microsoft.samples.SuperHero"); - ExecutableElement method = ElementFilter.methodsIn(element.getEnclosedElements()).get(0); - String paramName = "incomingDamage"; - - when(environment.getDocTrees()).thenReturn(docTrees); - when(docTrees.getDocCommentTree(method)).thenReturn(docCommentTree); - doReturn(Arrays.asList(paramTree)).when(docCommentTree).getBlockTags(); - when(paramTree.getKind()).thenReturn(Kind.PARAM); - doReturn(identifierTree).when(paramTree).getName(); - doReturn(Arrays.asList(textTree)).when(paramTree).getDescription(); - when(textTree.getKind()).thenReturn(Kind.TEXT); - when(textTree.toString()).thenReturn("some weird text"); - when(identifierTree.toString()).thenReturn(paramName); - - String result = classItemsLookup.extractParameterDescription(method, paramName); - - verify(environment).getDocTrees(); - verify(docTrees).getDocCommentTree(method); - verify(docCommentTree).getBlockTags(); - assertEquals("Wrong param description", result, "some weird text"); - } - - @Test - public void extractExceptions() { - TypeElement element = elements.getTypeElement("com.microsoft.samples.SuperHero"); - ExecutableElement method = ElementFilter.methodsIn(element.getEnclosedElements()).get(0); - - when(environment.getDocTrees()).thenReturn(docTrees); - when(docTrees.getDocCommentTree(method)).thenReturn(docCommentTree); - doReturn(Arrays.asList(throwsTree)).when(docCommentTree).getBlockTags(); - when(throwsTree.getKind()).thenReturn(Kind.THROWS); - doReturn(Arrays.asList(textTree)).when(throwsTree).getDescription(); - when(textTree.getKind()).thenReturn(Kind.TEXT); - when(textTree.toString()).thenReturn("some text"); - - List result = classItemsLookup.extractExceptions(method); - - verify(environment).getDocTrees(); - verify(docTrees).getDocCommentTree(method); - verify(docCommentTree).getBlockTags(); - verify(throwsTree).getKind(); - assertEquals("Wrong exceptions count", result.size(), 1); - assertEquals("Wrong type", result.get(0).getType(), "java.lang.IllegalArgumentException"); - assertEquals("Wrong description", result.get(0).getDescription(), "some text"); - } - - @Test - public void extractExceptionDescription() { - TypeElement element = elements.getTypeElement("com.microsoft.samples.SuperHero"); - ExecutableElement method = ElementFilter.methodsIn(element.getEnclosedElements()).get(0); - - when(environment.getDocTrees()).thenReturn(docTrees); - when(docTrees.getDocCommentTree(method)).thenReturn(docCommentTree); - doReturn(Arrays.asList(throwsTree)).when(docCommentTree).getBlockTags(); - when(throwsTree.getKind()).thenReturn(Kind.THROWS); - doReturn(Arrays.asList(textTree)).when(throwsTree).getDescription(); - when(textTree.getKind()).thenReturn(Kind.TEXT); - when(textTree.toString()).thenReturn("some weird text"); - - String result = classItemsLookup.extractExceptionDescription(method); - - verify(environment).getDocTrees(); - verify(docTrees).getDocCommentTree(method); - verify(docCommentTree).getBlockTags(); - verify(throwsTree).getKind(); - assertEquals("Wrong description", result, "some weird text"); - } - - @Test - public void extractReturnForExecutableElement() { - TypeElement element = elements.getTypeElement("com.microsoft.samples.SuperHero"); - ExecutableElement method0 = ElementFilter.methodsIn(element.getEnclosedElements()).get(0); - ExecutableElement method1 = ElementFilter.methodsIn(element.getEnclosedElements()).get(1); - ExecutableElement method2 = ElementFilter.methodsIn(element.getEnclosedElements()).get(2); - - when(environment.getDocTrees()).thenReturn(docTrees); - when(docTrees.getDocCommentTree(method0)).thenReturn(docCommentTree); - when(docTrees.getDocCommentTree(method1)).thenReturn(docCommentTree); - doReturn(Arrays.asList(returnTree)).when(docCommentTree).getBlockTags(); - when(returnTree.getKind()).thenReturn(Kind.RETURN); - doReturn(Arrays.asList(textTree)).when(returnTree).getDescription(); - when(textTree.getKind()).thenReturn(Kind.TEXT); - when(textTree.toString()).thenReturn("bla", "bla-bla"); - - checkReturnForExecutableElement(method0, "int", "bla"); - checkReturnForExecutableElement(method1, "java.lang.String", "bla-bla"); - checkVoidReturnForExecutableElement(method2); - - verify(environment, times(2)).getDocTrees(); - verify(docTrees).getDocCommentTree(method0); - verify(docTrees).getDocCommentTree(method1); - verify(docCommentTree, times(2)).getBlockTags(); - verify(returnTree, times(2)).getKind(); - verify(textTree, times(2)).getKind(); - } - - private void checkReturnForExecutableElement(ExecutableElement executableElement, String expectedType, - String expectedDescription) { - Return result = classItemsLookup.extractReturn(executableElement); - - assertEquals(result.getReturnType(), expectedType); - assertEquals(result.getReturnDescription(), expectedDescription); - } - - private void checkVoidReturnForExecutableElement(ExecutableElement executableElement) { - assertNull(classItemsLookup.extractReturn(executableElement)); - } - - @Test - public void extractReturnDescription() { - TypeElement element = elements.getTypeElement("com.microsoft.samples.SuperHero"); - ExecutableElement method0 = ElementFilter.methodsIn(element.getEnclosedElements()).get(0); - - when(environment.getDocTrees()).thenReturn(docTrees); - when(docTrees.getDocCommentTree(method0)).thenReturn(docCommentTree); - doReturn(Arrays.asList(returnTree)).when(docCommentTree).getBlockTags(); - when(returnTree.getKind()).thenReturn(Kind.RETURN); - when(textTree.getKind()).thenReturn(Kind.TEXT); - doReturn(Arrays.asList(textTree)).when(returnTree).getDescription(); - when(textTree.toString()).thenReturn("bla-bla description"); - - String result = classItemsLookup.extractReturnDescription(method0); - - verify(environment).getDocTrees(); - verify(docTrees).getDocCommentTree(method0); - verify(docCommentTree).getBlockTags(); - verify(returnTree).getKind(); - assertEquals("Wrong description", result, "bla-bla description"); - } - - @Test - public void extractReturnForVariableElement() { - TypeElement element = elements.getTypeElement("com.microsoft.samples.SuperHero"); - - checkReturnForVariableElement(element, 0, "java.lang.String"); - checkReturnForVariableElement(element, 1, "java.lang.String"); - checkReturnForVariableElement(element, 2, "int"); - checkReturnForVariableElement(element, 3, "int"); - checkReturnForVariableElement(element, 4, "java.lang.String"); - } - - private void checkReturnForVariableElement(TypeElement element, int variableNumber, String expectedType) { - VariableElement variableElement = ElementFilter.fieldsIn(element.getEnclosedElements()).get(variableNumber); - - Return result = classItemsLookup.extractReturn(variableElement); - - assertEquals(result.getReturnType(), expectedType); - } - - @Test - public void convertFullNameToOverload() { - assertEquals("Wrong result", classItemsLookup.convertFullNameToOverload( - "com.microsoft.samples.SuperHero.successfullyAttacked(int,java.lang.String)"), - "com.microsoft.samples.SuperHero.successfullyAttacked*"); - - assertEquals("Wrong result for case with generics", classItemsLookup.convertFullNameToOverload( - "com.microsoft.samples.subpackage.Display.show()"), - "com.microsoft.samples.subpackage.Display.show*"); - - assertEquals("Wrong result for constructor case", classItemsLookup.convertFullNameToOverload( - "com.microsoft.samples.SuperHero.SuperHero()"), - "com.microsoft.samples.SuperHero.SuperHero*"); - } - - @Test - public void determineTypeForEnumConstant() { - TypeElement element = elements - .getTypeElement("com.microsoft.samples.subpackage.Person.IdentificationInfo.Gender"); - - assertEquals(classItemsLookup.determineType(element.getEnclosedElements().get(0)), "Field"); - assertEquals(classItemsLookup.determineType(element.getEnclosedElements().get(1)), "Field"); - } - - @Test - public void testExtractJavaTypeStaticMethod() { - Element staticMethod = getElementByName(allGenderElements,"valueOf(java.lang.String)"); - assertEquals("Wrong javaType","static method", classItemsLookup.extractJavaType(staticMethod)); - } - - @Test - public void testExtractJavaTypeStaticField() { - Element field = getElementByName(allGenderElements,"FEMALE"); - assertEquals("Wrong javaType", "static field", classItemsLookup.extractJavaType(field)); - } - - @Test - public void testExtractJavaTypeNonStatic() { - Element constructor = getElementByName(allGenderElements,"Gender()"); - assertEquals("Wrong javaType",null, classItemsLookup.extractJavaType(constructor)); - - Element nonStaticMethod = getElementByName(allPersonElements,"getFirstName()"); - assertEquals("Wrong javaType",null, classItemsLookup.extractJavaType(nonStaticMethod)); - - Element nonStaticField = getElementByName(allPersonElements,"age"); - assertEquals("Wrong javaType",null, classItemsLookup.extractJavaType(nonStaticField)); - } - - private Element getElementByName(List elements, String name) { - return elements.stream() - .filter(e -> e.toString().equals(name)) - .findFirst().orElse(null); - } + @Rule public CompilationRule rule = new CompilationRule(); + private Elements elements; + private List allGenderElements; + private List allPersonElements; + private DocletEnvironment environment; + private DocTrees docTrees; + private DocCommentTree docCommentTree; + private ParamTree paramTree; + private ThrowsTree throwsTree; + private ReturnTree returnTree; + private DeprecatedTree deprecatedTree; + private TextTree textTree; + private IdentifierTree identifierTree; + private ClassItemsLookup classItemsLookup; + + @Before + public void setup() { + elements = rule.getElements(); + allGenderElements = + elements + .getTypeElement("com.microsoft.samples.subpackage.Person.IdentificationInfo.Gender") + .getEnclosedElements() + .stream() + .collect(Collectors.toList()); + allPersonElements = + elements + .getTypeElement("com.microsoft.samples.subpackage.Person") + .getEnclosedElements() + .stream() + .collect(Collectors.toList()); + environment = Mockito.mock(DocletEnvironment.class); + docTrees = Mockito.mock(DocTrees.class); + docCommentTree = Mockito.mock(DocCommentTree.class); + paramTree = Mockito.mock(ParamTree.class); + throwsTree = Mockito.mock(ThrowsTree.class); + returnTree = Mockito.mock(ReturnTree.class); + deprecatedTree = Mockito.mock(DeprecatedTree.class); + textTree = Mockito.mock(TextTree.class); + identifierTree = Mockito.mock(IdentifierTree.class); + classItemsLookup = new ClassItemsLookup(environment, Mockito.mock(ElementUtil.class)); + } + + @Test + public void extractParameters() { + TypeElement element = elements.getTypeElement("com.microsoft.samples.SuperHero"); + ExecutableElement method = ElementFilter.methodsIn(element.getEnclosedElements()).get(0); + + when(environment.getDocTrees()).thenReturn(docTrees); + when(docTrees.getDocCommentTree(method)).thenReturn(docCommentTree); + doReturn(Arrays.asList(paramTree)).when(docCommentTree).getBlockTags(); + when(paramTree.getKind()).thenReturn(Kind.PARAM); + when(textTree.getKind()).thenReturn(Kind.TEXT); + when(paramTree.getName()).thenReturn(identifierTree); + doReturn(Arrays.asList(textTree)).when(paramTree).getDescription(); + when(textTree.toString()).thenReturn("some text bla", "some text bla-bla"); + when(identifierTree.toString()).thenReturn("incomingDamage", "damageType"); + + List result = classItemsLookup.extractParameters(method); + + verify(environment, times(2)).getDocTrees(); + verify(docTrees, times(2)).getDocCommentTree(method); + verify(docCommentTree, times(2)).getBlockTags(); + assertEquals("Wrong parameters count", result.size(), 2); + + assertEquals("Wrong first param id", result.get(0).getId(), "incomingDamage"); + assertEquals("Wrong first param type", result.get(0).getType(), "int"); + assertEquals("Wrong first param description", result.get(0).getDescription(), "some text bla"); + + assertEquals("Wrong second param id", result.get(1).getId(), "damageType"); + assertEquals("Wrong second param type", result.get(1).getType(), "java.lang.String"); + assertEquals( + "Wrong second param description", result.get(1).getDescription(), "some text bla-bla"); + } + + @Test + public void extractParameterDescription() { + TypeElement element = elements.getTypeElement("com.microsoft.samples.SuperHero"); + ExecutableElement method = ElementFilter.methodsIn(element.getEnclosedElements()).get(0); + String paramName = "incomingDamage"; + + when(environment.getDocTrees()).thenReturn(docTrees); + when(docTrees.getDocCommentTree(method)).thenReturn(docCommentTree); + doReturn(Arrays.asList(paramTree)).when(docCommentTree).getBlockTags(); + when(paramTree.getKind()).thenReturn(Kind.PARAM); + doReturn(identifierTree).when(paramTree).getName(); + doReturn(Arrays.asList(textTree)).when(paramTree).getDescription(); + when(textTree.getKind()).thenReturn(Kind.TEXT); + when(textTree.toString()).thenReturn("some weird text"); + when(identifierTree.toString()).thenReturn(paramName); + + String result = classItemsLookup.extractParameterDescription(method, paramName); + + verify(environment).getDocTrees(); + verify(docTrees).getDocCommentTree(method); + verify(docCommentTree).getBlockTags(); + assertEquals("Wrong param description", result, "some weird text"); + } + + @Test + public void extractExceptions() { + TypeElement element = elements.getTypeElement("com.microsoft.samples.SuperHero"); + ExecutableElement method = ElementFilter.methodsIn(element.getEnclosedElements()).get(0); + + when(environment.getDocTrees()).thenReturn(docTrees); + when(docTrees.getDocCommentTree(method)).thenReturn(docCommentTree); + doReturn(Arrays.asList(throwsTree)).when(docCommentTree).getBlockTags(); + when(throwsTree.getKind()).thenReturn(Kind.THROWS); + doReturn(Arrays.asList(textTree)).when(throwsTree).getDescription(); + when(textTree.getKind()).thenReturn(Kind.TEXT); + when(textTree.toString()).thenReturn("some text"); + + List result = classItemsLookup.extractExceptions(method); + + verify(environment).getDocTrees(); + verify(docTrees).getDocCommentTree(method); + verify(docCommentTree).getBlockTags(); + verify(throwsTree).getKind(); + assertEquals("Wrong exceptions count", result.size(), 1); + assertEquals("Wrong type", result.get(0).getType(), "java.lang.IllegalArgumentException"); + assertEquals("Wrong description", result.get(0).getDescription(), "some text"); + } + + @Test + public void extractExceptionDescription() { + TypeElement element = elements.getTypeElement("com.microsoft.samples.SuperHero"); + ExecutableElement method = ElementFilter.methodsIn(element.getEnclosedElements()).get(0); + + when(environment.getDocTrees()).thenReturn(docTrees); + when(docTrees.getDocCommentTree(method)).thenReturn(docCommentTree); + doReturn(Arrays.asList(throwsTree)).when(docCommentTree).getBlockTags(); + when(throwsTree.getKind()).thenReturn(Kind.THROWS); + doReturn(Arrays.asList(textTree)).when(throwsTree).getDescription(); + when(textTree.getKind()).thenReturn(Kind.TEXT); + when(textTree.toString()).thenReturn("some weird text"); + + String result = classItemsLookup.extractExceptionDescription(method); + + verify(environment).getDocTrees(); + verify(docTrees).getDocCommentTree(method); + verify(docCommentTree).getBlockTags(); + verify(throwsTree).getKind(); + assertEquals("Wrong description", result, "some weird text"); + } + + @Test + public void extractReturnForExecutableElement() { + TypeElement element = elements.getTypeElement("com.microsoft.samples.SuperHero"); + ExecutableElement method0 = ElementFilter.methodsIn(element.getEnclosedElements()).get(0); + ExecutableElement method1 = ElementFilter.methodsIn(element.getEnclosedElements()).get(1); + ExecutableElement method2 = ElementFilter.methodsIn(element.getEnclosedElements()).get(2); + + when(environment.getDocTrees()).thenReturn(docTrees); + when(docTrees.getDocCommentTree(method0)).thenReturn(docCommentTree); + when(docTrees.getDocCommentTree(method1)).thenReturn(docCommentTree); + doReturn(Arrays.asList(returnTree)).when(docCommentTree).getBlockTags(); + when(returnTree.getKind()).thenReturn(Kind.RETURN); + doReturn(Arrays.asList(textTree)).when(returnTree).getDescription(); + when(textTree.getKind()).thenReturn(Kind.TEXT); + when(textTree.toString()).thenReturn("bla", "bla-bla"); + + checkReturnForExecutableElement(method0, "int", "bla"); + checkReturnForExecutableElement(method1, "java.lang.String", "bla-bla"); + checkVoidReturnForExecutableElement(method2); + + verify(environment, times(2)).getDocTrees(); + verify(docTrees).getDocCommentTree(method0); + verify(docTrees).getDocCommentTree(method1); + verify(docCommentTree, times(2)).getBlockTags(); + verify(returnTree, times(2)).getKind(); + verify(textTree, times(2)).getKind(); + } + + private void checkReturnForExecutableElement( + ExecutableElement executableElement, String expectedType, String expectedDescription) { + Return result = classItemsLookup.extractReturn(executableElement); + + assertEquals(result.getReturnType(), expectedType); + assertEquals(result.getReturnDescription(), expectedDescription); + } + + private void checkVoidReturnForExecutableElement(ExecutableElement executableElement) { + assertNull(classItemsLookup.extractReturn(executableElement)); + } + + @Test + public void extractReturnDescription() { + TypeElement element = elements.getTypeElement("com.microsoft.samples.SuperHero"); + ExecutableElement method0 = ElementFilter.methodsIn(element.getEnclosedElements()).get(0); + + when(environment.getDocTrees()).thenReturn(docTrees); + when(docTrees.getDocCommentTree(method0)).thenReturn(docCommentTree); + doReturn(Arrays.asList(returnTree)).when(docCommentTree).getBlockTags(); + when(returnTree.getKind()).thenReturn(Kind.RETURN); + when(textTree.getKind()).thenReturn(Kind.TEXT); + doReturn(Arrays.asList(textTree)).when(returnTree).getDescription(); + when(textTree.toString()).thenReturn("bla-bla description"); + + String result = classItemsLookup.extractReturnDescription(method0); + + verify(environment).getDocTrees(); + verify(docTrees).getDocCommentTree(method0); + verify(docCommentTree).getBlockTags(); + verify(returnTree).getKind(); + assertEquals("Wrong description", result, "bla-bla description"); + } + + @Test + public void extractReturnForVariableElement() { + TypeElement element = elements.getTypeElement("com.microsoft.samples.SuperHero"); + + checkReturnForVariableElement(element, 0, "java.lang.String"); + checkReturnForVariableElement(element, 1, "java.lang.String"); + checkReturnForVariableElement(element, 2, "int"); + checkReturnForVariableElement(element, 3, "int"); + checkReturnForVariableElement(element, 4, "java.lang.String"); + } + + private void checkReturnForVariableElement( + TypeElement element, int variableNumber, String expectedType) { + VariableElement variableElement = + ElementFilter.fieldsIn(element.getEnclosedElements()).get(variableNumber); + + Return result = classItemsLookup.extractReturn(variableElement); + + assertEquals(result.getReturnType(), expectedType); + } + + @Test + public void convertFullNameToOverload() { + assertEquals( + "Wrong result", + classItemsLookup.convertFullNameToOverload( + "com.microsoft.samples.SuperHero.successfullyAttacked(int,java.lang.String)"), + "com.microsoft.samples.SuperHero.successfullyAttacked*"); + + assertEquals( + "Wrong result for case with generics", + classItemsLookup.convertFullNameToOverload( + "com.microsoft.samples.subpackage.Display.show()"), + "com.microsoft.samples.subpackage.Display.show*"); + + assertEquals( + "Wrong result for constructor case", + classItemsLookup.convertFullNameToOverload("com.microsoft.samples.SuperHero.SuperHero()"), + "com.microsoft.samples.SuperHero.SuperHero*"); + } + + @Test + public void determineTypeForEnumConstant() { + TypeElement element = + elements.getTypeElement( + "com.microsoft.samples.subpackage.Person.IdentificationInfo.Gender"); + + assertEquals(classItemsLookup.determineType(element.getEnclosedElements().get(0)), "Field"); + assertEquals(classItemsLookup.determineType(element.getEnclosedElements().get(1)), "Field"); + } + + @Test + public void testExtractJavaTypeStaticMethod() { + Element staticMethod = getElementByName(allGenderElements, "valueOf(java.lang.String)"); + assertEquals("Wrong javaType", "static method", classItemsLookup.extractJavaType(staticMethod)); + } + + @Test + public void testExtractJavaTypeStaticField() { + Element field = getElementByName(allGenderElements, "FEMALE"); + assertEquals("Wrong javaType", "static field", classItemsLookup.extractJavaType(field)); + } + + @Test + public void testExtractJavaTypeNonStatic() { + Element constructor = getElementByName(allGenderElements, "Gender()"); + assertEquals("Wrong javaType", null, classItemsLookup.extractJavaType(constructor)); + + Element nonStaticMethod = getElementByName(allPersonElements, "getFirstName()"); + assertEquals("Wrong javaType", null, classItemsLookup.extractJavaType(nonStaticMethod)); + + Element nonStaticField = getElementByName(allPersonElements, "age"); + assertEquals("Wrong javaType", null, classItemsLookup.extractJavaType(nonStaticField)); + } + + private Element getElementByName(List elements, String name) { + return elements.stream().filter(e -> e.toString().equals(name)).findFirst().orElse(null); + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/lookup/ClassLookupTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/lookup/ClassLookupTest.java index f2c4869d..92f90c9b 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/lookup/ClassLookupTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/lookup/ClassLookupTest.java @@ -32,190 +32,213 @@ @RunWith(MockitoJUnitRunner.class) public class ClassLookupTest { - @Rule - public CompilationRule rule = new CompilationRule(); - private Elements elements; - private ClassLookup classLookup; - private DocletEnvironment environment; - private DocTrees docTrees; - private DocTree docTree; - private DocCommentTree docCommentTree; - private DeprecatedTree deprecatedTree; - private TextTree textTree; - private TypeMirror typeMirror; - - @Before - public void setup() { - elements = rule.getElements(); - environment = Mockito.mock(DocletEnvironment.class); - classLookup = new ClassLookup(environment, Mockito.mock(ElementUtil.class)); - docTrees = Mockito.mock(DocTrees.class); - docTree = Mockito.mock(DocTree.class); - docCommentTree = Mockito.mock(DocCommentTree.class); - deprecatedTree = Mockito.mock(DeprecatedTree.class); - textTree = Mockito.mock(TextTree.class); - typeMirror = Mockito.mock(TypeMirror.class); - } - - @Test - public void determineTypeParameters() { - TypeElement element = elements.getTypeElement("com.microsoft.samples.subpackage.Person"); - - List result = classLookup.determineTypeParameters(element); - - assertEquals("Wrong type params size", result.size(), 1); - assertEquals("Wrong type parameter id", result.get(0).getId(), "T"); - } - - @Test - public void determineSuperclass() { - TypeElement element = elements.getTypeElement("com.microsoft.samples.subpackage.Person"); - - String result = classLookup.determineSuperclass(element); - - assertEquals("Wrong result", result, "java.lang.Object"); - } - - @Test - public void determineSuperclassForChildClass() { - TypeElement element = elements.getTypeElement("com.microsoft.samples.SuperHero"); - - String result = classLookup.determineSuperclass(element); - - assertEquals("Wrong result", result, "com.microsoft.samples.subpackage.Person"); - } - - @Test - public void determineSuperclassForEnum() { - TypeElement element = elements - .getTypeElement("com.microsoft.samples.subpackage.Person.IdentificationInfo.Gender"); - - String result = classLookup.determineSuperclass(element); - - assertEquals("Wrong result", result, - "java.lang.Enum"); - } - - @Test - public void determineClassContent() { - TypeElement element = elements.getTypeElement("com.microsoft.samples.SuperHero"); - ExtendedMetadataFileItem container = new ExtendedMetadataFileItem("UID"); - - classLookup.populateContent(element, "SuperHero", container); - - assertEquals("Wrong content", container.getContent(), - "public class SuperHero extends Person implements Serializable, Cloneable"); - - - assertTrue("Wrong set of interfaces", container.getInterfaces().contains("java.io.Serializable")); - assertTrue("Wrong set of interfaces", container.getInterfaces().contains("java.lang.Cloneable")); - } - - @Test - public void determineClassContentForInterface() { - TypeElement element = elements.getTypeElement("com.microsoft.samples.subpackage.Display"); - ExtendedMetadataFileItem container = new ExtendedMetadataFileItem("UID"); - - classLookup.populateContent(element, "Display", container); - - assertEquals("Wrong content", container.getContent(), - "public interface Display extends Serializable, List>"); - - - assertTrue("Wrong set of interfaces", container.getInterfaces().contains("java.io.Serializable")); - assertTrue("Wrong set of interfaces", container.getInterfaces().contains("java.util.List>")); - } - - @Test - public void determineClassContentForEnum() { - TypeElement element = elements - .getTypeElement("com.microsoft.samples.subpackage.Person.IdentificationInfo.Gender"); - ExtendedMetadataFileItem container = new ExtendedMetadataFileItem("UID"); - - classLookup.populateContent(element, "Person.IdentificationInfo.Gender", container); - - assertEquals("Wrong content", container.getContent(), - "public enum Person.IdentificationInfo.Gender extends Enum"); - } - - @Test - public void determineClassContentForStaticClass() { - TypeElement element = elements.getTypeElement("com.microsoft.samples.subpackage.Person.IdentificationInfo"); - ExtendedMetadataFileItem container = new ExtendedMetadataFileItem("UID"); - - classLookup.populateContent(element, "Person.IdentificationInfo", container); - - assertEquals("Wrong content", container.getContent(), "public static class Person.IdentificationInfo"); - } - - @Test - public void determineTypeForInterface() { - TypeElement element = elements.getTypeElement("com.microsoft.samples.subpackage.Display"); - - assertEquals(classLookup.determineType(element), "Interface"); - } - - @Test - public void determineTypeForEnum() { - TypeElement element = elements - .getTypeElement("com.microsoft.samples.subpackage.Person.IdentificationInfo.Gender"); - - assertEquals(classLookup.determineType(element), "Enum"); - } - - @Test - public void determineTypeForClass() { - TypeElement element = elements.getTypeElement("com.microsoft.samples.subpackage.Person.IdentificationInfo"); - - assertEquals(classLookup.determineType(element), "Class"); - } - - @Test - public void extractStatusDeprecated() { - TypeElement element = elements.getTypeElement("com.microsoft.samples.agreements.AgreementDetailsCollectionOperations"); - - when(environment.getDocTrees()).thenReturn(docTrees); - when(docTrees.getDocCommentTree(element)).thenReturn(docCommentTree); - doReturn(Arrays.asList(deprecatedTree)).when(docCommentTree).getBlockTags(); - when(deprecatedTree.getKind()).thenReturn(DocTree.Kind.DEPRECATED); - - String result = classLookup.extractStatus(element); - - verify(environment).getDocTrees(); - verify(docTrees).getDocCommentTree(element); - verify(docCommentTree).getBlockTags(); - verify(deprecatedTree).getKind(); - assertEquals("Wrong description", result, Status.DEPRECATED.toString()); - } - - @Test - public void extractStatusNotDeprecated() { - TypeElement element = elements.getTypeElement("com.microsoft.samples.agreements.AgreementDetailsCollectionOperations"); - - when(environment.getDocTrees()).thenReturn(docTrees); - when(docTrees.getDocCommentTree(element)).thenReturn(docCommentTree); - doReturn(Arrays.asList()).when(docCommentTree).getBlockTags(); - - String result = classLookup.extractStatus(element); - - verify(environment).getDocTrees(); - verify(docTrees).getDocCommentTree(element); - verify(docCommentTree).getBlockTags(); - assertEquals("Wrong description", result, null); - } - - @Test - public void testExtractJavaType() { - TypeElement typeElement = elements.getTypeElement("com.microsoft.samples.google.ValidationException"); - assertEquals("Wrong javaType", classLookup.extractJavaType(typeElement), "exception"); - - typeElement = elements.getTypeElement("com.microsoft.samples.google.RecognitionAudio"); - assertEquals("Wrong javaType", classLookup.extractJavaType(typeElement), null); - - typeElement = elements.getTypeElement("com.microsoft.samples.google.BetaApi"); - assertEquals("Wrong javaType", classLookup.extractJavaType(typeElement), "annotationtype"); - - typeElement = elements.getTypeElement("com.microsoft.samples.IPartner"); - assertEquals("Wrong javaType", classLookup.extractJavaType(typeElement), null); - } + @Rule public CompilationRule rule = new CompilationRule(); + private Elements elements; + private ClassLookup classLookup; + private DocletEnvironment environment; + private DocTrees docTrees; + private DocTree docTree; + private DocCommentTree docCommentTree; + private DeprecatedTree deprecatedTree; + private TextTree textTree; + private TypeMirror typeMirror; + + @Before + public void setup() { + elements = rule.getElements(); + environment = Mockito.mock(DocletEnvironment.class); + classLookup = new ClassLookup(environment, Mockito.mock(ElementUtil.class)); + docTrees = Mockito.mock(DocTrees.class); + docTree = Mockito.mock(DocTree.class); + docCommentTree = Mockito.mock(DocCommentTree.class); + deprecatedTree = Mockito.mock(DeprecatedTree.class); + textTree = Mockito.mock(TextTree.class); + typeMirror = Mockito.mock(TypeMirror.class); + } + + @Test + public void determineTypeParameters() { + TypeElement element = elements.getTypeElement("com.microsoft.samples.subpackage.Person"); + + List result = classLookup.determineTypeParameters(element); + + assertEquals("Wrong type params size", result.size(), 1); + assertEquals("Wrong type parameter id", result.get(0).getId(), "T"); + } + + @Test + public void determineSuperclass() { + TypeElement element = elements.getTypeElement("com.microsoft.samples.subpackage.Person"); + + String result = classLookup.determineSuperclass(element); + + assertEquals("Wrong result", result, "java.lang.Object"); + } + + @Test + public void determineSuperclassForChildClass() { + TypeElement element = elements.getTypeElement("com.microsoft.samples.SuperHero"); + + String result = classLookup.determineSuperclass(element); + + assertEquals("Wrong result", result, "com.microsoft.samples.subpackage.Person"); + } + + @Test + public void determineSuperclassForEnum() { + TypeElement element = + elements.getTypeElement( + "com.microsoft.samples.subpackage.Person.IdentificationInfo.Gender"); + + String result = classLookup.determineSuperclass(element); + + assertEquals( + "Wrong result", + result, + "java.lang.Enum"); + } + + @Test + public void determineClassContent() { + TypeElement element = elements.getTypeElement("com.microsoft.samples.SuperHero"); + ExtendedMetadataFileItem container = new ExtendedMetadataFileItem("UID"); + + classLookup.populateContent(element, "SuperHero", container); + + assertEquals( + "Wrong content", + container.getContent(), + "public class SuperHero extends Person implements Serializable, Cloneable"); + + assertTrue( + "Wrong set of interfaces", container.getInterfaces().contains("java.io.Serializable")); + assertTrue( + "Wrong set of interfaces", container.getInterfaces().contains("java.lang.Cloneable")); + } + + @Test + public void determineClassContentForInterface() { + TypeElement element = elements.getTypeElement("com.microsoft.samples.subpackage.Display"); + ExtendedMetadataFileItem container = new ExtendedMetadataFileItem("UID"); + + classLookup.populateContent(element, "Display", container); + + assertEquals( + "Wrong content", + container.getContent(), + "public interface Display extends Serializable, List>"); + + assertTrue( + "Wrong set of interfaces", container.getInterfaces().contains("java.io.Serializable")); + assertTrue( + "Wrong set of interfaces", + container + .getInterfaces() + .contains("java.util.List>")); + } + + @Test + public void determineClassContentForEnum() { + TypeElement element = + elements.getTypeElement( + "com.microsoft.samples.subpackage.Person.IdentificationInfo.Gender"); + ExtendedMetadataFileItem container = new ExtendedMetadataFileItem("UID"); + + classLookup.populateContent(element, "Person.IdentificationInfo.Gender", container); + + assertEquals( + "Wrong content", + container.getContent(), + "public enum Person.IdentificationInfo.Gender extends Enum"); + } + + @Test + public void determineClassContentForStaticClass() { + TypeElement element = + elements.getTypeElement("com.microsoft.samples.subpackage.Person.IdentificationInfo"); + ExtendedMetadataFileItem container = new ExtendedMetadataFileItem("UID"); + + classLookup.populateContent(element, "Person.IdentificationInfo", container); + + assertEquals( + "Wrong content", container.getContent(), "public static class Person.IdentificationInfo"); + } + + @Test + public void determineTypeForInterface() { + TypeElement element = elements.getTypeElement("com.microsoft.samples.subpackage.Display"); + + assertEquals(classLookup.determineType(element), "Interface"); + } + + @Test + public void determineTypeForEnum() { + TypeElement element = + elements.getTypeElement( + "com.microsoft.samples.subpackage.Person.IdentificationInfo.Gender"); + + assertEquals(classLookup.determineType(element), "Enum"); + } + + @Test + public void determineTypeForClass() { + TypeElement element = + elements.getTypeElement("com.microsoft.samples.subpackage.Person.IdentificationInfo"); + + assertEquals(classLookup.determineType(element), "Class"); + } + + @Test + public void extractStatusDeprecated() { + TypeElement element = + elements.getTypeElement( + "com.microsoft.samples.agreements.AgreementDetailsCollectionOperations"); + + when(environment.getDocTrees()).thenReturn(docTrees); + when(docTrees.getDocCommentTree(element)).thenReturn(docCommentTree); + doReturn(Arrays.asList(deprecatedTree)).when(docCommentTree).getBlockTags(); + when(deprecatedTree.getKind()).thenReturn(DocTree.Kind.DEPRECATED); + + String result = classLookup.extractStatus(element); + + verify(environment).getDocTrees(); + verify(docTrees).getDocCommentTree(element); + verify(docCommentTree).getBlockTags(); + verify(deprecatedTree).getKind(); + assertEquals("Wrong description", result, Status.DEPRECATED.toString()); + } + + @Test + public void extractStatusNotDeprecated() { + TypeElement element = + elements.getTypeElement( + "com.microsoft.samples.agreements.AgreementDetailsCollectionOperations"); + + when(environment.getDocTrees()).thenReturn(docTrees); + when(docTrees.getDocCommentTree(element)).thenReturn(docCommentTree); + doReturn(Arrays.asList()).when(docCommentTree).getBlockTags(); + + String result = classLookup.extractStatus(element); + + verify(environment).getDocTrees(); + verify(docTrees).getDocCommentTree(element); + verify(docCommentTree).getBlockTags(); + assertEquals("Wrong description", result, null); + } + + @Test + public void testExtractJavaType() { + TypeElement typeElement = + elements.getTypeElement("com.microsoft.samples.google.ValidationException"); + assertEquals("Wrong javaType", classLookup.extractJavaType(typeElement), "exception"); + + typeElement = elements.getTypeElement("com.microsoft.samples.google.RecognitionAudio"); + assertEquals("Wrong javaType", classLookup.extractJavaType(typeElement), null); + + typeElement = elements.getTypeElement("com.microsoft.samples.google.BetaApi"); + assertEquals("Wrong javaType", classLookup.extractJavaType(typeElement), "annotationtype"); + + typeElement = elements.getTypeElement("com.microsoft.samples.IPartner"); + assertEquals("Wrong javaType", classLookup.extractJavaType(typeElement), null); + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/lookup/PackageLookupTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/lookup/PackageLookupTest.java index 90408fb7..0cdbbf10 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/lookup/PackageLookupTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/lookup/PackageLookupTest.java @@ -1,7 +1,11 @@ package com.microsoft.lookup; +import static org.junit.Assert.assertEquals; + import com.google.testing.compile.CompilationRule; import com.microsoft.model.Status; +import javax.lang.model.element.PackageElement; +import javax.lang.model.util.Elements; import jdk.javadoc.doclet.DocletEnvironment; import org.junit.Before; import org.junit.Rule; @@ -10,52 +14,47 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; -import javax.lang.model.element.PackageElement; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Elements; - -import static org.junit.Assert.assertEquals; - @RunWith(MockitoJUnitRunner.class) public class PackageLookupTest { - @Rule - public CompilationRule rule = new CompilationRule(); - private Elements elements; - private PackageLookup packageLookup; - private DocletEnvironment environment; - - @Before - public void setup() { - elements = rule.getElements(); - environment = Mockito.mock(DocletEnvironment.class); - packageLookup = new PackageLookup(environment); - } - - @Test - public void extractPackageContent() { - PackageElement element = elements.getPackageElement("com.microsoft.samples"); - - String result = packageLookup.determinePackageContent(element); - - assertEquals("Wrong result", result, "package com.microsoft.samples"); - } - - @Test - public void extractPackageStatus() { - PackageElement elementBeta = elements.getPackageElement("com.microsoft.samples.google.v1beta"); - PackageElement elementAlpha = elements.getPackageElement("com.microsoft.samples.google.v1p1alpha"); - - String resultA = packageLookup.extractStatus(elementAlpha); - String resultB = packageLookup.extractStatus(elementBeta); - - assertEquals("Wrong result", resultA, Status.ALPHA.toString()); - assertEquals("Wrong result", resultB, Status.BETA.toString()); - } - - @Test - public void testExtractJavaType() { - PackageElement packageElement = elements.getPackageElement("com.microsoft.samples.google.v1beta"); - assertEquals("Wrong javaType", packageLookup.extractJavaType(packageElement), "package"); - } + @Rule public CompilationRule rule = new CompilationRule(); + private Elements elements; + private PackageLookup packageLookup; + private DocletEnvironment environment; + + @Before + public void setup() { + elements = rule.getElements(); + environment = Mockito.mock(DocletEnvironment.class); + packageLookup = new PackageLookup(environment); + } + + @Test + public void extractPackageContent() { + PackageElement element = elements.getPackageElement("com.microsoft.samples"); + + String result = packageLookup.determinePackageContent(element); + + assertEquals("Wrong result", result, "package com.microsoft.samples"); + } + + @Test + public void extractPackageStatus() { + PackageElement elementBeta = elements.getPackageElement("com.microsoft.samples.google.v1beta"); + PackageElement elementAlpha = + elements.getPackageElement("com.microsoft.samples.google.v1p1alpha"); + + String resultA = packageLookup.extractStatus(elementAlpha); + String resultB = packageLookup.extractStatus(elementBeta); + + assertEquals("Wrong result", resultA, Status.ALPHA.toString()); + assertEquals("Wrong result", resultB, Status.BETA.toString()); + } + + @Test + public void testExtractJavaType() { + PackageElement packageElement = + elements.getPackageElement("com.microsoft.samples.google.v1beta"); + assertEquals("Wrong javaType", packageLookup.extractJavaType(packageElement), "package"); + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/model/MetadataFileItemTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/model/MetadataFileItemTest.java index 534be760..a5a9bd8f 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/model/MetadataFileItemTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/model/MetadataFileItemTest.java @@ -1,163 +1,165 @@ package com.microsoft.model; -import org.junit.Test; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - -import static org.junit.Assert.*; +import org.junit.Test; public class MetadataFileItemTest { - @Test - public void testEquals() { - MetadataFileItem object1 = new MetadataFileItem("123"); - MetadataFileItem object2 = new MetadataFileItem("1234"); - MetadataFileItem object3 = new MetadataFileItem("123"); - - assertTrue("Should be equal to self", object1.equals(object1)); - assertFalse("Should not be equal to null", object1.equals(null)); - assertFalse("Should not be equal to object of another type", object1.equals(123)); - assertFalse("Should not be equal to object with another uid", object1.equals(object2)); - assertTrue("Should be equal to object with same uid", object1.equals(object3)); - } - - @Test - public void testHashCode() { - String uid = "123"; - MetadataFileItem object = new MetadataFileItem(uid); - - assertEquals("Wrong result", uid.hashCode(), object.hashCode()); - } - - @Test - public void setTypeParameters() { - MetadataFileItem object = new MetadataFileItem("123"); - List typeParams = new ArrayList<>(); - - object.setTypeParameters(typeParams); + @Test + public void testEquals() { + MetadataFileItem object1 = new MetadataFileItem("123"); + MetadataFileItem object2 = new MetadataFileItem("1234"); + MetadataFileItem object3 = new MetadataFileItem("123"); - assertNotNull("Syntax should not be null", object.getSyntax()); - assertEquals("Wrong typeParameters value", object.getSyntax().getTypeParameters(), typeParams); - } + assertTrue("Should be equal to self", object1.equals(object1)); + assertFalse("Should not be equal to null", object1.equals(null)); + assertFalse("Should not be equal to object of another type", object1.equals(123)); + assertFalse("Should not be equal to object with another uid", object1.equals(object2)); + assertTrue("Should be equal to object with same uid", object1.equals(object3)); + } - @Test - public void setTypeParametersWhenSyntaxAlreadyPresent() { - MetadataFileItem object = new MetadataFileItem("123"); - Syntax existingSyntax = new Syntax(); - object.setSyntax(existingSyntax); - List typeParams = new ArrayList<>(); + @Test + public void testHashCode() { + String uid = "123"; + MetadataFileItem object = new MetadataFileItem(uid); - object.setTypeParameters(typeParams); + assertEquals("Wrong result", uid.hashCode(), object.hashCode()); + } - assertEquals("Syntax object should remain the same", object.getSyntax(), existingSyntax); - assertEquals("Wrong typeParameters value", object.getSyntax().getTypeParameters(), typeParams); - } + @Test + public void setTypeParameters() { + MetadataFileItem object = new MetadataFileItem("123"); + List typeParams = new ArrayList<>(); - @Test - public void setParameters() { - MetadataFileItem object = new MetadataFileItem("123"); - List params = new ArrayList<>(); - - object.setParameters(params); - - assertNotNull("Syntax should not be null", object.getSyntax()); - assertEquals("Wrong parameters value", object.getSyntax().getParameters(), params); - } - - @Test - public void setParametersWhenSyntaxAlreadyPresent() { - MetadataFileItem object = new MetadataFileItem("123"); - Syntax existingSyntax = new Syntax(); - object.setSyntax(existingSyntax); - List params = new ArrayList<>(); - - object.setParameters(params); - - assertEquals("Syntax object should remain the same", object.getSyntax(), existingSyntax); - assertEquals("Wrong parameters value", object.getSyntax().getParameters(), params); - } - - @Test - public void setReturn() { - MetadataFileItem object = new MetadataFileItem("123"); - Return returnValue = new Return("type"); - - object.setReturn(returnValue); - - assertNotNull("Syntax should not be null", object.getSyntax()); - assertEquals("Wrong return value", object.getSyntax().getReturnValue(), returnValue); - } - - @Test - public void setReturnWhenSyntaxAlreadyPresent() { - MetadataFileItem object = new MetadataFileItem("123"); - Syntax existingSyntax = new Syntax(); - object.setSyntax(existingSyntax); - Return returnValue = new Return("type"); - - object.setReturn(returnValue); - - assertEquals("Syntax object should remain the same", object.getSyntax(), existingSyntax); - assertEquals("Wrong return value", object.getSyntax().getReturnValue(), returnValue); - } - - @Test - public void setContent() { - MetadataFileItem object = new MetadataFileItem("123"); - String content = "Some content"; - - object.setContent(content); - - assertNotNull("Syntax should not be null", object.getSyntax()); - assertEquals("Wrong content value", object.getSyntax().getContent(), content); - } - - @Test - public void setContentWhenSyntaxAlreadyPresent() { - MetadataFileItem object = new MetadataFileItem("123"); - Syntax existingSyntax = new Syntax(); - object.setSyntax(existingSyntax); - String content = "Some content"; - - object.setContent(content); + object.setTypeParameters(typeParams); - assertEquals("Syntax object should remain the same", object.getSyntax(), existingSyntax); - assertEquals("Wrong content value", object.getSyntax().getContent(), content); - } + assertNotNull("Syntax should not be null", object.getSyntax()); + assertEquals("Wrong typeParameters value", object.getSyntax().getTypeParameters(), typeParams); + } - @Test - public void setInheritance() { - MetadataFileItem object = new MetadataFileItem("123"); + @Test + public void setTypeParametersWhenSyntaxAlreadyPresent() { + MetadataFileItem object = new MetadataFileItem("123"); + Syntax existingSyntax = new Syntax(); + object.setSyntax(existingSyntax); + List typeParams = new ArrayList<>(); - object.setInheritance(Arrays.asList("Some value")); - - assertEquals("Wrong inheritance size", object.getInheritance().size(), 1); - assertTrue("Wrong inheritance content", object.getInheritance().contains("Some value")); - } - - @Test - public void setInheritanceForNull() { - MetadataFileItem object = new MetadataFileItem("123"); - - object.setInheritance(null); - - assertNull("Wrong inheritance", object.getInheritance()); - } + object.setTypeParameters(typeParams); - @Test - public void getIsExternal() { - assertNull("Wrong isExternal when null", (new MetadataFileItem("123")).getIsExternal()); - assertTrue("Wrong isExternal when true", (new MetadataFileItem("123", "name", true)).getIsExternal()); - assertNull("Wrong isExternal when false", (new MetadataFileItem("123", "name", false)).getIsExternal()); - } - - @Test - public void setJavaType() { - MetadataFileItem metadataFileItem = new MetadataFileItem("123"); - assertNull("Wrong javaType when null", metadataFileItem.getJavaType()); - metadataFileItem.setJavaType("javaType"); - assertEquals("Wrong javaType when set","javaType", metadataFileItem.getJavaType()); - } + assertEquals("Syntax object should remain the same", object.getSyntax(), existingSyntax); + assertEquals("Wrong typeParameters value", object.getSyntax().getTypeParameters(), typeParams); + } + + @Test + public void setParameters() { + MetadataFileItem object = new MetadataFileItem("123"); + List params = new ArrayList<>(); + + object.setParameters(params); + + assertNotNull("Syntax should not be null", object.getSyntax()); + assertEquals("Wrong parameters value", object.getSyntax().getParameters(), params); + } + + @Test + public void setParametersWhenSyntaxAlreadyPresent() { + MetadataFileItem object = new MetadataFileItem("123"); + Syntax existingSyntax = new Syntax(); + object.setSyntax(existingSyntax); + List params = new ArrayList<>(); + + object.setParameters(params); + + assertEquals("Syntax object should remain the same", object.getSyntax(), existingSyntax); + assertEquals("Wrong parameters value", object.getSyntax().getParameters(), params); + } + + @Test + public void setReturn() { + MetadataFileItem object = new MetadataFileItem("123"); + Return returnValue = new Return("type"); + + object.setReturn(returnValue); + + assertNotNull("Syntax should not be null", object.getSyntax()); + assertEquals("Wrong return value", object.getSyntax().getReturnValue(), returnValue); + } + + @Test + public void setReturnWhenSyntaxAlreadyPresent() { + MetadataFileItem object = new MetadataFileItem("123"); + Syntax existingSyntax = new Syntax(); + object.setSyntax(existingSyntax); + Return returnValue = new Return("type"); + + object.setReturn(returnValue); + + assertEquals("Syntax object should remain the same", object.getSyntax(), existingSyntax); + assertEquals("Wrong return value", object.getSyntax().getReturnValue(), returnValue); + } + + @Test + public void setContent() { + MetadataFileItem object = new MetadataFileItem("123"); + String content = "Some content"; + + object.setContent(content); + + assertNotNull("Syntax should not be null", object.getSyntax()); + assertEquals("Wrong content value", object.getSyntax().getContent(), content); + } + + @Test + public void setContentWhenSyntaxAlreadyPresent() { + MetadataFileItem object = new MetadataFileItem("123"); + Syntax existingSyntax = new Syntax(); + object.setSyntax(existingSyntax); + String content = "Some content"; + + object.setContent(content); + + assertEquals("Syntax object should remain the same", object.getSyntax(), existingSyntax); + assertEquals("Wrong content value", object.getSyntax().getContent(), content); + } + + @Test + public void setInheritance() { + MetadataFileItem object = new MetadataFileItem("123"); + + object.setInheritance(Arrays.asList("Some value")); + + assertEquals("Wrong inheritance size", object.getInheritance().size(), 1); + assertTrue("Wrong inheritance content", object.getInheritance().contains("Some value")); + } + + @Test + public void setInheritanceForNull() { + MetadataFileItem object = new MetadataFileItem("123"); + + object.setInheritance(null); + + assertNull("Wrong inheritance", object.getInheritance()); + } + + @Test + public void getIsExternal() { + assertNull("Wrong isExternal when null", (new MetadataFileItem("123")).getIsExternal()); + assertTrue( + "Wrong isExternal when true", (new MetadataFileItem("123", "name", true)).getIsExternal()); + assertNull( + "Wrong isExternal when false", + (new MetadataFileItem("123", "name", false)).getIsExternal()); + } + + @Test + public void setJavaType() { + MetadataFileItem metadataFileItem = new MetadataFileItem("123"); + assertNull("Wrong javaType when null", metadataFileItem.getJavaType()); + metadataFileItem.setJavaType("javaType"); + assertEquals("Wrong javaType when set", "javaType", metadataFileItem.getJavaType()); + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/model/StatusTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/model/StatusTest.java index cff62ebb..62a40698 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/model/StatusTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/model/StatusTest.java @@ -16,15 +16,15 @@ package com.microsoft.model; -import org.junit.Test; - import static org.junit.Assert.assertEquals; +import org.junit.Test; + public class StatusTest { - @Test - public void statusName() { - String name = Status.DEPRECATED.toString(); - assertEquals("Status should be deprecated", name, "deprecated"); - } -} \ No newline at end of file + @Test + public void statusName() { + String name = Status.DEPRECATED.toString(); + assertEquals("Status should be deprecated", name, "deprecated"); + } +} diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/model/TocContentsTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/model/TocContentsTest.java index 530910d8..31833830 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/model/TocContentsTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/model/TocContentsTest.java @@ -16,88 +16,91 @@ package com.microsoft.model; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; import java.util.ArrayList; import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import org.junit.Before; +import org.junit.Test; public class TocContentsTest { - private TocItem tocItemA; - private TocItem tocItemB; - private TocItem tocItemC; - private List tocItems; - private String projectName = "google-cloud-project"; - private boolean disableChangelog = false; - - @Before - public void setup() { - tocItemA = new TocItem("A.uid.package.class", "nameA"); - tocItemB = new TocItem("B.uid.package.class", "nameB"); - tocItemC = new TocItem("C.uid.package.class", "nameC"); - - tocItems = new ArrayList<>(); - tocItems.add(tocItemA); - tocItems.add(tocItemB); - tocItems.add(tocItemC); - } - - @Test - public void getContentsWithProjectName() { - // should include ProjectContents and Guides - List tocContents = new TocContents(projectName, disableChangelog, tocItems).getContents(); - - assertEquals("Should only include 1 item", tocContents.size(), 1); - assertEquals("Should include ProjectContents", tocContents.get(0).getClass(), ProjectContents.class); - - ProjectContents contents = (ProjectContents) tocContents.get(0); - assertEquals(contents.getName(), "google-cloud-project"); - - List items = contents.getItems(); - assertEquals("Should be 5 items", items.size(), 5); - - assertEquals("Guide should be first", items.get(0).getClass(), Guide.class); - Guide overview = (Guide) items.get(0); - assertEquals("First guide should be Overview", overview.getName(), "Overview"); - - assertEquals("Guide should be second", items.get(1).getClass(), Guide.class); - Guide history = (Guide) items.get(1); - assertEquals("Second guide should be Version History", history.getName(), "Version history"); - - assertEquals("Item A should be third", items.get(2), tocItemA); - assertEquals("Item B should be fourth", items.get(3), tocItemB); - assertEquals("Item C should be fifth", items.get(4), tocItemC); - } - - @Test - public void getContentsNoProjectName() { - List tocContents = new TocContents("", disableChangelog, tocItems).getContents(); - - // should not include ProjectContents or Guides - assertEquals("Should be 3 items", tocContents.size(), 3); - assertEquals("Item A should be first", tocContents.get(0), tocItemA); - assertEquals("Item B should be second", tocContents.get(1), tocItemB); - assertEquals("Item C should be third", tocContents.get(2), tocItemC); - } - - @Test - public void getContentsWithDisabledChangelog() { - disableChangelog = true; - List tocContents = new TocContents(projectName, disableChangelog, tocItems).getContents(); - - ProjectContents contents = (ProjectContents) tocContents.get(0); - List items = contents.getItems(); - assertEquals("Should be 4 items", items.size(), 4); - - Guide overview = (Guide) items.get(0); - assertEquals("First guide should be Overview", overview.getName(), "Overview"); - assertNotEquals("Second item should not be Version History guide", items.get(1).getClass(), Guide.class); - assertEquals("Item A should be second", items.get(1), tocItemA); - assertEquals("Item B should be third", items.get(2), tocItemB); - assertEquals("Item C should be fourth", items.get(3), tocItemC); - } -} \ No newline at end of file + private TocItem tocItemA; + private TocItem tocItemB; + private TocItem tocItemC; + private List tocItems; + private String projectName = "google-cloud-project"; + private boolean disableChangelog = false; + + @Before + public void setup() { + tocItemA = new TocItem("A.uid.package.class", "nameA"); + tocItemB = new TocItem("B.uid.package.class", "nameB"); + tocItemC = new TocItem("C.uid.package.class", "nameC"); + + tocItems = new ArrayList<>(); + tocItems.add(tocItemA); + tocItems.add(tocItemB); + tocItems.add(tocItemC); + } + + @Test + public void getContentsWithProjectName() { + // should include ProjectContents and Guides + List tocContents = + new TocContents(projectName, disableChangelog, tocItems).getContents(); + + assertEquals("Should only include 1 item", tocContents.size(), 1); + assertEquals( + "Should include ProjectContents", tocContents.get(0).getClass(), ProjectContents.class); + + ProjectContents contents = (ProjectContents) tocContents.get(0); + assertEquals(contents.getName(), "google-cloud-project"); + + List items = contents.getItems(); + assertEquals("Should be 5 items", items.size(), 5); + + assertEquals("Guide should be first", items.get(0).getClass(), Guide.class); + Guide overview = (Guide) items.get(0); + assertEquals("First guide should be Overview", overview.getName(), "Overview"); + + assertEquals("Guide should be second", items.get(1).getClass(), Guide.class); + Guide history = (Guide) items.get(1); + assertEquals("Second guide should be Version History", history.getName(), "Version history"); + + assertEquals("Item A should be third", items.get(2), tocItemA); + assertEquals("Item B should be fourth", items.get(3), tocItemB); + assertEquals("Item C should be fifth", items.get(4), tocItemC); + } + + @Test + public void getContentsNoProjectName() { + List tocContents = new TocContents("", disableChangelog, tocItems).getContents(); + + // should not include ProjectContents or Guides + assertEquals("Should be 3 items", tocContents.size(), 3); + assertEquals("Item A should be first", tocContents.get(0), tocItemA); + assertEquals("Item B should be second", tocContents.get(1), tocItemB); + assertEquals("Item C should be third", tocContents.get(2), tocItemC); + } + + @Test + public void getContentsWithDisabledChangelog() { + disableChangelog = true; + List tocContents = + new TocContents(projectName, disableChangelog, tocItems).getContents(); + + ProjectContents contents = (ProjectContents) tocContents.get(0); + List items = contents.getItems(); + assertEquals("Should be 4 items", items.size(), 4); + + Guide overview = (Guide) items.get(0); + assertEquals("First guide should be Overview", overview.getName(), "Overview"); + assertNotEquals( + "Second item should not be Version History guide", items.get(1).getClass(), Guide.class); + assertEquals("Item A should be second", items.get(1), tocItemA); + assertEquals("Item B should be third", items.get(2), tocItemB); + assertEquals("Item C should be fourth", items.get(3), tocItemC); + } +} diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/model/TocFileTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/model/TocFileTest.java index c1c174ff..990b4e11 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/model/TocFileTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/model/TocFileTest.java @@ -16,31 +16,31 @@ package com.microsoft.model; -import org.junit.Test; - import static org.junit.Assert.assertEquals; +import org.junit.Test; + public class TocFileTest { - @Test - public void sortsByUid() { - TocFile tocFile = new TocFile("outputPath", "google-cloud-project", false); - TocItem tocItemA = new TocItem("A.uid.package.class", "name"); - TocItem tocItemB = new TocItem("B.uid.package.class", "name"); - TocItem tocItemC = new TocItem("C.uid.package.class", "name"); + @Test + public void sortsByUid() { + TocFile tocFile = new TocFile("outputPath", "google-cloud-project", false); + TocItem tocItemA = new TocItem("A.uid.package.class", "name"); + TocItem tocItemB = new TocItem("B.uid.package.class", "name"); + TocItem tocItemC = new TocItem("C.uid.package.class", "name"); - tocFile.addTocItem(tocItemC); - tocFile.addTocItem(tocItemA); - tocFile.addTocItem(tocItemB); + tocFile.addTocItem(tocItemC); + tocFile.addTocItem(tocItemA); + tocFile.addTocItem(tocItemB); - assertEquals("Should be out of uid order", tocFile.get(0), tocItemC); - assertEquals("Should be out of uid order", tocFile.get(1), tocItemA); - assertEquals("Should be out of uid order", tocFile.get(2), tocItemB); + assertEquals("Should be out of uid order", tocFile.get(0), tocItemC); + assertEquals("Should be out of uid order", tocFile.get(1), tocItemA); + assertEquals("Should be out of uid order", tocFile.get(2), tocItemB); - tocFile.sortByUid(); + tocFile.sortByUid(); - assertEquals("Should sort toc by uid", tocFile.get(0), tocItemA); - assertEquals("Should sort toc by uid", tocFile.get(1), tocItemB); - assertEquals("Should sort toc by uid", tocFile.get(2), tocItemC); - } -} \ No newline at end of file + assertEquals("Should sort toc by uid", tocFile.get(0), tocItemA); + assertEquals("Should sort toc by uid", tocFile.get(1), tocItemB); + assertEquals("Should sort toc by uid", tocFile.get(2), tocItemC); + } +} diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/model/TocTypeMapTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/model/TocTypeMapTest.java index 77593e8c..ae06c264 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/model/TocTypeMapTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/model/TocTypeMapTest.java @@ -15,26 +15,29 @@ */ package com.microsoft.model; +import static org.junit.Assert.*; + +import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; -import java.util.List; - -import static org.junit.Assert.*; - @RunWith(MockitoJUnitRunner.class) public class TocTypeMapTest { - @Test - public void elementKindsExistInMap() { - TocTypeMap tocTypeMap = new TocTypeMap(); - List titleList = tocTypeMap.getTitleList(); + @Test + public void elementKindsExistInMap() { + TocTypeMap tocTypeMap = new TocTypeMap(); + List titleList = tocTypeMap.getTitleList(); - assertEquals("Should include 5 items in list", 5, titleList.size()); + assertEquals("Should include 5 items in list", 5, titleList.size()); - titleList.stream().forEach(kindtitle -> assertNotNull("Element kind should exist in map", - tocTypeMap.get(kindtitle.getElementKind()))); + titleList.stream() + .forEach( + kindtitle -> + assertNotNull( + "Element kind should exist in map", + tocTypeMap.get(kindtitle.getElementKind()))); - assertNull("Should not include provided key", tocTypeMap.get("FAKE_VALUE")); - } + assertNull("Should not include provided key", tocTypeMap.get("FAKE_VALUE")); + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/BasePartnerComponent.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/BasePartnerComponent.java index 93d352f9..9dd4580d 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/BasePartnerComponent.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/BasePartnerComponent.java @@ -7,48 +7,40 @@ package com.microsoft.samples; /** - * Holds common partner component properties and behavior. All components should inherit from this class. The context - * object type. + * Holds common partner component properties and behavior. All components should inherit from this + * class. The context object type. */ public abstract class BasePartnerComponent { - /** - * Initializes a new instance of the BasePartnerComponent class. - * - * @param rootPartnerOperations The root partner operations that created this component. - * @param componentContext A component context object to work with. - */ - protected BasePartnerComponent(IPartner rootPartnerOperations, TContext componentContext) { - if (rootPartnerOperations == null) { - throw new NullPointerException("rootPartnerOperations null"); - } - - this.setPartner(rootPartnerOperations); - this.setContext(componentContext); + /** + * Initializes a new instance of the BasePartnerComponent class. + * + * @param rootPartnerOperations The root partner operations that created this component. + * @param componentContext A component context object to work with. + */ + protected BasePartnerComponent(IPartner rootPartnerOperations, TContext componentContext) { + if (rootPartnerOperations == null) { + throw new NullPointerException("rootPartnerOperations null"); } - /** - * Gets a reference to the partner operations instance that generated this component. - */ - private IPartner partner; + this.setPartner(rootPartnerOperations); + this.setContext(componentContext); + } + /** Gets a reference to the partner operations instance that generated this component. */ + private IPartner partner; - private void setPartner(IPartner value) { - partner = value; - } + private void setPartner(IPartner value) { + partner = value; + } - /** - * Gets the component context object. - */ - private TContext context; + /** Gets the component context object. */ + private TContext context; + private void setContext(TContext value) { + context = value; + } - private void setContext(TContext value) { - context = value; - } + protected void testBase() {} - protected void testBase() { - } - - protected void testInherited() { - } -} \ No newline at end of file + protected void testInherited() {} +} diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/BasePartnerComponentString.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/BasePartnerComponentString.java index 6324e1e1..546d0d82 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/BasePartnerComponentString.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/BasePartnerComponentString.java @@ -9,28 +9,26 @@ /** * Holds common partner component properties and behavior. The context is string type by default. */ -public abstract class BasePartnerComponentString - extends BasePartnerComponent { - /** - * Initializes a new instance of the BasePartnerComponent class. - * - * @param rootPartnerOperations The root partner operations that created this component. - */ - protected BasePartnerComponentString(IPartner rootPartnerOperations) { - super(rootPartnerOperations, null); - } +public abstract class BasePartnerComponentString extends BasePartnerComponent { + /** + * Initializes a new instance of the BasePartnerComponent class. + * + * @param rootPartnerOperations The root partner operations that created this component. + */ + protected BasePartnerComponentString(IPartner rootPartnerOperations) { + super(rootPartnerOperations, null); + } - /** - * Initializes a new instance of the BasePartnerComponent class. - * - * @param rootPartnerOperations The root partner operations that created this component. - * @param componentContext A component context object to work with. - */ - protected BasePartnerComponentString(IPartner rootPartnerOperations, String componentContext) { - super(rootPartnerOperations, componentContext); - } + /** + * Initializes a new instance of the BasePartnerComponent class. + * + * @param rootPartnerOperations The root partner operations that created this component. + * @param componentContext A component context object to work with. + */ + protected BasePartnerComponentString(IPartner rootPartnerOperations, String componentContext) { + super(rootPartnerOperations, componentContext); + } - @Override - protected void testInherited() { - } -} \ No newline at end of file + @Override + protected void testInherited() {} +} diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/ExceptionHandler.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/ExceptionHandler.java index 693090ab..982f797e 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/ExceptionHandler.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/ExceptionHandler.java @@ -16,6 +16,8 @@ package com.microsoft.samples; +import static com.google.common.base.Preconditions.checkNotNull; + import com.google.api.core.BetaApi; import com.google.api.gax.retrying.ResultRetryAlgorithm; import com.google.api.gax.retrying.TimedAttemptSettings; @@ -24,15 +26,12 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; - import java.io.Serializable; import java.lang.reflect.Method; import java.util.Objects; import java.util.Set; import java.util.concurrent.Callable; -import static com.google.common.base.Preconditions.checkNotNull; - /** Exception retry algorithm implementation used by {@link RetryHelper}. */ @BetaApi public final class ExceptionHandler implements ResultRetryAlgorithm, Serializable { diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/IPartner.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/IPartner.java index 73aa4db0..cf13e154 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/IPartner.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/IPartner.java @@ -6,24 +6,22 @@ package com.microsoft.samples; - /** - * The main entry point into using the partner SDK functionality. Represents a partner and encapsulates all the behavior - * attached to partners. Use this interface to get to the partner's customers, profiles, and customer orders, profiles - * and subscriptions and more. + * The main entry point into using the partner SDK functionality. Represents a partner and + * encapsulates all the behavior attached to partners. Use this interface to get to the partner's + * customers, profiles, and customer orders, profiles and subscriptions and more. */ public interface IPartner { - /** - * Gets the partner credentials. - * - * @return The partner credentials. - */ - String getCredentials(); - - /** - * Gets the request context. - * - * @return The request context. - */ + /** + * Gets the partner credentials. + * + * @return The partner credentials. + */ + String getCredentials(); -} \ No newline at end of file + /** + * Gets the request context. + * + * @return The request context. + */ +} diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/KeyValuePair.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/KeyValuePair.java index bb052bf2..672df61d 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/KeyValuePair.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/KeyValuePair.java @@ -2,22 +2,21 @@ public class KeyValuePair { - private K key; - private V value; + private K key; + private V value; - public KeyValuePair() { - } + public KeyValuePair() {} - public KeyValuePair(K key, V value) { - this.key = key; - this.value = value; - } + public KeyValuePair(K key, V value) { + this.key = key; + this.value = value; + } - public K getKey() { - return key; - } + public K getKey() { + return key; + } - public V getValue() { - return value; - } + public V getValue() { + return value; + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/Link.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/Link.java index d96c8ef9..be15ef95 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/Link.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/Link.java @@ -4,41 +4,37 @@ public class Link { - public Link() { - } - - /** - * Initializes a new instance of the Link class. - * - * @param uri The URI. - */ - - /** - * Gets the URI. - *

- * /** - * Gets the method. - */ - private String method; - - public String getMethod() { - return method; - } - - public void setMethod(String value) { - method = value; - } - - /** - * Gets the link headers. - */ - private Collection> headers; - - public Collection> getHeaders() { - return headers; - } - - public void setHeaders(Collection> value) { - headers = value; - } + public Link() {} + + /** + * Initializes a new instance of the Link class. + * + * @param uri The URI. + */ + + /** + * Gets the URI. + * + *

/** Gets the method. + */ + private String method; + + public String getMethod() { + return method; + } + + public void setMethod(String value) { + method = value; + } + + /** Gets the link headers. */ + private Collection> headers; + + public Collection> getHeaders() { + return headers; + } + + public void setHeaders(Collection> value) { + headers = value; + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/Subpackage.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/Subpackage.java index 8e2b679b..b16d190c 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/Subpackage.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/Subpackage.java @@ -1,5 +1,3 @@ package com.microsoft.samples; -public class Subpackage { - -} +public class Subpackage {} diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/SuperHero.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/SuperHero.java index 54276e67..04055a3a 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/SuperHero.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/SuperHero.java @@ -1,9 +1,8 @@ package com.microsoft.samples; import com.microsoft.samples.subpackage.Person; -import org.apache.commons.lang3.StringUtils; - import java.io.Serializable; +import org.apache.commons.lang3.StringUtils; /** * Hero is the main entity we will be using to something @@ -12,99 +11,98 @@ */ public class SuperHero extends Person implements Serializable, Cloneable { - /** - * The public name of a hero that is common knowledge - */ - private String heroName; - private String uniquePower; - private int health; - private int defense; - String hobby; - - public final String SOME_PUBLIC_STRING = "So important string value"; - - public SuperHero() { - } - - public SuperHero(String heroName, String uniquePower, int health, int defense) { - this.heroName = heroName; - this.uniquePower = uniquePower; - this.health = health; - this.defense = defense; - } - - /** - *

This is a simple description of the method. . . - * Superman! - *

- * - * @param incomingDamage the amount of incoming damage for {@link SuperHero} - * @param damageType type of damage with similar word damageTypeLong, sure - * @return the amount of health hero has after attack - * @throws IllegalArgumentException when incomingDamage is negative and thanks for {@link Exception} - * @version 1.2 - * @see HERO-402 - * @since 1.0 - * @deprecated As of version 1.1, use . . . instead - */ - @Deprecated - public int successfullyAttacked(int incomingDamage, String damageType) throws IllegalArgumentException { - // do things - if (incomingDamage < 0) { - throw new IllegalArgumentException("Cannot cause negative damage"); - } - return 0; - } - - public String getHeroName() { - return heroName; - } - - public void setHeroName(String heroName) { - this.heroName = heroName; - } - - /** - * Get capitalized last name. But it's not the end, - * because of multiline comment - * - * @return lastName in uppercase. But it's not the end, - * because of multiline comment - */ - @Override - public String getLastName() { - return StringUtils.upperCase(super.getLastName()); - } - - public String getUniquePower() { - return uniquePower; - } - - public void setUniquePower(String uniquePower) { - this.uniquePower = uniquePower; - } - - protected int getHealth() { - return health; - } - - protected void setHealth(int health) { - this.health = health; - } - - public int getDefense() { - return defense; - } - - public void setDefense(int defense) { - this.defense = defense; - } - - private void setHobby(String hobby) { - this.hobby = hobby; - } - - String getHobby() { - return hobby; + /** The public name of a hero that is common knowledge */ + private String heroName; + + private String uniquePower; + private int health; + private int defense; + String hobby; + + public final String SOME_PUBLIC_STRING = "So important string value"; + + public SuperHero() {} + + public SuperHero(String heroName, String uniquePower, int health, int defense) { + this.heroName = heroName; + this.uniquePower = uniquePower; + this.health = health; + this.defense = defense; + } + + /** + * This is a simple description of the method. . . Superman! + * + * @param incomingDamage the amount of incoming damage for {@link SuperHero} + * @param damageType type of damage with similar word damageTypeLong, sure + * @return the amount of health hero has after attack + * @throws IllegalArgumentException when incomingDamage is negative and thanks for {@link + * Exception} + * @version 1.2 + * @see HERO-402 + * @since 1.0 + * @deprecated As of version 1.1, use . . . instead + */ + @Deprecated + public int successfullyAttacked(int incomingDamage, String damageType) + throws IllegalArgumentException { + // do things + if (incomingDamage < 0) { + throw new IllegalArgumentException("Cannot cause negative damage"); } + return 0; + } + + public String getHeroName() { + return heroName; + } + + public void setHeroName(String heroName) { + this.heroName = heroName; + } + + /** + * Get capitalized last name. But it's not the end, because we add a lot of text to make this a + * multiline comment + * + * @return lastName in uppercase. But it's not the end, because we add a lot of text to make this + * a multiline comment + */ + @Override + public String getLastName() { + return StringUtils.upperCase(super.getLastName()); + } + + public String getUniquePower() { + return uniquePower; + } + + public void setUniquePower(String uniquePower) { + this.uniquePower = uniquePower; + } + + protected int getHealth() { + return health; + } + + protected void setHealth(int health) { + this.health = health; + } + + public int getDefense() { + return defense; + } + + public void setDefense(int defense) { + this.defense = defense; + } + + private void setHobby(String hobby) { + this.hobby = hobby; + } + + String getHobby() { + return hobby; + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/agreements/AgreementDetailsCollectionOperations.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/agreements/AgreementDetailsCollectionOperations.java index 55a9b2b1..740a1bdc 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/agreements/AgreementDetailsCollectionOperations.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/agreements/AgreementDetailsCollectionOperations.java @@ -3,30 +3,29 @@ import com.microsoft.samples.BasePartnerComponentString; import com.microsoft.samples.IPartner; - /** * Agreement details collection operations implementation class. + * * @deprecated Use {@link AgreementMetaData} instead. */ -public class AgreementDetailsCollectionOperations - extends BasePartnerComponentString - implements IAgreementDetailsCollection { - /** - * Initializes a new instance of the AgreementDetailsCollectionOperations class. - * - * @param rootPartnerOperations The root partner operations instance. - */ - public AgreementDetailsCollectionOperations(IPartner rootPartnerOperations) { - super(rootPartnerOperations); - } +public class AgreementDetailsCollectionOperations extends BasePartnerComponentString + implements IAgreementDetailsCollection { + /** + * Initializes a new instance of the AgreementDetailsCollectionOperations class. + * + * @param rootPartnerOperations The root partner operations instance. + */ + public AgreementDetailsCollectionOperations(IPartner rootPartnerOperations) { + super(rootPartnerOperations); + } - /** - * Retrieves the agreement details. - * - * @return A list of agreement details. - * @deprecated Some text - */ - public ResourceCollection get() { - return null; - } -} \ No newline at end of file + /** + * Retrieves the agreement details. + * + * @return A list of agreement details. + * @deprecated Some text + */ + public ResourceCollection get() { + return null; + } +} diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/agreements/AgreementMetaData.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/agreements/AgreementMetaData.java index 277c5b7d..cc06cab6 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/agreements/AgreementMetaData.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/agreements/AgreementMetaData.java @@ -3,55 +3,49 @@ import com.fasterxml.jackson.annotation.JsonProperty; /** - * The AgreementMetaData provides metadata about the agreement type - * that partner can provide confirmation of customer acceptance. + * The AgreementMetaData provides metadata about the agreement type that partner can provide + * confirmation of customer acceptance. */ public class AgreementMetaData { - /** - * Gets or sets the unique identifier of an agreement template. - */ - @JsonProperty("templateId") - private String templateId; - - public String getTemplateId() { - return templateId; - } - - public void setTemplateId(String value) { - templateId = value; - } - - /** - * Gets or sets agreement type. - */ - - - /** - * Gets or sets URL to the agreement template. - * @deprecated - */ - @JsonProperty("agreementLink") - private String agreementLink; - - public String getAgreementLink() { - return agreementLink; - } - - public void setAgreementLink(String value) { - agreementLink = value; - } - - /** - * Gets or sets the version rank of an agreement template. - */ - @JsonProperty("versionRank") - private int versionRank; - - public int getVersionRank() { - return versionRank; - } - - public void setVersionRank(int value) { - versionRank = value; - } -} \ No newline at end of file + /** Gets or sets the unique identifier of an agreement template. */ + @JsonProperty("templateId") + private String templateId; + + public String getTemplateId() { + return templateId; + } + + public void setTemplateId(String value) { + templateId = value; + } + + /** Gets or sets agreement type. */ + + /** + * Gets or sets URL to the agreement template. + * + * @deprecated + */ + @JsonProperty("agreementLink") + private String agreementLink; + + public String getAgreementLink() { + return agreementLink; + } + + public void setAgreementLink(String value) { + agreementLink = value; + } + + /** Gets or sets the version rank of an agreement template. */ + @JsonProperty("versionRank") + private int versionRank; + + public int getVersionRank() { + return versionRank; + } + + public void setVersionRank(int value) { + versionRank = value; + } +} diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/agreements/IAgreementDetailsCollection.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/agreements/IAgreementDetailsCollection.java index 5d8a5944..8b80e81d 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/agreements/IAgreementDetailsCollection.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/agreements/IAgreementDetailsCollection.java @@ -1,15 +1,15 @@ package com.microsoft.samples.agreements; - /** * Encapsulates the operations on the agreement metadata collection. + * * @deprecated This one is deprecated :( */ public interface IAgreementDetailsCollection { - /** - * Retrieves all current agreement metadata. - * - * @return The current agreement metadata. - */ - ResourceCollection get(); -} \ No newline at end of file + /** + * Retrieves all current agreement metadata. + * + * @return The current agreement metadata. + */ + ResourceCollection get(); +} diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/agreements/ResourceCollection.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/agreements/ResourceCollection.java index 9b829aed..7b8d8ca2 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/agreements/ResourceCollection.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/agreements/ResourceCollection.java @@ -1,8 +1,7 @@ package com.microsoft.samples.agreements; /** - * Contains a collection of resources with JSON properties to represent the output Type of objects in collection + * Contains a collection of resources with JSON properties to represent the output Type of objects + * in collection */ -public class ResourceCollection { - -} \ No newline at end of file +public class ResourceCollection {} diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Animal.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Animal.java index 6ac38bc8..2d1d7a94 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Animal.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Animal.java @@ -1,28 +1,16 @@ package com.microsoft.samples.commentinheritance; -/** - * Animal. - */ +/** Animal. */ public abstract class Animal implements Organism { - /** - * Breathe. - */ - public void breathe() { - } + /** Breathe. */ + public void breathe() {} - /** - * Communicate verbally. - */ - public abstract void verballyCommunicate(); + /** Communicate verbally. */ + public abstract void verballyCommunicate(); - /** - * Feed offspring. - */ - public abstract void feed(); + /** Feed offspring. */ + public abstract void feed(); - /** - * {@inheritDoc} - * Get kind from Animal. - */ - public abstract String getKind(); + /** {@inheritDoc} Get kind from Animal. */ + public abstract String getKind(); } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Carnivorous.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Carnivorous.java index 96811e00..3bc8be6d 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Carnivorous.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Carnivorous.java @@ -1,18 +1,14 @@ package com.microsoft.samples.commentinheritance; -/** - * Marks an Animal that eats other animals. - */ +/** Marks an Animal that eats other animals. */ public interface Carnivorous { - /** - * Eat the provided animal. - * - * @param animalBeingEaten Animal that will be eaten. - */ - void eat(Animal animalBeingEaten); + /** + * Eat the provided animal. + * + * @param animalBeingEaten Animal that will be eaten. + */ + void eat(Animal animalBeingEaten); - /** - * Get kind from Carnivorous. - */ - String getKind(); + /** Get kind from Carnivorous. */ + String getKind(); } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Dog.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Dog.java index 09e7d2d5..a950f1cd 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Dog.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Dog.java @@ -1,71 +1,58 @@ package com.microsoft.samples.commentinheritance; -import java.awt.*; - import static java.lang.System.out; -/** - * Canine and man's best friend. - */ -public class Dog extends Mammal implements Omnivorous, Viviparous { - private final Color hairColor = null; - - /** - * {@inheritDoc} - * - * @param otherAnimal Tasty treat. - */ - @Override - public void eat(final Animal otherAnimal) { - } - - /** - * {@inheritDoc} - * - * @param plantToBeEaten Plant that this dog will eat. - */ - @Override - public void eat(final Plant plantToBeEaten) { - } - - /** - * {@inheritDoc} Bark. - */ - public void verballyCommunicate() { - out.println("Woof!"); - } - - /** - * {@inheritDoc} - * - * @param numberPuppies Number of puppies being born. - */ - @Override - public void giveBirth(final int numberPuppies) { - } - - /** - * Provide the color of the dog's hair. - * - * @return Color of the dog's fur. - */ - public Color getHairColor() { - return hairColor; - } - - /** - * {@inheritDoc} - */ - @Override - public void feed() { - } +import java.awt.*; - /** - * {@inheritDoc} - * Get kind from Dog. - */ - @Override - public String getKind() { - return "Dog"; - } +/** Canine and man's best friend. */ +public class Dog extends Mammal implements Omnivorous, Viviparous { + private final Color hairColor = null; + + /** + * {@inheritDoc} + * + * @param otherAnimal Tasty treat. + */ + @Override + public void eat(final Animal otherAnimal) {} + + /** + * {@inheritDoc} + * + * @param plantToBeEaten Plant that this dog will eat. + */ + @Override + public void eat(final Plant plantToBeEaten) {} + + /** {@inheritDoc} Bark. */ + public void verballyCommunicate() { + out.println("Woof!"); + } + + /** + * {@inheritDoc} + * + * @param numberPuppies Number of puppies being born. + */ + @Override + public void giveBirth(final int numberPuppies) {} + + /** + * Provide the color of the dog's hair. + * + * @return Color of the dog's fur. + */ + public Color getHairColor() { + return hairColor; + } + + /** {@inheritDoc} */ + @Override + public void feed() {} + + /** {@inheritDoc} Get kind from Dog. */ + @Override + public String getKind() { + return "Dog"; + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Herbivorous.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Herbivorous.java index 32abea1f..5102185d 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Herbivorous.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Herbivorous.java @@ -1,22 +1,16 @@ package com.microsoft.samples.commentinheritance; -/** - * Marks animals that eat plants. - */ +/** Marks animals that eat plants. */ public interface Herbivorous { - /** - * Eat the provided plant. - * - * @param plantToBeEaten Plant that will be eaten. - */ - void eat(Plant plantToBeEaten); + /** + * Eat the provided plant. + * + * @param plantToBeEaten Plant that will be eaten. + */ + void eat(Plant plantToBeEaten); - /** - * Get kind from Herbivorous. - */ - String getKind(); - - public class Plant { - } + /** Get kind from Herbivorous. */ + String getKind(); + public class Plant {} } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Mammal.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Mammal.java index a72edc13..2b5b2306 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Mammal.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Mammal.java @@ -1,13 +1,8 @@ package com.microsoft.samples.commentinheritance; -/** - * Mammal. - */ +/** Mammal. */ public abstract class Mammal extends Animal { - /** - * {@inheritDoc} - * Get kind from Mammal. - */ - public abstract String getKind(); + /** {@inheritDoc} Get kind from Mammal. */ + public abstract String getKind(); } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Omnivorous.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Omnivorous.java index b5686eb5..a7a3244c 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Omnivorous.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Omnivorous.java @@ -1,19 +1,14 @@ package com.microsoft.samples.commentinheritance; -/** - * Eats plants and animals. - */ +/** Eats plants and animals. */ public interface Omnivorous extends Carnivorous, Herbivorous { - @Override - void eat(Animal animalToBeEaten); + @Override + void eat(Animal animalToBeEaten); - @Override - void eat(Plant plantToBeEaten); + @Override + void eat(Plant plantToBeEaten); - /** - * {@inheritDoc} - * Get kind from Omnivorous. - */ - @Override - String getKind(); + /** {@inheritDoc} Get kind from Omnivorous. */ + @Override + String getKind(); } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Organism.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Organism.java index 8edf9a62..751dad3d 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Organism.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Organism.java @@ -2,8 +2,6 @@ public interface Organism { - /** - * Get kind from Organism. - */ - String getKind(); + /** Get kind from Organism. */ + String getKind(); } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Viviparous.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Viviparous.java index 685eba41..1fd59bf0 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Viviparous.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/commentinheritance/Viviparous.java @@ -1,14 +1,10 @@ package com.microsoft.samples.commentinheritance; -/** - * Mammals that give birth to young that develop within the mother's body. - */ +/** Mammals that give birth to young that develop within the mother's body. */ public interface Viviparous { - void giveBirth(int numberOfOffspring); + void giveBirth(int numberOfOffspring); - /** - * Get kind from Viviparous. - */ - String getKind(); + /** Get kind from Viviparous. */ + String getKind(); } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/BetaApi.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/BetaApi.java index ca32def1..4cb3b930 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/BetaApi.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/BetaApi.java @@ -40,15 +40,15 @@ * Indicates a public API that can change at any time, and has no guarantee of API stability and * backward-compatibility. * - *

- * Usage guidelines: + *

Usage guidelines: + * *

    - *
  1. This annotation is used only on APIs with public visibility. Internal interfaces should not - * use it.
  2. - *
  3. This annotation should only be added to new APIs. Adding it to an existing API is considered - * API-breaking.
  4. - *
  5. Removing this annotation from an API gives it stable status, assuming the API doesn't have - * other annotations denoting instability. + *
  6. This annotation is used only on APIs with public visibility. Internal interfaces should not + * use it. + *
  7. This annotation should only be added to new APIs. Adding it to an existing API is + * considered API-breaking. + *
  8. Removing this annotation from an API gives it stable status, assuming the API doesn't have + * other annotations denoting instability. *
*/ @BetaApi @@ -63,8 +63,6 @@ }) @Documented public @interface BetaApi { - /** - * Context information such as links to a discussion thread, tracking issue, etc. - */ + /** Context information such as links to a discussion thread, tracking issue, etc. */ String value() default ""; } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/ProductSearchSettings.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/ProductSearchSettings.java index fdb97d6e..50d9b44b 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/ProductSearchSettings.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/ProductSearchSettings.java @@ -16,6 +16,8 @@ package com.microsoft.samples.google; +import static com.google.cloud.vision.v1.ProductSearchClient.*; + import com.google.api.core.ApiFunction; import com.google.api.core.BetaApi; import com.google.api.gax.core.GoogleCredentialsProvider; @@ -26,12 +28,9 @@ import com.google.cloud.vision.v1.stub.ProductSearchStubSettings; import com.google.longrunning.Operation; import com.google.protobuf.Empty; - -import javax.annotation.Generated; import java.io.IOException; import java.util.List; - -import static com.google.cloud.vision.v1.ProductSearchClient.*; +import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/RecognitionAudio.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/RecognitionAudio.java index 6a8ecd80..79583de0 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/RecognitionAudio.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/RecognitionAudio.java @@ -52,9 +52,9 @@ * Protobuf type {@code google.cloud.speech.v1.RecognitionAudio} */ public final class RecognitionAudio extends com.google.protobuf.GeneratedMessageV3 - implements - // @@protoc_insertion_point(message_implements:google.cloud.speech.v1.RecognitionAudio) - RecognitionAudioOrBuilder { + implements + // @@protoc_insertion_point(message_implements:google.cloud.speech.v1.RecognitionAudio) + RecognitionAudioOrBuilder { private static final long serialVersionUID = 0L; // Use RecognitionAudio.newBuilder() to construct. @@ -67,8 +67,7 @@ protected FieldAccessorTable internalGetFieldAccessorTable() { return null; } - private RecognitionAudio() { - } + private RecognitionAudio() {} @java.lang.Override @SuppressWarnings({"unused"}) @@ -92,15 +91,15 @@ public final com.google.protobuf.UnknownFieldSet getUnknownFields() { } private RecognitionAudio( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder(); + com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { @@ -109,23 +108,26 @@ private RecognitionAudio( case 0: done = true; break; - case 10: { - audioSourceCase_ = 1; - audioSource_ = input.readBytes(); - break; - } - case 18: { - java.lang.String s = input.readStringRequireUtf8(); - audioSourceCase_ = 2; - audioSource_ = s; - break; - } - default: { - if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { - done = true; + case 10: + { + audioSourceCase_ = 1; + audioSource_ = input.readBytes(); + break; + } + case 18: + { + java.lang.String s = input.readStringRequireUtf8(); + audioSourceCase_ = 2; + audioSource_ = s; + break; + } + default: + { + if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; } - break; - } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { @@ -152,7 +154,7 @@ public Message.Builder toBuilder() { } public enum AudioSourceCase - implements + implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { CONTENT(1), @@ -190,9 +192,7 @@ public static AudioSourceCase forNumber(int value) { public int getNumber() { return this.value; } - } - - ; + }; public com.google.cloud.speech.v1.RecognitionAudio.AudioSourceCase getAudioSourceCase() { return com.google.cloud.speech.v1.RecognitionAudio.AudioSourceCase.forNumber(audioSourceCase_); @@ -201,6 +201,8 @@ public com.google.cloud.speech.v1.RecognitionAudio.AudioSourceCase getAudioSourc public static final int CONTENT_FIELD_NUMBER = 1; /** + * + * *
    * The audio data bytes encoded as specified in
    * `RecognitionConfig`. Note: as with all bytes fields, proto buffers use a
@@ -217,6 +219,8 @@ public boolean hasContent() {
   }
 
   /**
+   *
+   *
    * 
    * The audio data bytes encoded as specified in
    * `RecognitionConfig`. Note: as with all bytes fields, proto buffers use a
@@ -238,6 +242,8 @@ public com.google.protobuf.ByteString getContent() {
   public static final int URI_FIELD_NUMBER = 2;
 
   /**
+   *
+   *
    * 
    * URI that points to a file that contains audio data bytes as specified in
    * `RecognitionConfig`. The file must not be compressed (for example, gzip).
@@ -257,6 +263,8 @@ public boolean hasUri() {
   }
 
   /**
+   *
+   *
    * 
    * URI that points to a file that contains audio data bytes as specified in
    * `RecognitionConfig`. The file must not be compressed (for example, gzip).
@@ -289,6 +297,8 @@ public java.lang.String getUri() {
   }
 
   /**
+   *
+   *
    * 
    * URI that points to a file that contains audio data bytes as specified in
    * `RecognitionConfig`. The file must not be compressed (for example, gzip).
@@ -310,7 +320,7 @@ public com.google.protobuf.ByteString getUriBytes() {
     }
     if (ref instanceof java.lang.String) {
       com.google.protobuf.ByteString b =
-              com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
+          com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
       if (audioSourceCase_ == 2) {
         audioSource_ = b;
       }
@@ -351,8 +361,8 @@ public int getSerializedSize() {
     size = 0;
     if (audioSourceCase_ == 1) {
       size +=
-              com.google.protobuf.CodedOutputStream.computeBytesSize(
-                      1, (com.google.protobuf.ByteString) audioSource_);
+          com.google.protobuf.CodedOutputStream.computeBytesSize(
+              1, (com.google.protobuf.ByteString) audioSource_);
     }
     if (audioSourceCase_ == 2) {
       size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, audioSource_);
@@ -362,4 +372,3 @@ public int getSerializedSize() {
     return size;
   }
 }
-
diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/SpeechClient.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/SpeechClient.java
index 386caaee..263eede4 100644
--- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/SpeechClient.java
+++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/SpeechClient.java
@@ -22,16 +22,15 @@
 import com.google.api.gax.rpc.BidiStreamingCallable;
 import com.google.api.gax.rpc.OperationCallable;
 import com.google.api.gax.rpc.UnaryCallable;
-import com.google.cloud.speech.v1p1beta1.RecognitionAudio;
 import com.google.cloud.speech.v1p1beta1.*;
+import com.google.cloud.speech.v1p1beta1.RecognitionAudio;
 import com.google.cloud.speech.v1p1beta1.stub.SpeechStub;
 import com.google.cloud.speech.v1p1beta1.stub.SpeechStubSettings;
 import com.google.longrunning.Operation;
 import com.google.longrunning.OperationsClient;
-
-import javax.annotation.Generated;
 import java.io.IOException;
 import java.util.concurrent.TimeUnit;
+import javax.annotation.Generated;
 
 // AUTO-GENERATED DOCUMENTATION AND CLASS.
 
@@ -177,7 +176,8 @@ public final OperationsClient getOperationsClient() {
    * @param audio Required. The audio data to be recognized.
    * @throws com.google.api.gax.rpc.ApiException if the remote call fails
    */
-  public final RecognizeResponse recognize(RecognitionConfig config, com.google.cloud.speech.v1p1beta1.RecognitionAudio audio) {
+  public final RecognizeResponse recognize(
+      RecognitionConfig config, com.google.cloud.speech.v1p1beta1.RecognitionAudio audio) {
     RecognizeRequest request =
         RecognizeRequest.newBuilder().setConfig(config).setAudio(audio).build();
     return recognize(request);
diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/SpeechSettings.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/SpeechSettings.java
index fc51244e..fca83c3a 100644
--- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/SpeechSettings.java
+++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/SpeechSettings.java
@@ -22,14 +22,13 @@
 import com.google.api.gax.core.InstantiatingExecutorProvider;
 import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
 import com.google.api.gax.rpc.*;
-import com.google.cloud.speech.v1p1beta1.SpeechClient;
 import com.google.cloud.speech.v1p1beta1.*;
+import com.google.cloud.speech.v1p1beta1.SpeechClient;
 import com.google.cloud.speech.v1p1beta1.stub.SpeechStubSettings;
 import com.google.longrunning.Operation;
-
-import javax.annotation.Generated;
 import java.io.IOException;
 import java.util.List;
+import javax.annotation.Generated;
 
 // AUTO-GENERATED DOCUMENTATION AND CLASS.
 
diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/ValidationException.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/ValidationException.java
index acebe8c9..602af46a 100644
--- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/ValidationException.java
+++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/ValidationException.java
@@ -37,8 +37,9 @@
  * Exception thrown if there is a validation problem with a path template, http config, or related
  * framework methods. Comes as an illegal argument exception subclass. Allows to globally set a
  * thread-local validation context description which each exception inherits.
+ *
  * @see Google Cloud
- *      Storage error codes
+ *     Storage error codes
  */
 public class ValidationException extends IllegalArgumentException {
 
@@ -71,9 +72,7 @@ public String get() {
         });
   }
 
-  /**
-   * Clears the validation context.
-   */
+  /** Clears the validation context. */
   public static void popCurrentThreadValidationContext() {
     Stack stack = contextLocal.get();
     if (stack != null) {
@@ -81,9 +80,7 @@ public static void popCurrentThreadValidationContext() {
     }
   }
 
-  /**
-   * Construct validation exception with implicit context.
-   */
+  /** Construct validation exception with implicit context. */
   public ValidationException(String format, Object... args) {
     super(message(contextLocal.get(), format, args));
   }
diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/v1beta/SpeechClient.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/v1beta/SpeechClient.java
index e145e0c3..37fd187d 100644
--- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/v1beta/SpeechClient.java
+++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/v1beta/SpeechClient.java
@@ -27,10 +27,9 @@
 import com.google.cloud.speech.v1p1beta1.stub.SpeechStubSettings;
 import com.google.longrunning.Operation;
 import com.google.longrunning.OperationsClient;
-
-import javax.annotation.Generated;
 import java.io.IOException;
 import java.util.concurrent.TimeUnit;
+import javax.annotation.Generated;
 
 // AUTO-GENERATED DOCUMENTATION AND CLASS.
 
@@ -109,7 +108,8 @@ public static final SpeechClient create() throws IOException {
    * Constructs an instance of SpeechClient, using the given settings. The channels are created
    * based on the settings passed in, or defaults for any settings that are not set.
    */
-  public static final SpeechClient create(com.microsoft.samples.google.SpeechSettings settings) throws IOException {
+  public static final SpeechClient create(com.microsoft.samples.google.SpeechSettings settings)
+      throws IOException {
     return new SpeechClient(settings);
   }
 
diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/v1p1alpha/SpeechClient.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/v1p1alpha/SpeechClient.java
index d8f00ead..ec2c7dae 100644
--- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/v1p1alpha/SpeechClient.java
+++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/google/v1p1alpha/SpeechClient.java
@@ -27,10 +27,9 @@
 import com.google.cloud.speech.v1p1beta1.stub.SpeechStubSettings;
 import com.google.longrunning.Operation;
 import com.google.longrunning.OperationsClient;
-
-import javax.annotation.Generated;
 import java.io.IOException;
 import java.util.concurrent.TimeUnit;
+import javax.annotation.Generated;
 
 // AUTO-GENERATED DOCUMENTATION AND CLASS.
 
@@ -107,11 +106,12 @@ public static final SpeechClient create() throws IOException {
 
   /**
    * Constructs an instance of SpeechClient, using the given settings. The channels are created
-   * based on the settings passed in, or defaults for any settings that are not set.
-   * Example broken links: {@link "http://tools.ietf.org/html/rfc2616#section-3.7"}
-   * {@link ApiFutures#immediateFuture(null)}.
+   * based on the settings passed in, or defaults for any settings that are not set. Example broken
+   * links: {@link "http://tools.ietf.org/html/rfc2616#section-3.7"} {@link
+   * ApiFutures#immediateFuture(null)}.
    */
-  public static final SpeechClient create(com.microsoft.samples.google.SpeechSettings settings) throws IOException {
+  public static final SpeechClient create(com.microsoft.samples.google.SpeechSettings settings)
+      throws IOException {
     return new SpeechClient(settings);
   }
 
diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/offers/Offer.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/offers/Offer.java
index 0cb9025d..51ed3a23 100644
--- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/offers/Offer.java
+++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/offers/Offer.java
@@ -1,38 +1,35 @@
 package com.microsoft.samples.offers;
 
-/**
- * Represents a form of product availability to customer
- */
+/** Represents a form of product availability to customer */
 public class Offer {
-    /**
-     * Initializes a new instance of the Offer class.
-     */
-    public Offer() {
-    }
+  /** Initializes a new instance of the Offer class. */
+  public Offer() {}
 
-    /**
-     * Gets or sets qualifications required by the Partner in order to purchase the offer for a customer.
-     */
-    private String[] __ResellerQualifications;
+  /**
+   * Gets or sets qualifications required by the Partner in order to purchase the offer for a
+   * customer.
+   */
+  private String[] __ResellerQualifications;
 
-    public String[] getResellerQualifications() {
-        return __ResellerQualifications;
-    }
+  public String[] getResellerQualifications() {
+    return __ResellerQualifications;
+  }
 
-    public void setResellerQualifications(String[] value) {
-        __ResellerQualifications = value;
-    }
+  public void setResellerQualifications(String[] value) {
+    __ResellerQualifications = value;
+  }
 
-    /**
-     * Gets or sets qualifications required by the customer for the partner to purchase it for the customer.
-     */
-    private String[] __ReselleeQualifications;
+  /**
+   * Gets or sets qualifications required by the customer for the partner to purchase it for the
+   * customer.
+   */
+  private String[] __ReselleeQualifications;
 
-    public String[] getReselleeQualifications() {
-        return __ReselleeQualifications;
-    }
+  public String[] getReselleeQualifications() {
+    return __ReselleeQualifications;
+  }
 
-    public void setReselleeQualifications(String[] value) {
-        __ReselleeQualifications = value;
-    }
-}
\ No newline at end of file
+  public void setReselleeQualifications(String[] value) {
+    __ReselleeQualifications = value;
+  }
+}
diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/someexcludedpackage/SomeClassInExcludedPackage.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/someexcludedpackage/SomeClassInExcludedPackage.java
index 8d9d4133..8b01667b 100644
--- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/someexcludedpackage/SomeClassInExcludedPackage.java
+++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/someexcludedpackage/SomeClassInExcludedPackage.java
@@ -2,13 +2,13 @@
 
 public class SomeClassInExcludedPackage {
 
-    private String field;
+  private String field;
 
-    public String getField() {
-        return field;
-    }
+  public String getField() {
+    return field;
+  }
 
-    public void setField(String field) {
-        this.field = field;
-    }
+  public void setField(String field) {
+    this.field = field;
+  }
 }
diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/CustomException.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/CustomException.java
index 8717af6b..dc982f91 100644
--- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/CustomException.java
+++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/CustomException.java
@@ -2,20 +2,20 @@
 
 public class CustomException extends Exception {
 
-    public CustomException(String message) {
-        super(message);
-    }
+  public CustomException(String message) {
+    super(message);
+  }
 
-    /**
-     * We need to have such method that throw exception declared in the same class
-     *
-     * @throws CustomException with reason message
-     */
-    public void makeSomething() throws CustomException {
-        throw new CustomException("It happened!");
-    }
+  /**
+   * We need to have such method that throw exception declared in the same class
+   *
+   * @throws CustomException with reason message
+   */
+  public void makeSomething() throws CustomException {
+    throw new CustomException("It happened!");
+  }
 
-    private class PrivateException {
-        private String message;
-    }
+  private class PrivateException {
+    private String message;
+  }
 }
diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/Display.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/Display.java
index c1b0eed1..6fa6ae8f 100644
--- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/Display.java
+++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/Display.java
@@ -5,12 +5,12 @@
 
 /**
  * Do you see some First code block?
- * 

- * Or this {@code Second} code block? + * + *

Or this {@code Second} code block? */ public interface Display extends Serializable, List> { - void show(); + void show(); - void hide(); + void hide(); } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/InternalException.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/InternalException.java index c868a4cc..788d88ac 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/InternalException.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/InternalException.java @@ -2,7 +2,7 @@ class InternalException extends Exception { - public InternalException(String message) { - super(message); - } + public InternalException(String message) { + super(message); + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/Person.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/Person.java index fb09f8af..32a64e16 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/Person.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/Person.java @@ -7,71 +7,70 @@ /** * Class that describes some person * - * This comment has links to: + *

This comment has links to: + * *

    - *
  • Owner class {@link Person}
  • - *
  • Its inner class {@link Person.IdentificationInfo}
  • - *
  • Its method {@link Person#setLastName(String lastName)}
  • - *
  • Its method without params {@link Person#setLastName()}
  • - *
  • Its public field {@link Person#age}
  • - *
  • Another class which used here {@link Set}
  • - *
  • Another class which not used here {@link List}
  • - *
  • Broken link {@link sdfdsagdsfghfgh}
  • - *
  • Plain link {@linkplain someContent}
  • - *
  • Link that starts from '#' {@link #setLastName()}
  • - *
  • Link with label {@link Set WordOne}
  • + *
  • Owner class {@link Person} + *
  • Its inner class {@link Person.IdentificationInfo} + *
  • Its method {@link Person#setLastName(String lastName)} + *
  • Its method without params {@link Person#setLastName()} + *
  • Its public field {@link Person#age} + *
  • Another class which used here {@link Set} + *
  • Another class which not used here {@link List} + *
  • Broken link {@link sdfdsagdsfghfgh} + *
  • Plain link {@linkplain someContent} + *
  • Link that starts from '#' {@link #setLastName()} + *
  • Link with label {@link Set WordOne} *
* * This is an "at" symbol: {@literal @} + * * @see Display */ public class Person { - private String firstName; - private String lastName; - public int age; + private String firstName; + private String lastName; + public int age; - public String getFirstName() { - return firstName; - } + public String getFirstName() { + return firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public String getLastName() { - return lastName; - } + public String getLastName() { + return lastName; + } - public void setLastName(String lastName) { - this.lastName = lastName; - } + public void setLastName(String lastName) { + this.lastName = lastName; + } - public void setLastName() { - this.lastName = null; - } + public void setLastName() { + this.lastName = null; + } - public Set getSomeSet() { - return Collections.emptySet(); - } + public Set getSomeSet() { + return Collections.emptySet(); + } - /** - * We need to have this method that takes parameter and return types declared in the current class - */ - public static Person buildPerson(Person seed) { - return seed; - } + /** + * We need to have this method that takes parameter and return types declared in the current class + */ + public static Person buildPerson(Person seed) { + return seed; + } - /** - * Class that describes person's identification - */ - public static class IdentificationInfo { + /** Class that describes person's identification */ + public static class IdentificationInfo { - /** - * Enum describes person's gender - */ - public enum Gender { - MALE, FEMALE - } + /** Enum describes person's gender */ + public enum Gender { + MALE, + FEMALE } + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/SomeExcludedClass.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/SomeExcludedClass.java index 66a87af6..6cf5d103 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/SomeExcludedClass.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/SomeExcludedClass.java @@ -2,13 +2,13 @@ public class SomeExcludedClass { - private String field; + private String field; - public String getField() { - return field; - } + public String getField() { + return field; + } - public void setField(String field) { - this.field = field; - } + public void setField(String field) { + this.field = field; + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/Tuple.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/Tuple.java index 2ab5e686..f028a231 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/Tuple.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/Tuple.java @@ -1,29 +1,28 @@ package com.microsoft.samples.subpackage; public class Tuple { - private T1 item1; + private T1 item1; - private T2 item2; + private T2 item2; - public Tuple(T1 item1, T2 item2) { - this.item1 = item1; - this.item2 = item2; - } + public Tuple(T1 item1, T2 item2) { + this.item1 = item1; + this.item2 = item2; + } - public T1 getItem1() { - return item1; - } + public T1 getItem1() { + return item1; + } - public void setItem1(T1 item1) { - this.item1 = item1; - } + public void setItem1(T1 item1) { + this.item1 = item1; + } - public T2 getItem2() { - return item2; - } + public T2 getItem2() { + return item2; + } - public void setItem2(T2 item2) { - this.item2 = item2; - } - -} \ No newline at end of file + public void setItem2(T2 item2) { + this.item2 = item2; + } +} diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/package-info.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/package-info.java index 8d5be309..e076a379 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/package-info.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/samples/subpackage/package-info.java @@ -1,4 +1,2 @@ -/** - * This subpackage contains the sample set of classes for testing DocFx doclet. - */ +/** This subpackage contains the sample set of classes for testing DocFx doclet. */ package com.microsoft.samples.subpackage; diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/util/ElementUtilTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/util/ElementUtilTest.java index 312aae07..178be191 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/util/ElementUtilTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/util/ElementUtilTest.java @@ -1,85 +1,104 @@ package com.microsoft.util; -import com.google.testing.compile.CompilationRule; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import static org.junit.Assert.*; -import javax.lang.model.element.Element; -import javax.lang.model.util.Elements; +import com.google.testing.compile.CompilationRule; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; - -import static org.junit.Assert.*; +import javax.lang.model.element.Element; +import javax.lang.model.util.Elements; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class ElementUtilTest { - @Rule - public CompilationRule rule = new CompilationRule(); - private Elements elements; - private ElementUtil elementUtil; - - @Before - public void setup() { - elements = rule.getElements(); - elementUtil = new ElementUtil( - new String[]{"samples\\.someexcludedpackage"}, - new String[]{"com\\.microsoft\\..*SomeExcludedClass"}); - } - - @Test - public void extractPackageElements() { - Set elementsSet = new HashSet<>() {{ + @Rule public CompilationRule rule = new CompilationRule(); + private Elements elements; + private ElementUtil elementUtil; + + @Before + public void setup() { + elements = rule.getElements(); + elementUtil = + new ElementUtil( + new String[] {"samples\\.someexcludedpackage"}, + new String[] {"com\\.microsoft\\..*SomeExcludedClass"}); + } + + @Test + public void extractPackageElements() { + Set elementsSet = + new HashSet<>() { + { add(elements.getPackageElement("com.microsoft.samples")); add(elements.getTypeElement("com.microsoft.samples.SuperHero")); add(elements.getPackageElement("com.microsoft.samples.subpackage")); - }}; - - List result = elementUtil.extractPackageElements(elementsSet) - .stream().map(String::valueOf).collect(Collectors.toList()); - - assertEquals("Wrong result list size", result.size(), 2); - assertEquals("Unexpected first item", result.get(0), "com.microsoft.samples"); - assertEquals("Unexpected second item", result.get(1), "com.microsoft.samples.subpackage"); - } - - @Test - public void extractSortedElements() { - Element element = elements.getPackageElement("com.microsoft.samples.subpackage"); - - List allElements = element.getEnclosedElements() - .stream().map(String::valueOf).collect(Collectors.toList()); - - // Ensure items to exclude exist. - assertEquals("Wrong enclosed elements number", allElements.size(), 6); - assertTrue("Unexpected package private class", allElements.contains("com.microsoft.samples.subpackage.InternalException")); - assertTrue("Unexpected to-exclude class", allElements.contains("com.microsoft.samples.subpackage.SomeExcludedClass")); - - - List extractedElements = elementUtil.extractSortedElements(element) - .stream().map(String::valueOf).collect(Collectors.toList()); - - // Verify filtered and sorted result - assertEquals("Wrong result list size", extractedElements.size(), 4); - assertEquals("Unexpected first item in the result list after invoke method extractSortedElements()", extractedElements.get(0), "com.microsoft.samples.subpackage.CustomException"); - assertEquals("Unexpected second item in the result list after invoke method extractSortedElements()", extractedElements.get(1), "com.microsoft.samples.subpackage.Display"); - assertEquals("Unexpected third item in the result list after invoke method extractSortedElements()", extractedElements.get(2), "com.microsoft.samples.subpackage.Person"); - } - - @Test - public void matchAnyPattern() { - HashSet patterns = new HashSet<>( - Arrays.asList(Pattern.compile("com\\.ms\\.Some.*"), Pattern.compile(".*UsualClass"))); - assertTrue(elementUtil.matchAnyPattern(patterns, "com.ms.SomeStrangeClass")); - assertTrue(elementUtil.matchAnyPattern(patterns, "UsualClass")); - assertFalse(elementUtil.matchAnyPattern(patterns, "EngineFive")); - assertFalse(elementUtil.matchAnyPattern(patterns, "com.ms.Awesome")); - } + } + }; + + List result = + elementUtil.extractPackageElements(elementsSet).stream() + .map(String::valueOf) + .collect(Collectors.toList()); + + assertEquals("Wrong result list size", result.size(), 2); + assertEquals("Unexpected first item", result.get(0), "com.microsoft.samples"); + assertEquals("Unexpected second item", result.get(1), "com.microsoft.samples.subpackage"); + } + + @Test + public void extractSortedElements() { + Element element = elements.getPackageElement("com.microsoft.samples.subpackage"); + + List allElements = + element.getEnclosedElements().stream().map(String::valueOf).collect(Collectors.toList()); + + // Ensure items to exclude exist. + assertEquals("Wrong enclosed elements number", allElements.size(), 6); + assertTrue( + "Unexpected package private class", + allElements.contains("com.microsoft.samples.subpackage.InternalException")); + assertTrue( + "Unexpected to-exclude class", + allElements.contains("com.microsoft.samples.subpackage.SomeExcludedClass")); + + List extractedElements = + elementUtil.extractSortedElements(element).stream() + .map(String::valueOf) + .collect(Collectors.toList()); + + // Verify filtered and sorted result + assertEquals("Wrong result list size", extractedElements.size(), 4); + assertEquals( + "Unexpected first item in the result list after invoke method extractSortedElements()", + extractedElements.get(0), + "com.microsoft.samples.subpackage.CustomException"); + assertEquals( + "Unexpected second item in the result list after invoke method extractSortedElements()", + extractedElements.get(1), + "com.microsoft.samples.subpackage.Display"); + assertEquals( + "Unexpected third item in the result list after invoke method extractSortedElements()", + extractedElements.get(2), + "com.microsoft.samples.subpackage.Person"); + } + + @Test + public void matchAnyPattern() { + HashSet patterns = + new HashSet<>( + Arrays.asList(Pattern.compile("com\\.ms\\.Some.*"), Pattern.compile(".*UsualClass"))); + assertTrue(elementUtil.matchAnyPattern(patterns, "com.ms.SomeStrangeClass")); + assertTrue(elementUtil.matchAnyPattern(patterns, "UsualClass")); + assertFalse(elementUtil.matchAnyPattern(patterns, "EngineFive")); + assertFalse(elementUtil.matchAnyPattern(patterns, "com.ms.Awesome")); + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/util/FileUtilTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/util/FileUtilTest.java index dfb675bd..16c379ad 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/util/FileUtilTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/util/FileUtilTest.java @@ -1,8 +1,7 @@ package com.microsoft.util; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; @@ -10,60 +9,58 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.Comparator; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; public class FileUtilTest { - private final String ROOT_DIR = "target/dir1"; - private final String FILE_NAME = ROOT_DIR + "/dir2/out.txt"; + private final String ROOT_DIR = "target/dir1"; + private final String FILE_NAME = ROOT_DIR + "/dir2/out.txt"; - @Before - public void setup() throws IOException { - deleteDirectory(ROOT_DIR); - } + @Before + public void setup() throws IOException { + deleteDirectory(ROOT_DIR); + } - @After - public void tearDown() throws IOException { - deleteDirectory(ROOT_DIR); - } + @After + public void tearDown() throws IOException { + deleteDirectory(ROOT_DIR); + } - @Test - public void dumpToFileWithDirectoryCreation() throws IOException { - String content = "Bla-bla content"; + @Test + public void dumpToFileWithDirectoryCreation() throws IOException { + String content = "Bla-bla content"; - FileUtil.dumpToFile(content, FILE_NAME); + FileUtil.dumpToFile(content, FILE_NAME); - assertTrue("New file should appear", Files.exists(Paths.get(FILE_NAME))); - assertEquals("Invalid file content", Files.readString(Paths.get(FILE_NAME)), content); - } + assertTrue("New file should appear", Files.exists(Paths.get(FILE_NAME))); + assertEquals("Invalid file content", Files.readString(Paths.get(FILE_NAME)), content); + } - @Test - public void dumpToFileForExistingNonEmptyDirectory() throws IOException { - createDirectoryWithFile(ROOT_DIR + "/dir2/tmp1.txt"); - String content = "Bla-bla content"; + @Test + public void dumpToFileForExistingNonEmptyDirectory() throws IOException { + createDirectoryWithFile(ROOT_DIR + "/dir2/tmp1.txt"); + String content = "Bla-bla content"; - FileUtil.dumpToFile(content, FILE_NAME); + FileUtil.dumpToFile(content, FILE_NAME); - assertTrue("Existing file should not be deleted", Files.exists(Path.of(ROOT_DIR + "/dir2/tmp1.txt"))); - assertTrue("New file should appear", Files.exists(Paths.get(FILE_NAME))); - assertEquals("Invalid file content", Files.readString(Paths.get(FILE_NAME)), content); - } + assertTrue( + "Existing file should not be deleted", Files.exists(Path.of(ROOT_DIR + "/dir2/tmp1.txt"))); + assertTrue("New file should appear", Files.exists(Paths.get(FILE_NAME))); + assertEquals("Invalid file content", Files.readString(Paths.get(FILE_NAME)), content); + } - public static void deleteDirectory(String pathString) throws IOException { - Path path = Paths.get(pathString); - if (Files.exists(path)) { - Files.walk(path) - .sorted(Comparator.reverseOrder()) - .map(Path::toFile) - .forEach(File::delete); - } + public static void deleteDirectory(String pathString) throws IOException { + Path path = Paths.get(pathString); + if (Files.exists(path)) { + Files.walk(path).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); } + } - public static void createDirectoryWithFile(String pathString) throws IOException { - Path path = Paths.get(pathString); - Files.createDirectories(path.getParent()); - Files.createFile(path); - } + public static void createDirectoryWithFile(String pathString) throws IOException { + Path path = Paths.get(pathString); + Files.createDirectories(path.getParent()); + Files.createFile(path); + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/util/OptionsFileUtilTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/util/OptionsFileUtilTest.java index 093fa9b0..3491b94e 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/util/OptionsFileUtilTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/util/OptionsFileUtilTest.java @@ -1,40 +1,46 @@ package com.microsoft.util; -import org.junit.Test; -import java.util.List; - import static org.junit.Assert.assertTrue; +import java.util.List; +import org.junit.Test; + public class OptionsFileUtilTest { - private final String PARAMS_DIR = "src/test/resources/test-doclet-params.txt"; + private final String PARAMS_DIR = "src/test/resources/test-doclet-params.txt"; - @Test - public void processOptionsFile() { - List strings = OptionsFileUtil.processOptionsFile(PARAMS_DIR); + @Test + public void processOptionsFile() { + List strings = OptionsFileUtil.processOptionsFile(PARAMS_DIR); - assertTrue("Wrong result", strings.contains("-doclet")); - assertTrue("Wrong result", strings.contains("com.microsoft.doclet.DocFxDoclet")); + assertTrue("Wrong result", strings.contains("-doclet")); + assertTrue("Wrong result", strings.contains("com.microsoft.doclet.DocFxDoclet")); - assertTrue("Wrong result", strings.contains("-sourcepath")); - assertTrue("Wrong result", strings.contains("./src/test/java")); + assertTrue("Wrong result", strings.contains("-sourcepath")); + assertTrue("Wrong result", strings.contains("./src/test/java")); - assertTrue("Wrong result", strings.contains("-outputpath")); - assertTrue("Wrong result", strings.contains("./target/test-out")); + assertTrue("Wrong result", strings.contains("-outputpath")); + assertTrue("Wrong result", strings.contains("./target/test-out")); - assertTrue("Wrong result", strings.contains("-encoding")); - assertTrue("Wrong result", strings.contains("UTF-8")); + assertTrue("Wrong result", strings.contains("-encoding")); + assertTrue("Wrong result", strings.contains("UTF-8")); - assertTrue("Wrong result", strings.contains("-projectname")); - assertTrue("Wrong result", strings.contains("google-cloud-project-parent")); + assertTrue("Wrong result", strings.contains("-projectname")); + assertTrue("Wrong result", strings.contains("google-cloud-project-parent")); - assertTrue("Wrong result", strings.contains("-excludepackages")); - assertTrue("Wrong result", strings.contains("com\\.microsoft\\.samples\\.someexcludedpack.*:com\\.microsoft\\.samples\\.someunexistingpackage")); + assertTrue("Wrong result", strings.contains("-excludepackages")); + assertTrue( + "Wrong result", + strings.contains( + "com\\.microsoft\\.samples\\.someexcludedpack.*:com\\.microsoft\\.samples\\.someunexistingpackage")); - assertTrue("Wrong result", strings.contains("-excludeclasses")); - assertTrue("Wrong result", strings.contains("com\\.microsoft\\.samples\\.subpackage\\.SomeExcluded.*:com\\.microsoft\\.samples\\.subpackage\\.SomeUnexistingClass")); + assertTrue("Wrong result", strings.contains("-excludeclasses")); + assertTrue( + "Wrong result", + strings.contains( + "com\\.microsoft\\.samples\\.subpackage\\.SomeExcluded.*:com\\.microsoft\\.samples\\.subpackage\\.SomeUnexistingClass")); - assertTrue("Wrong result", strings.contains("-subpackages")); - assertTrue("Wrong result", strings.contains("com.microsoft.samples")); - } + assertTrue("Wrong result", strings.contains("-subpackages")); + assertTrue("Wrong result", strings.contains("com.microsoft.samples")); + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/util/UtilsTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/util/UtilsTest.java index 2acf975f..ff9ad5b8 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/util/UtilsTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/util/UtilsTest.java @@ -1,97 +1,98 @@ package com.microsoft.util; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import com.google.testing.compile.CompilationRule; +import java.util.List; +import java.util.stream.Collectors; +import javax.lang.model.element.Element; +import javax.lang.model.element.ElementKind; +import javax.lang.model.util.Elements; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; -import javax.lang.model.element.Element; -import javax.lang.model.element.ElementKind; -import javax.lang.model.util.Elements; -import java.util.List; -import java.util.stream.Collectors; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - @RunWith(MockitoJUnitRunner.class) public class UtilsTest { - @Rule - public CompilationRule rule = new CompilationRule(); - private Elements elements; - private List allElements; - - @Before - public void setup() { - elements = rule.getElements(); - Element element = elements.getTypeElement("com.microsoft.samples.SuperHero"); - allElements = element.getEnclosedElements().stream().collect(Collectors.toList()); - } - - // Test isPackagePrivate() method - @Test - public void isPackagePrivate_True_PackagePrivateMethod() { - Element method = getElementByKindAndName(allElements, ElementKind.METHOD, "getHobby()"); - assertTrue(Utils.isPackagePrivate(method)); - } - - @Test - public void isPackagePrivate_True_PackagePrivateField() { - Element field = getElementByKindAndName(allElements, ElementKind.FIELD, "hobby"); - assertTrue(Utils.isPackagePrivate(field)); - } - - // Test isPrivate() method - @Test - public void isPrivate_True_PrivateMethod() { - Element method = getElementByKindAndName(allElements, ElementKind.METHOD, "setHobby(java.lang.String)"); - assertTrue(Utils.isPrivate(method)); - } - - @Test - public void isPrivate_True_PrivateField() { - Element field = getElementByKindAndName(allElements, ElementKind.FIELD, "uniquePower"); - assertTrue(Utils.isPrivate(field)); - } - - // Test isPrivateOrPackagePrivate() method - @Test - public void isPrivateOrPackagePrivate_True_PackagePrivateMethod() { - Element method = getElementByKindAndName(allElements, ElementKind.METHOD, "getHobby()"); - assertTrue(Utils.isPrivateOrPackagePrivate(method)); - } - - @Test - public void isPrivateOrPackagePrivate_True_PrivateFiled() { - Element field = getElementByKindAndName(allElements, ElementKind.FIELD, "uniquePower"); - assertTrue(Utils.isPrivateOrPackagePrivate(field)); - } - - @Test - public void isPrivateOrPackagePrivate_False_PublicMethod() { - Element method = getElementByKindAndName(allElements, ElementKind.METHOD, "getUniquePower()"); - assertFalse(Utils.isPrivateOrPackagePrivate(method)); - } - - @Test - public void isPrivateOrPackagePrivate_False_PublicField() { - Element field = getElementByKindAndName(allElements, ElementKind.FIELD, "SOME_PUBLIC_STRING"); - assertFalse(Utils.isPrivateOrPackagePrivate(field)); - } - - @Test - public void isPrivateOrPackagePrivate_False_ProtectedMethod() { - Element method = getElementByKindAndName(allElements, ElementKind.METHOD, "getHealth()"); - assertFalse(Utils.isPrivateOrPackagePrivate(method)); - } - - private Element getElementByKindAndName(List elements, ElementKind elementKind, String name) { - return elements.stream() - .filter(e -> e.toString().equals(name)) - .filter(e -> e.getKind() == elementKind) - .findFirst().orElse(null); - } + @Rule public CompilationRule rule = new CompilationRule(); + private Elements elements; + private List allElements; + + @Before + public void setup() { + elements = rule.getElements(); + Element element = elements.getTypeElement("com.microsoft.samples.SuperHero"); + allElements = element.getEnclosedElements().stream().collect(Collectors.toList()); + } + + // Test isPackagePrivate() method + @Test + public void isPackagePrivate_True_PackagePrivateMethod() { + Element method = getElementByKindAndName(allElements, ElementKind.METHOD, "getHobby()"); + assertTrue(Utils.isPackagePrivate(method)); + } + + @Test + public void isPackagePrivate_True_PackagePrivateField() { + Element field = getElementByKindAndName(allElements, ElementKind.FIELD, "hobby"); + assertTrue(Utils.isPackagePrivate(field)); + } + + // Test isPrivate() method + @Test + public void isPrivate_True_PrivateMethod() { + Element method = + getElementByKindAndName(allElements, ElementKind.METHOD, "setHobby(java.lang.String)"); + assertTrue(Utils.isPrivate(method)); + } + + @Test + public void isPrivate_True_PrivateField() { + Element field = getElementByKindAndName(allElements, ElementKind.FIELD, "uniquePower"); + assertTrue(Utils.isPrivate(field)); + } + + // Test isPrivateOrPackagePrivate() method + @Test + public void isPrivateOrPackagePrivate_True_PackagePrivateMethod() { + Element method = getElementByKindAndName(allElements, ElementKind.METHOD, "getHobby()"); + assertTrue(Utils.isPrivateOrPackagePrivate(method)); + } + + @Test + public void isPrivateOrPackagePrivate_True_PrivateFiled() { + Element field = getElementByKindAndName(allElements, ElementKind.FIELD, "uniquePower"); + assertTrue(Utils.isPrivateOrPackagePrivate(field)); + } + + @Test + public void isPrivateOrPackagePrivate_False_PublicMethod() { + Element method = getElementByKindAndName(allElements, ElementKind.METHOD, "getUniquePower()"); + assertFalse(Utils.isPrivateOrPackagePrivate(method)); + } + + @Test + public void isPrivateOrPackagePrivate_False_PublicField() { + Element field = getElementByKindAndName(allElements, ElementKind.FIELD, "SOME_PUBLIC_STRING"); + assertFalse(Utils.isPrivateOrPackagePrivate(field)); + } + + @Test + public void isPrivateOrPackagePrivate_False_ProtectedMethod() { + Element method = getElementByKindAndName(allElements, ElementKind.METHOD, "getHealth()"); + assertFalse(Utils.isPrivateOrPackagePrivate(method)); + } + + private Element getElementByKindAndName( + List elements, ElementKind elementKind, String name) { + return elements.stream() + .filter(e -> e.toString().equals(name)) + .filter(e -> e.getKind() == elementKind) + .findFirst() + .orElse(null); + } } diff --git a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/util/YamlUtilTest.java b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/util/YamlUtilTest.java index b2856fda..44c26e60 100644 --- a/third_party/docfx-doclet-143274/src/test/java/com/microsoft/util/YamlUtilTest.java +++ b/third_party/docfx-doclet-143274/src/test/java/com/microsoft/util/YamlUtilTest.java @@ -1,174 +1,211 @@ package com.microsoft.util; +import static org.junit.Assert.*; + import com.microsoft.model.MetadataFile; import com.microsoft.model.MetadataFileItem; import com.microsoft.model.MethodParameter; -import org.apache.commons.io.FileUtils; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; import java.util.Collections; import java.util.UUID; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.*; +import org.junit.Test; public class YamlUtilTest { - @Test - public void objectToYamlString() { - MetadataFile metadataFile = new MetadataFile("", "SomeFileName"); - metadataFile.getItems().add(buildMetadataFileItem(3)); - metadataFile.getReferences().add(buildMetadataFileItem(5)); - - String result = YamlUtil.objectToYamlString(metadataFile); - - assertEquals("Wrong result", result, "" - + "items:\n" - + "- uid: \"Some uid 3\"\n" - + " id: \"Some id3\"\n" - + " href: \"Some href3\"\n" - + " syntax:\n" - + " parameters:\n" - + " - id: \"Some id 3\"\n" - + " type: \"Some type 3\"\n" - + " description: \"Some desc 3\"\n" - + "references:\n" - + "- uid: \"Some uid 5\"\n" - + " id: \"Some id5\"\n" - + " href: \"Some href5\"\n" - + " syntax:\n" - + " parameters:\n" - + " - id: \"Some id 5\"\n" - + " type: \"Some type 5\"\n" - + " description: \"Some desc 5\"\n"); - } - - private MetadataFileItem buildMetadataFileItem(int seed) { - MetadataFileItem metadataFileItem = new MetadataFileItem("Some uid " + seed); - metadataFileItem.setId("Some id" + seed); - metadataFileItem.setHref("Some href" + seed); - metadataFileItem.setParameters(Collections.singletonList( - new MethodParameter("Some id " + seed, "Some type " + seed, "Some desc " + seed))); - - return metadataFileItem; - } - - - @Test - public void cleanupHtmlRemoveLonePreTagsTest() { - String expectedActual = "
text
"; - String expectedResult = "text"; - String expectedWithCode = "
text
"; - String random = UUID.randomUUID().toString(); - - assertEquals(expectedResult, YamlUtil.cleanupHtml(expectedActual)); - assertEquals(random + expectedResult + random, YamlUtil.cleanupHtml(random + expectedActual + random)); - assertEquals(expectedResult + random + expectedResult, YamlUtil.cleanupHtml(expectedActual + random + expectedActual)); - assertEquals(expectedWithCode, YamlUtil.cleanupHtml(expectedWithCode)); - } - - @Test - public void cleanupHtmlIncludePrettyPrintTest() { - String expectedActual = "
";
-        String expectedResult = "
";
-        String random = UUID.randomUUID().toString();
-
-        assertEquals(expectedResult, YamlUtil.cleanupHtml(expectedActual));
-        assertEquals(random + expectedResult + random, YamlUtil.cleanupHtml(random + expectedActual + random));
-        assertEquals(expectedResult + random + expectedResult, YamlUtil.cleanupHtml(expectedActual + random + expectedActual));
-        assertNotEquals(expectedResult, YamlUtil.cleanupHtml("
" + random + ""));
-        assertFalse(YamlUtil.cleanupHtml("
" + random + "").contains("class=\"prettyprint lang-java\""));
-    }
-
-    @Test
-    public void cleanupHtmlEncodeBracketsTest() {
-        String expectedActual = " List things = new ArrayList<>(); \n  

text

" ; - String expectedResult = " List<String> things = new ArrayList<>(); \n

text

<Object>"; - String random = UUID.randomUUID().toString(); - - assertEquals(expectedResult, YamlUtil.cleanupHtml(expectedActual)); - assertEquals(random + expectedResult + random, YamlUtil.cleanupHtml(random + expectedActual + random)); - } - - @Test - public void cleanupHtmlAddCodeTagsTest() { - String expectedActual = "`text`"; - String expectedResult = "text"; - String random = UUID.randomUUID().toString(); - - assertEquals(expectedResult, YamlUtil.cleanupHtml(expectedActual)); - assertEquals(random + expectedResult + random, YamlUtil.cleanupHtml(random + expectedActual + random)); - assertEquals(expectedResult + random + expectedResult, YamlUtil.cleanupHtml(expectedActual + random + expectedActual)); - assertEquals("`" + expectedResult, YamlUtil.cleanupHtml("`" + expectedActual)); - assertFalse(YamlUtil.cleanupHtml("`" + random).contains("")); - } - - @Test - public void cleanupHtmlAddHrefTagsTest() { - String expectedActual = "[text](link)"; - String expectedResult = "text"; - String random = UUID.randomUUID().toString(); - - assertEquals(expectedResult, YamlUtil.cleanupHtml(expectedActual)); - assertEquals(random + expectedResult + random, YamlUtil.cleanupHtml(random + expectedActual + random)); - assertEquals(expectedResult + random + expectedResult, YamlUtil.cleanupHtml(expectedActual + random + expectedActual)); - assertEquals("[text]](link)", YamlUtil.cleanupHtml("[text]](link)")); - assertFalse(YamlUtil.cleanupHtml("[text(link)]").contains("href")); - } - - @Test - public void cleanupHtmlEqualTitlesTest() { - String expectedActual = "======================= SpeechClient ======================="; - String expectedResult = "

SpeechClient

"; - String random = UUID.randomUUID().toString(); - - assertEquals(expectedResult, YamlUtil.cleanupHtml(expectedActual)); - assertEquals(random + expectedResult + random, YamlUtil.cleanupHtml(random + expectedActual + random)); - assertEquals(expectedResult + random + expectedResult, YamlUtil.cleanupHtml(expectedActual + random + expectedActual)); - - assertEquals("= text =", YamlUtil.cleanupHtml("= text =")); - assertEquals("==testing==", YamlUtil.cleanupHtml("==testing==")); - assertEquals("=======================SpeechClient=======================", "=======================SpeechClient======================="); - assertEquals("\"scikit-learn\":\"==0.19.0\"TextTextText\"botocore\":\"==1.7.14\"", "\"scikit-learn\":\"==0.19.0\"TextTextText\"botocore\":\"==1.7.14\""); - assertEquals("======= test1234 ===== 1234test === 1234test1234 == test =", YamlUtil.cleanupHtml("======= test1234 ===== 1234test === 1234test1234 == test =")); - assertEquals("====== Markdown H1 Test ======", YamlUtil.cleanupHtml("====== Markdown H1 Test ======")); - } - - @Test - public void cleanupHtmlReferenceTest() { - String expectedActual = "[KeyRing][google.cloud.kms.v1.KeyRing]"; - String expectedResult = "KeyRing"; - String random = UUID.randomUUID().toString(); - - assertEquals(expectedResult, YamlUtil.cleanupHtml(expectedActual)); - assertEquals(random + expectedResult + random, YamlUtil.cleanupHtml(random + expectedActual + random)); - assertEquals(expectedResult + random + expectedResult, YamlUtil.cleanupHtml(expectedActual + random + expectedActual)); - - assertEquals("[uid]][text]", YamlUtil.cleanupHtml("[uid]][text]")); - assertFalse(YamlUtil.cleanupHtml("[text[uid]]").contains("xref")); - } - - @Test - public void cleanupHtmlLinkTagWithLinkTest() { - String expectedActual = "{@link \"http://www.bad-way-to-include-link.com#section\"}"; - String expectedResult = "http://www.bad-way-to-include-link.com#section"; - String random = UUID.randomUUID().toString(); - - assertEquals(expectedResult, YamlUtil.cleanupHtml(expectedActual)); - assertEquals(random + expectedResult + random, YamlUtil.cleanupHtml(random + expectedActual + random)); - assertEquals(expectedResult + random + expectedResult, YamlUtil.cleanupHtml(expectedActual + random + expectedActual)); - } - - @Test - public void cleanupHtmlLinkTagNotRecognizedTest() { - String expectedActual = "{@link WeirdLink#didntResolve(null)}"; - String expectedResult = "WeirdLink#didntResolve(null)"; - String random = UUID.randomUUID().toString(); - - assertEquals(expectedResult, YamlUtil.cleanupHtml(expectedActual)); - assertEquals(random + expectedResult + random, YamlUtil.cleanupHtml(random + expectedActual + random)); - assertEquals(expectedResult + random + expectedResult, YamlUtil.cleanupHtml(expectedActual + random + expectedActual)); - } + @Test + public void objectToYamlString() { + MetadataFile metadataFile = new MetadataFile("", "SomeFileName"); + metadataFile.getItems().add(buildMetadataFileItem(3)); + metadataFile.getReferences().add(buildMetadataFileItem(5)); + + String result = YamlUtil.objectToYamlString(metadataFile); + + assertEquals( + "Wrong result", + result, + "" + + "items:\n" + + "- uid: \"Some uid 3\"\n" + + " id: \"Some id3\"\n" + + " href: \"Some href3\"\n" + + " syntax:\n" + + " parameters:\n" + + " - id: \"Some id 3\"\n" + + " type: \"Some type 3\"\n" + + " description: \"Some desc 3\"\n" + + "references:\n" + + "- uid: \"Some uid 5\"\n" + + " id: \"Some id5\"\n" + + " href: \"Some href5\"\n" + + " syntax:\n" + + " parameters:\n" + + " - id: \"Some id 5\"\n" + + " type: \"Some type 5\"\n" + + " description: \"Some desc 5\"\n"); + } + + private MetadataFileItem buildMetadataFileItem(int seed) { + MetadataFileItem metadataFileItem = new MetadataFileItem("Some uid " + seed); + metadataFileItem.setId("Some id" + seed); + metadataFileItem.setHref("Some href" + seed); + metadataFileItem.setParameters( + Collections.singletonList( + new MethodParameter("Some id " + seed, "Some type " + seed, "Some desc " + seed))); + + return metadataFileItem; + } + + @Test + public void cleanupHtmlRemoveLonePreTagsTest() { + String expectedActual = "
text
"; + String expectedResult = "text"; + String expectedWithCode = "
text
"; + String random = UUID.randomUUID().toString(); + + assertEquals(expectedResult, YamlUtil.cleanupHtml(expectedActual)); + assertEquals( + random + expectedResult + random, YamlUtil.cleanupHtml(random + expectedActual + random)); + assertEquals( + expectedResult + random + expectedResult, + YamlUtil.cleanupHtml(expectedActual + random + expectedActual)); + assertEquals(expectedWithCode, YamlUtil.cleanupHtml(expectedWithCode)); + } + + @Test + public void cleanupHtmlIncludePrettyPrintTest() { + String expectedActual = "
";
+    String expectedResult = "
";
+    String random = UUID.randomUUID().toString();
+
+    assertEquals(expectedResult, YamlUtil.cleanupHtml(expectedActual));
+    assertEquals(
+        random + expectedResult + random, YamlUtil.cleanupHtml(random + expectedActual + random));
+    assertEquals(
+        expectedResult + random + expectedResult,
+        YamlUtil.cleanupHtml(expectedActual + random + expectedActual));
+    assertNotEquals(expectedResult, YamlUtil.cleanupHtml("
" + random + ""));
+    assertFalse(
+        YamlUtil.cleanupHtml("
" + random + "")
+            .contains("class=\"prettyprint lang-java\""));
+  }
+
+  @Test
+  public void cleanupHtmlEncodeBracketsTest() {
+    String expectedActual =
+        " List things = new ArrayList<>(); \n  

text

"; + String expectedResult = + " List<String> things = new ArrayList<>(); \n

text

<Object>"; + String random = UUID.randomUUID().toString(); + + assertEquals(expectedResult, YamlUtil.cleanupHtml(expectedActual)); + assertEquals( + random + expectedResult + random, YamlUtil.cleanupHtml(random + expectedActual + random)); + } + + @Test + public void cleanupHtmlAddCodeTagsTest() { + String expectedActual = "`text`"; + String expectedResult = "text"; + String random = UUID.randomUUID().toString(); + + assertEquals(expectedResult, YamlUtil.cleanupHtml(expectedActual)); + assertEquals( + random + expectedResult + random, YamlUtil.cleanupHtml(random + expectedActual + random)); + assertEquals( + expectedResult + random + expectedResult, + YamlUtil.cleanupHtml(expectedActual + random + expectedActual)); + assertEquals("`" + expectedResult, YamlUtil.cleanupHtml("`" + expectedActual)); + assertFalse(YamlUtil.cleanupHtml("`" + random).contains("")); + } + + @Test + public void cleanupHtmlAddHrefTagsTest() { + String expectedActual = "[text](link)"; + String expectedResult = "text"; + String random = UUID.randomUUID().toString(); + + assertEquals(expectedResult, YamlUtil.cleanupHtml(expectedActual)); + assertEquals( + random + expectedResult + random, YamlUtil.cleanupHtml(random + expectedActual + random)); + assertEquals( + expectedResult + random + expectedResult, + YamlUtil.cleanupHtml(expectedActual + random + expectedActual)); + assertEquals("[text]](link)", YamlUtil.cleanupHtml("[text]](link)")); + assertFalse(YamlUtil.cleanupHtml("[text(link)]").contains("href")); + } + + @Test + public void cleanupHtmlEqualTitlesTest() { + String expectedActual = "======================= SpeechClient ======================="; + String expectedResult = "

SpeechClient

"; + String random = UUID.randomUUID().toString(); + + assertEquals(expectedResult, YamlUtil.cleanupHtml(expectedActual)); + assertEquals( + random + expectedResult + random, YamlUtil.cleanupHtml(random + expectedActual + random)); + assertEquals( + expectedResult + random + expectedResult, + YamlUtil.cleanupHtml(expectedActual + random + expectedActual)); + + assertEquals("= text =", YamlUtil.cleanupHtml("= text =")); + assertEquals("==testing==", YamlUtil.cleanupHtml("==testing==")); + assertEquals( + "=======================SpeechClient=======================", + "=======================SpeechClient======================="); + assertEquals( + "\"scikit-learn\":\"==0.19.0\"TextTextText\"botocore\":\"==1.7.14\"", + "\"scikit-learn\":\"==0.19.0\"TextTextText\"botocore\":\"==1.7.14\""); + assertEquals( + "======= test1234 ===== 1234test === 1234test1234 == test =", + YamlUtil.cleanupHtml("======= test1234 ===== 1234test === 1234test1234 == test =")); + assertEquals( + "====== Markdown H1 Test ======", YamlUtil.cleanupHtml("====== Markdown H1 Test ======")); + } + + @Test + public void cleanupHtmlReferenceTest() { + String expectedActual = "[KeyRing][google.cloud.kms.v1.KeyRing]"; + String expectedResult = + "KeyRing"; + String random = UUID.randomUUID().toString(); + + assertEquals(expectedResult, YamlUtil.cleanupHtml(expectedActual)); + assertEquals( + random + expectedResult + random, YamlUtil.cleanupHtml(random + expectedActual + random)); + assertEquals( + expectedResult + random + expectedResult, + YamlUtil.cleanupHtml(expectedActual + random + expectedActual)); + + assertEquals("[uid]][text]", YamlUtil.cleanupHtml("[uid]][text]")); + assertFalse(YamlUtil.cleanupHtml("[text[uid]]").contains("xref")); + } + + @Test + public void cleanupHtmlLinkTagWithLinkTest() { + String expectedActual = "{@link \"http://www.bad-way-to-include-link.com#section\"}"; + String expectedResult = + "http://www.bad-way-to-include-link.com#section"; + String random = UUID.randomUUID().toString(); + + assertEquals(expectedResult, YamlUtil.cleanupHtml(expectedActual)); + assertEquals( + random + expectedResult + random, YamlUtil.cleanupHtml(random + expectedActual + random)); + assertEquals( + expectedResult + random + expectedResult, + YamlUtil.cleanupHtml(expectedActual + random + expectedActual)); + } + + @Test + public void cleanupHtmlLinkTagNotRecognizedTest() { + String expectedActual = "{@link WeirdLink#didntResolve(null)}"; + String expectedResult = + "WeirdLink#didntResolve(null)"; + String random = UUID.randomUUID().toString(); + + assertEquals(expectedResult, YamlUtil.cleanupHtml(expectedActual)); + assertEquals( + random + expectedResult + random, YamlUtil.cleanupHtml(random + expectedActual + random)); + assertEquals( + expectedResult + random + expectedResult, + YamlUtil.cleanupHtml(expectedActual + random + expectedActual)); + } } diff --git a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.BasePartnerComponent.yml b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.BasePartnerComponent.yml index 5aa4cfcf..5d4b9f0d 100644 --- a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.BasePartnerComponent.yml +++ b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.BasePartnerComponent.yml @@ -14,7 +14,7 @@ items: fullName: "com.microsoft.samples.BasePartnerComponent" type: "Class" package: "com.microsoft.samples" - summary: "Holds common partner component properties and behavior. All components should inherit from this class. The context\n object type." + summary: "Holds common partner component properties and behavior. All components should inherit from this\n class. The context object type." syntax: content: "public abstract class BasePartnerComponent" typeParameters: diff --git a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.IPartner.yml b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.IPartner.yml index 9bae6eeb..f225f621 100644 --- a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.IPartner.yml +++ b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.IPartner.yml @@ -12,7 +12,7 @@ items: fullName: "com.microsoft.samples.IPartner" type: "Interface" package: "com.microsoft.samples" - summary: "The main entry point into using the partner SDK functionality. Represents a partner and encapsulates all the behavior\n attached to partners. Use this interface to get to the partner's customers, profiles, and customer orders, profiles\n and subscriptions and more." + summary: "The main entry point into using the partner SDK functionality. Represents a partner and\n encapsulates all the behavior attached to partners. Use this interface to get to the partner's\n customers, profiles, and customer orders, profiles and subscriptions and more." syntax: content: "public interface IPartner" - uid: "com.microsoft.samples.IPartner.getCredentials()" diff --git a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.SuperHero.yml b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.SuperHero.yml index 457fbbdc..c86e4904 100644 --- a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.SuperHero.yml +++ b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.SuperHero.yml @@ -158,12 +158,12 @@ items: overridden: "com.microsoft.samples.subpackage.Person.getLastName()" type: "Method" package: "com.microsoft.samples" - summary: "Get capitalized last name. But it's not the end,\n because of multiline comment" + summary: "Get capitalized last name. But it's not the end, because we add a lot of text to make this a\n multiline comment" syntax: content: "public String getLastName()" return: type: "java.lang.String" - description: "lastName in uppercase. But it's not the end,\n because of multiline comment" + description: "lastName in uppercase. But it's not the end, because we add a lot of text to make this\n a multiline comment" - uid: "com.microsoft.samples.SuperHero.getUniquePower()" id: "getUniquePower()" parent: "com.microsoft.samples.SuperHero" @@ -254,7 +254,7 @@ items: overload: "com.microsoft.samples.SuperHero.successfullyAttacked*" type: "Method" package: "com.microsoft.samples" - summary: "\nDeprecated. As of version 1.1, use . . . instead\n\n

This is a simple description of the method. . .\n Superman!\n

\nSee Also: HERO-402\n" + summary: "\nDeprecated. As of version 1.1, use . . . instead\n\nThis is a simple description of the method. . . Superman!\nSee Also: HERO-402\n" syntax: content: "public int successfullyAttacked(int incomingDamage, String damageType)" parameters: diff --git a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.agreements.AgreementMetaData.yml b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.agreements.AgreementMetaData.yml index 50cdfb1e..6dc7f8cd 100644 --- a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.agreements.AgreementMetaData.yml +++ b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.agreements.AgreementMetaData.yml @@ -18,7 +18,7 @@ items: fullName: "com.microsoft.samples.agreements.AgreementMetaData" type: "Class" package: "com.microsoft.samples.agreements" - summary: "The AgreementMetaData provides metadata about the agreement type\n that partner can provide confirmation of customer acceptance." + summary: "The AgreementMetaData provides metadata about the agreement type that partner can provide\n confirmation of customer acceptance." syntax: content: "public class AgreementMetaData" inheritance: diff --git a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.agreements.ResourceCollection.yml b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.agreements.ResourceCollection.yml index 59cea190..80f3dd10 100644 --- a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.agreements.ResourceCollection.yml +++ b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.agreements.ResourceCollection.yml @@ -12,7 +12,7 @@ items: fullName: "com.microsoft.samples.agreements.ResourceCollection" type: "Class" package: "com.microsoft.samples.agreements" - summary: "Contains a collection of resources with JSON properties to represent the output Type of objects in collection" + summary: "Contains a collection of resources with JSON properties to represent the output Type of objects\n in collection" syntax: content: "public class ResourceCollection" typeParameters: diff --git a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.commentinheritance.Animal.yml b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.commentinheritance.Animal.yml index b3a2d5c4..4ded03b4 100644 --- a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.commentinheritance.Animal.yml +++ b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.commentinheritance.Animal.yml @@ -87,7 +87,7 @@ items: overload: "com.microsoft.samples.commentinheritance.Animal.getKind*" type: "Method" package: "com.microsoft.samples.commentinheritance" - summary: "Get kind from Organism.\n Get kind from Animal." + summary: "Get kind from Organism. Get kind from Animal." syntax: content: "public abstract String getKind()" return: diff --git a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.commentinheritance.Dog.yml b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.commentinheritance.Dog.yml index 169cf75c..91c05db5 100644 --- a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.commentinheritance.Dog.yml +++ b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.commentinheritance.Dog.yml @@ -138,7 +138,7 @@ items: overridden: "com.microsoft.samples.commentinheritance.Mammal.getKind()" type: "Method" package: "com.microsoft.samples.commentinheritance" - summary: "Get kind from Organism.\n Get kind from Animal.\n Get kind from Mammal.\n Get kind from Dog." + summary: "Get kind from Organism. Get kind from Animal. Get kind from Mammal. Get kind from Dog." syntax: content: "public String getKind()" return: diff --git a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.commentinheritance.Mammal.yml b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.commentinheritance.Mammal.yml index 82c30c40..16d78013 100644 --- a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.commentinheritance.Mammal.yml +++ b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.commentinheritance.Mammal.yml @@ -60,7 +60,7 @@ items: overridden: "com.microsoft.samples.commentinheritance.Animal.getKind()" type: "Method" package: "com.microsoft.samples.commentinheritance" - summary: "Get kind from Organism.\n Get kind from Animal.\n Get kind from Mammal." + summary: "Get kind from Organism. Get kind from Animal. Get kind from Mammal." syntax: content: "public abstract String getKind()" return: diff --git a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.commentinheritance.Omnivorous.yml b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.commentinheritance.Omnivorous.yml index 7dc54473..87bc961b 100644 --- a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.commentinheritance.Omnivorous.yml +++ b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.commentinheritance.Omnivorous.yml @@ -65,7 +65,7 @@ items: overload: "com.microsoft.samples.commentinheritance.Omnivorous.getKind*" type: "Method" package: "com.microsoft.samples.commentinheritance" - summary: "Get kind from Carnivorous.\n Get kind from Omnivorous." + summary: "Get kind from Carnivorous. Get kind from Omnivorous." syntax: content: "public abstract String getKind()" return: diff --git a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.google.BetaApi.yml b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.google.BetaApi.yml index d70e3939..3094daf5 100644 --- a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.google.BetaApi.yml +++ b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.google.BetaApi.yml @@ -12,7 +12,7 @@ items: fullName: "com.microsoft.samples.google.BetaApi" type: "Interface" package: "com.microsoft.samples.google" - summary: "Indicates a public API that can change at any time, and has no guarantee of API stability and\n backward-compatibility.\n\n

\n Usage guidelines:\n

    \n
  1. This annotation is used only on APIs with public visibility. Internal interfaces should not\n use it.
  2. \n
  3. This annotation should only be added to new APIs. Adding it to an existing API is considered\n API-breaking.
  4. \n
  5. Removing this annotation from an API gives it stable status, assuming the API doesn't have\n other annotations denoting instability.\n
" + summary: "Indicates a public API that can change at any time, and has no guarantee of API stability and\n backward-compatibility.\n\n

Usage guidelines:\n\n

    \n
  1. This annotation is used only on APIs with public visibility. Internal interfaces should not\n use it.\n
  2. This annotation should only be added to new APIs. Adding it to an existing API is\n considered API-breaking.\n
  3. Removing this annotation from an API gives it stable status, assuming the API doesn't have\n other annotations denoting instability.\n
" syntax: content: "public interface BetaApi implements Annotation" implements: diff --git a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.google.ValidationException.yml b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.google.ValidationException.yml index 74124c8a..d45df9d5 100644 --- a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.google.ValidationException.yml +++ b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.google.ValidationException.yml @@ -16,7 +16,7 @@ items: fullName: "com.microsoft.samples.google.ValidationException" type: "Class" package: "com.microsoft.samples.google" - summary: "Exception thrown if there is a validation problem with a path template, http config, or related\n framework methods. Comes as an illegal argument exception subclass. Allows to globally set a\n thread-local validation context description which each exception inherits.\nSee Also: Google Cloud Storage error codes\n" + summary: "Exception thrown if there is a validation problem with a path template, http config, or related\n framework methods. Comes as an illegal argument exception subclass. Allows to globally set a\n thread-local validation context description which each exception inherits.\nSee Also: Google Cloud Storage error codes\n" syntax: content: "public class ValidationException extends IllegalArgumentException" inheritance: diff --git a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.google.v1p1alpha.SpeechClient.yml b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.google.v1p1alpha.SpeechClient.yml index 759edda9..5b6934f3 100644 --- a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.google.v1p1alpha.SpeechClient.yml +++ b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.google.v1p1alpha.SpeechClient.yml @@ -170,7 +170,7 @@ items: overload: "com.microsoft.samples.google.v1p1alpha.SpeechClient.create*" type: "Method" package: "com.microsoft.samples.google.v1p1alpha" - summary: "Constructs an instance of SpeechClient, using the given settings. The channels are created\n based on the settings passed in, or defaults for any settings that are not set.\n Example broken links: http://tools.ietf.org/html/rfc2616#section-3.7\n ApiFutures#immediateFuture(null)." + summary: "Constructs an instance of SpeechClient, using the given settings. The channels are created\n based on the settings passed in, or defaults for any settings that are not set. Example broken\n links: http://tools.ietf.org/html/rfc2616#section-3.7 \n ApiFutures#immediateFuture(null)." syntax: content: "public static final SpeechClient create(SpeechSettings settings)" parameters: diff --git a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.subpackage.Display.yml b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.subpackage.Display.yml index 116528a9..a67b1121 100644 --- a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.subpackage.Display.yml +++ b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.subpackage.Display.yml @@ -13,7 +13,7 @@ items: fullName: "com.microsoft.samples.subpackage.Display" type: "Interface" package: "com.microsoft.samples.subpackage" - summary: "Do you see some First code block?\n

\n Or this Second code block?" + summary: "Do you see some First code block?\n\n

Or this Second code block?" syntax: content: "public interface Display extends Serializable, List>" typeParameters: diff --git a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.subpackage.Person.yml b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.subpackage.Person.yml index 1aa47a46..129b95ca 100644 --- a/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.subpackage.Person.yml +++ b/third_party/docfx-doclet-143274/src/test/resources/expected-generated-files/com.microsoft.samples.subpackage.Person.yml @@ -21,7 +21,7 @@ items: fullName: "com.microsoft.samples.subpackage.Person" type: "Class" package: "com.microsoft.samples.subpackage" - summary: "Class that describes some person\n\n This comment has links to:\n

    \n
  • Owner class Person
  • \n
  • Its inner class Person.IdentificationInfo
  • \n
  • Its method Person#setLastName(String lastName)
  • \n
  • Its method without params Person#setLastName()
  • \n
  • Its public field Person#age
  • \n
  • Another class which used here Set
  • \n
  • Another class which not used here List
  • \n
  • Broken link sdfdsagdsfghfgh
  • \n
  • Plain link someContent
  • \n
  • Link that starts from '#' #setLastName()
  • \n
  • Link with label WordOne
  • \n
\n\n This is an \"at\" symbol: @\nSee Also: Display\n" + summary: "Class that describes some person\n\n

This comment has links to:\n\n

    \n
  • Owner class Person\n
  • Its inner class Person.IdentificationInfo\n
  • Its method Person#setLastName(String lastName)\n
  • Its method without params Person#setLastName()\n
  • Its public field Person#age\n
  • Another class which used here Set\n
  • Another class which not used here List\n
  • Broken link sdfdsagdsfghfgh\n
  • Plain link someContent\n
  • Link that starts from '#' #setLastName()\n
  • Link with label WordOne\n
\n\n This is an \"at\" symbol: @\nSee Also: Display\n" syntax: content: "public class Person" typeParameters: