├── .github
└── PULL_REQUEST_TEMPLATE.md
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE.txt
├── NOTICE.txt
├── README.md
├── aws-java-sdk-generated-samples
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── amazonaws
│ └── samples
│ ├── GeneratedSamplesClassWriter.java
│ ├── SampleGenerationRunner.java
│ ├── SamplesGenerator.java
│ ├── exception
│ └── SampleGenerationException.java
│ └── util
│ └── IntermediateModelRetriever.java
├── aws-java-sdk-handwritten-samples
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── amazonaws
│ └── samples
│ └── s3
│ └── S3Samples.java
├── aws-java-sdk-sample-extractor
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── com
│ │ └── amazonaws
│ │ ├── codesamples
│ │ ├── CodeSample.java
│ │ ├── SampleCodeExtractor.java
│ │ ├── SamplesParser.java
│ │ ├── SamplesWriter.java
│ │ └── exception
│ │ │ └── SampleParsingException.java
│ │ └── util
│ │ └── ParsingUtils.java
│ └── test
│ ├── java
│ └── com
│ │ └── amazonaws
│ │ ├── codesamples
│ │ ├── CodeSampleTest.java
│ │ ├── SampleExtractorTestUtils.java
│ │ ├── SampleWriterTest.java
│ │ └── SamplesParserTest.java
│ │ └── util
│ │ └── ParsingUtilsTest.java
│ └── resources
│ └── testsamples
│ ├── BadBeginHiddenTagSample.java
│ ├── BadDescriptionTagSample.java
│ ├── BadEndHiddenTagSample.java
│ ├── BadEndTagSample.java
│ ├── BadExtension.cpp
│ ├── BadStartTagSample.java
│ ├── BadTitleTagSample.java
│ ├── EmptySamples.java
│ ├── NoContentSample.java
│ ├── NoDescriptionSample.java
│ ├── NoTitleSample.java
│ ├── TestSamples.java
│ └── UnclosedSample.java
├── aws-java-sdk-samples
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── com
│ │ └── amazonaws
│ │ └── codesamples
│ │ ├── RetrievedCodeSample.java
│ │ ├── SampleCodeReader.java
│ │ ├── SampleCodeTaglet.java
│ │ ├── SampleCodeXMLParser.java
│ │ ├── exception
│ │ └── SampleRetrievalException.java
│ │ └── util
│ │ ├── SampleHTMLTemplates.java
│ │ └── ValidationUtils.java
│ └── test
│ ├── java
│ └── com
│ │ └── amazonaws
│ │ └── codesamples
│ │ ├── RetrievedCodeSampleTest.java
│ │ └── SampleCodeReaderTest.java
│ └── resources
│ └── testsamples
│ └── FooService.xml
└── pom.xml
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | *Issue #, if available:*
2 |
3 | *Description of changes:*
4 |
5 |
6 | By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Eclipse
2 | .classpath
3 | .project
4 | .settings/
5 |
6 | # Intellij
7 | .idea/
8 | *.iml
9 | *.iws
10 |
11 | # Mac
12 | .DS_Store
13 |
14 | # Maven
15 | target/
16 |
17 | **/dependency-reduced-pom.xml
18 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | ## Code of Conduct
2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
4 | opensource-codeofconduct@amazon.com with any additional questions or comments.
5 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing Guidelines
2 |
3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional
4 | documentation, we greatly value feedback and contributions from our community.
5 |
6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary
7 | information to effectively respond to your bug report or contribution.
8 |
9 |
10 | ## Reporting Bugs/Feature Requests
11 |
12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features.
13 |
14 | When filing an issue, please check [existing open](https://github.com/aws/aws-sdk-java-samples/issues), or [recently closed](https://github.com/aws/aws-sdk-java-samples/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20), issues to make sure somebody else hasn't already
15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful:
16 |
17 | * A reproducible test case or series of steps
18 | * The version of our code being used
19 | * Any modifications you've made relevant to the bug
20 | * Anything unusual about your environment or deployment
21 |
22 |
23 | ## Contributing via Pull Requests
24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that:
25 |
26 | 1. You are working against the latest source on the *master* branch.
27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already.
28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted.
29 |
30 | To send us a pull request, please:
31 |
32 | 1. Fork the repository.
33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change.
34 | 3. Ensure local tests pass.
35 | 4. Commit to your fork using clear commit messages.
36 | 5. Send us a pull request, answering any default questions in the pull request interface.
37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation.
38 |
39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and
40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/).
41 |
42 |
43 | ## Finding contributions to work on
44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels ((enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any ['help wanted'](https://github.com/aws/aws-sdk-java-samples/labels/help%20wanted) issues is a great place to start.
45 |
46 |
47 | ## Code of Conduct
48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
50 | opensource-codeofconduct@amazon.com with any additional questions or comments.
51 |
52 |
53 | ## Security issue notifications
54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue.
55 |
56 |
57 | ## Licensing
58 |
59 | See the [LICENSE](https://github.com/aws/aws-sdk-java-samples/blob/master/LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution.
60 |
61 | We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes.
62 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 |
4 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
5 |
6 | 1. Definitions.
7 |
8 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
9 |
10 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
11 |
12 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
13 |
14 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
15 |
16 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
17 |
18 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
19 |
20 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
21 |
22 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
23 |
24 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
25 |
26 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
27 |
28 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
29 |
30 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
31 |
32 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
33 |
34 | 1. You must give any other recipients of the Work or Derivative Works a copy of this License; and
35 | 2. You must cause any modified files to carry prominent notices stating that You changed the files; and
36 | 3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
37 | 4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
38 |
39 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
40 |
41 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
42 |
43 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
44 |
45 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
46 |
47 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
48 |
49 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
50 |
51 | END OF TERMS AND CONDITIONS
52 |
53 | Note: Other license terms may apply to certain, identified software files contained within or distributed with the accompanying software if such terms are included in the directory containing the accompanying software. Such other license terms will then apply in lieu of the terms of the software license above.
54 |
--------------------------------------------------------------------------------
/NOTICE.txt:
--------------------------------------------------------------------------------
1 | AWS SDK for Java Samples
2 | Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 |
4 | This product includes software developed by
5 | Amazon Technologies, Inc (http://www.amazon.com/).
6 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # AWS SDK for Java Samples
2 | This repo contains modules that inject both handwritten and generated code samples for the AWS SDK for Java into the SDK Javadocs.
3 |
--------------------------------------------------------------------------------
/aws-java-sdk-generated-samples/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4.0.0
4 |
5 | com.amazonaws
6 | aws-java-sdk-samples-pom
7 | 1.1.4-SNAPSHOT
8 |
9 | com.amazonaws
10 | aws-java-sdk-generated-samples
11 | 1.1.4-SNAPSHOT
12 | aws-java-sdk-generated-samples
13 | http://maven.apache.org
14 | maven-plugin
15 |
16 | UTF-8
17 |
18 |
19 |
20 |
21 | org.apache.maven.plugins
22 | maven-compiler-plugin
23 | 3.3
24 |
25 | 1.8
26 | 1.8
27 |
28 |
29 |
30 | org.apache.maven.plugins
31 | maven-plugin-plugin
32 | 3.3
33 |
34 |
35 |
36 |
37 |
38 | junit
39 | junit
40 | 3.8.1
41 | test
42 |
43 |
44 | com.fasterxml.jackson.core
45 | jackson-core
46 | 2.5.5
47 |
48 |
49 | com.fasterxml.jackson.core
50 | jackson-annotations
51 | 2.5.5
52 |
53 |
54 | com.fasterxml.jackson.core
55 | jackson-databind
56 | 2.5.5
57 |
58 |
59 | commons-logging
60 | commons-logging
61 | 1.2
62 |
63 |
64 | org.apache.commons
65 | commons-lang3
66 | 3.4
67 |
68 |
69 | args4j
70 | args4j
71 | 2.32
72 |
73 |
74 | org.eclipse.jdt
75 | org.eclipse.jdt.core
76 | 3.10.0
77 |
78 |
79 | org.apache.maven
80 | maven-plugin-api
81 | 3.0
82 |
83 |
84 | org.apache.maven.plugin-tools
85 | maven-plugin-annotations
86 | 3.4
87 | provided
88 |
89 |
90 | org.twdata.maven
91 | mojo-executor
92 | 2.2.0
93 |
94 |
95 | com.amazonaws
96 | aws-java-sdk-code-generator
97 | ${awsjavasdk.version}
98 |
99 |
100 | com.amazonaws
101 | aws-java-sdk-models
102 | ${awsjavasdk.version}
103 |
104 |
105 |
106 |
--------------------------------------------------------------------------------
/aws-java-sdk-generated-samples/src/main/java/com/amazonaws/samples/GeneratedSamplesClassWriter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License").
5 | * You may not use this file except in compliance with the License.
6 | * A copy of the License is located at
7 | *
8 | * http://aws.amazon.com/apache2.0
9 | *
10 | * or in the "license" file accompanying this file. This file is distributed
11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 | * express or implied. See the License for the specific language governing
13 | * permissions and limitations under the License.
14 | */
15 | package com.amazonaws.samples;
16 |
17 | import java.io.File;
18 | import java.io.IOException;
19 | import java.nio.file.Files;
20 | import java.nio.file.Paths;
21 |
22 | import com.amazonaws.samples.exception.SampleGenerationException;
23 |
24 | /**
25 | * Utility to write contents of a generated samples class to disk.
26 | */
27 | public class GeneratedSamplesClassWriter {
28 |
29 | /**
30 | * Writes the contents of a generated samples class to disk.
31 | *
32 | * @param outputDirLocation
33 | * directory to write to
34 | * @param serviceName
35 | * name of service
36 | * @param samples
37 | * generated sample class contents
38 | */
39 | public static void writeSamples(String outputDirLocation, final String serviceName, final String samples) {
40 | if (!outputDirLocation.endsWith("/")) {
41 | outputDirLocation += "/";
42 | }
43 |
44 | File outputDir = new File(outputDirLocation);
45 | if (!outputDir.exists()) {
46 | outputDir.mkdirs();
47 | }
48 |
49 | try {
50 | String filename = String.format("%sGeneratedSamples.java", serviceName.replaceAll("\\s+", ""));
51 | Files.write(Paths.get(outputDirLocation + filename), samples.getBytes());
52 | } catch (IOException e) {
53 | throw new SampleGenerationException("Failed to write sample class", e);
54 | }
55 | }
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/aws-java-sdk-generated-samples/src/main/java/com/amazonaws/samples/SampleGenerationRunner.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License").
5 | * You may not use this file except in compliance with the License.
6 | * A copy of the License is located at
7 | *
8 | * http://aws.amazon.com/apache2.0
9 | *
10 | * or in the "license" file accompanying this file. This file is distributed
11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 | * express or implied. See the License for the specific language governing
13 | * permissions and limitations under the License.
14 | */
15 | package com.amazonaws.samples;
16 |
17 | import java.io.IOException;
18 | import org.apache.maven.execution.MavenSession;
19 | import org.apache.maven.plugins.annotations.Component;
20 | import org.apache.maven.plugins.annotations.Mojo;
21 | import org.apache.maven.plugins.annotations.Parameter;
22 | import org.apache.maven.plugin.AbstractMojo;
23 | import org.apache.maven.plugin.BuildPluginManager;
24 | import org.apache.maven.plugin.MojoExecutionException;
25 | import org.apache.maven.plugin.MojoFailureException;
26 | import org.apache.maven.project.MavenProject;
27 |
28 | import com.amazonaws.codegen.model.intermediate.IntermediateModel;
29 | import com.amazonaws.samples.util.IntermediateModelRetriever;
30 |
31 | import static org.twdata.maven.mojoexecutor.MojoExecutor.*;
32 |
33 | /**
34 | * Mojo to generate samples classes for JSON snippet samples retrieved from
35 | * dependencies on the classpath.
36 | */
37 | @Mojo(name = "GenerateSamples")
38 | public class SampleGenerationRunner extends AbstractMojo {
39 |
40 | @Component
41 | private MavenProject mavenProject;
42 |
43 | @Component
44 | private MavenSession mavenSession;
45 |
46 | @Component
47 | private BuildPluginManager pluginManager;
48 |
49 | @Parameter(defaultValue = "${project.build.sourceDirectory}")
50 | private String projectSourceDir;
51 |
52 | public void execute() throws MojoExecutionException, MojoFailureException {
53 | try {
54 | for (IntermediateModel model : IntermediateModelRetriever
55 | .getDependencyIntermediateModels()) {
56 | if (!model.getExamples().getOperationExamples().isEmpty()) {
57 | SamplesGenerator writer = new SamplesGenerator(model);
58 | GeneratedSamplesClassWriter.writeSamples(projectSourceDir + "/samples/",
59 | model
60 | .getMetadata().getSyncInterface(), writer
61 | .getGeneratedSamples());
62 | }
63 | }
64 |
65 | executeMojo(
66 | plugin(
67 | groupId("com.amazonaws"),
68 | artifactId("aws-java-sdk-sample-extractor"),
69 | version("LATEST")
70 | ),
71 | goal("ExtractSamples"),
72 | configuration(
73 | element("sourceExtension", "java"),
74 | element("sampleSubDir", "/samples")
75 | ),
76 | executionEnvironment(
77 | mavenProject,
78 | mavenSession,
79 | pluginManager));
80 |
81 | } catch (IOException e) {
82 | throw new MojoFailureException("Failed to generate samples", e);
83 | }
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/aws-java-sdk-generated-samples/src/main/java/com/amazonaws/samples/SamplesGenerator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License").
5 | * You may not use this file except in compliance with the License.
6 | * A copy of the License is located at
7 | *
8 | * http://aws.amazon.com/apache2.0
9 | *
10 | * or in the "license" file accompanying this file. This file is distributed
11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 | * express or implied. See the License for the specific language governing
13 | * permissions and limitations under the License.
14 | */
15 | package com.amazonaws.samples;
16 |
17 | import java.util.Iterator;
18 | import java.util.List;
19 | import java.util.Map;
20 | import java.util.Map.Entry;
21 | import java.util.HashMap;
22 |
23 | import com.amazonaws.codegen.model.intermediate.Example;
24 | import com.amazonaws.codegen.model.intermediate.IntermediateModel;
25 | import com.amazonaws.codegen.model.intermediate.ListModel;
26 | import com.amazonaws.codegen.model.intermediate.MapModel;
27 | import com.amazonaws.codegen.model.intermediate.MemberModel;
28 | import com.amazonaws.codegen.model.intermediate.Metadata;
29 | import com.amazonaws.codegen.model.intermediate.OperationModel;
30 | import com.amazonaws.codegen.model.intermediate.ShapeModel;
31 | import com.amazonaws.samples.exception.SampleGenerationException;
32 | import com.amazonaws.codegen.emitters.JavaCodeFormatter;
33 | import com.fasterxml.jackson.databind.JsonNode;
34 | import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants;
35 | import org.apache.commons.lang3.StringEscapeUtils;
36 |
37 | /**
38 | * Produces Java generated sample code from generic sample content included with
39 | * a service intermediate model.
40 | */
41 | public class SamplesGenerator {
42 |
43 | private final IntermediateModel model;
44 | private final StringBuilder sb;
45 | private final JavaCodeFormatter formatter;
46 |
47 | /**
48 | * Ctor.
49 | *
50 | * @param model
51 | * service intermediate model containing generic samples
52 | */
53 | public SamplesGenerator(final IntermediateModel model) {
54 | if (model == null) {
55 | throw new IllegalArgumentException("Intermediate model must be provided");
56 | }
57 |
58 | this.model = model;
59 | this.sb = new StringBuilder();
60 |
61 | Map formatterOptions = new HashMap();
62 | formatterOptions.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_LINE_COMMENT, false);
63 | this.formatter = new JavaCodeFormatter(formatterOptions);
64 | }
65 |
66 | /**
67 | * Produces Java generated samples content.
68 | *
69 | * @return generated samples content
70 | */
71 | public String getGeneratedSamples() {
72 | String serviceName = model.getMetadata().getSyncInterface();
73 |
74 | String packageName = model.getMetadata().getPackageName();
75 | writeLine("package com.amazonaws.codesamples.samples;\n");
76 | writeLine(String.format("import %s.%s;", packageName, serviceName));
77 | writeLine(String.format("import %s.%sClientBuilder;", packageName, serviceName));
78 | writeLine(String.format("import %s.model.*;\n", packageName));
79 | writeLine("import java.util.*;\n");
80 | writeLine("import java.nio.*;\n");
81 | writeLine("import java.io.*;");
82 | writeLine(String.format("public class %sGeneratedSamples {", serviceName));
83 |
84 | model.getExamples().getOperationExamples().forEach((k, v) -> emitCode(serviceName, k, v));
85 |
86 | writeLine("}");
87 |
88 | return formatter.apply(sb.toString());
89 | }
90 |
91 | private void emitCode(final String serviceName, final String operationName, final List examples) {
92 |
93 | if (model.getOperation(operationName).isDeprecated()) {
94 | return;
95 | }
96 |
97 | Metadata metadata = model.getMetadata();
98 | OperationModel operationModel = model.getOperations().get(operationName);
99 |
100 | if (operationModel == null) {
101 | throw new IllegalArgumentException("Could not retrieve operation model for operation " + operationName);
102 | }
103 |
104 | String operationMethodName = operationModel.getMethodName();
105 | String inputType = operationModel.getInput().getVariableType();
106 | ShapeModel inputModel = model.getShapes().get(inputType);
107 |
108 | for (int i = 0; i < examples.size(); i++) {
109 | Example example = examples.get(i);
110 |
111 | // There are some services literally providing "null" example
112 | if (example == null) {
113 | continue;
114 | }
115 |
116 | writeLine(String.format("public void %s_%s() {", operationName, i+1));
117 | writeLine(String.format("//BEGIN_SAMPLE:%s.%s", serviceName, operationName));
118 | writeLine("//TITLE:" + example.getTitle());
119 |
120 | if (example.getDescription() != null && example.getDescription().isEmpty()) {
121 | writeLine("//DESCRIPTION:" + operationName);
122 | } else {
123 | writeLine("//DESCRIPTION:" + example.getDescription());
124 | }
125 |
126 | writeLine(String.format("%s client = %sBuilder.standard().build();", metadata.getSyncInterface(), metadata.getSyncClient()));
127 | writeLine(String.format("%1$s request = new %1$s()", inputType));
128 |
129 | getRequestAssignments(example.getInput(), inputModel, example.getComments().getInputComments());
130 |
131 | if (operationModel.getReturnType() != null) {
132 | String returnType = operationModel.getReturnType().getReturnType();
133 | writeLine(String.format("%s response = client.%s(request);", returnType,
134 | operationMethodName));
135 | } else {
136 | writeLine(String.format("client.%s(request);", operationMethodName));
137 | }
138 | writeLine("//END_SAMPLE");
139 | writeLine("}");
140 | }
141 | }
142 |
143 | private void getRequestAssignments(final JsonNode node, final ShapeModel inputModel,
144 | final Map comments) {
145 | Iterator iter = node.fieldNames();
146 | while (iter.hasNext()) {
147 | String fieldName = iter.next();
148 | MemberModel memberModel = inputModel.findMemberModelByC2jName(fieldName);
149 |
150 | StringBuilder assignmentValue = new StringBuilder();
151 | getAssignmentValue(assignmentValue, node.get(fieldName), memberModel);
152 |
153 | if (comments != null && comments.containsKey(fieldName)) {
154 | writeLine("//" + comments.get(fieldName));
155 | }
156 |
157 | if (memberModel.isList()) {
158 | sb.append(String.format(".with%s(%s)", firstCharToUpper(fieldName), assignmentValue.toString()));
159 | } else if (memberModel.isMap()) {
160 | sb.append(assignmentValue.toString());
161 | } else {
162 | sb.append(String.format(".with%s(%s)", firstCharToUpper(fieldName), assignmentValue.toString()));
163 | }
164 | }
165 | sb.append(";\n");
166 | }
167 |
168 | private void getAssignmentValue(final StringBuilder sb, final JsonNode node, MemberModel memberModel) {
169 | if (memberModel.isSimple()) {
170 | sb.append(formatPrimitiveValue(memberModel.getSetterModel().getSimpleType(), node.asText()));
171 | } else if (memberModel.isList()) {
172 | ListModel listModel = memberModel.getListModel();
173 | Iterator iter = node.iterator();
174 |
175 | if (!iter.hasNext()) {
176 | sb.append("new ArrayList()");
177 | }
178 |
179 | while (iter.hasNext()) {
180 | JsonNode entry = iter.next();
181 |
182 | if (listModel.getListMemberModel() == null) {
183 | sb.append(formatPrimitiveValue(listModel.getMemberType(), entry.asText()));
184 | } else {
185 | getAssignmentValue(sb, entry, listModel.getListMemberModel());
186 | }
187 |
188 | if (iter.hasNext()) {
189 | sb.append(", ");
190 | }
191 | }
192 | } else if (memberModel.isMap()) {
193 | MapModel mapModel = memberModel.getMapModel();
194 | Iterator> iter = node.fields();
195 |
196 | while (iter.hasNext()) {
197 | Entry field = iter.next();
198 | JsonNode curNode = field.getValue();
199 | sb.append(String.format(".add%sEntry(", firstCharToUpper(memberModel.getC2jName())));
200 |
201 | sb.append(formatPrimitiveValue(mapModel.getKeyType(), field.getKey()));
202 | sb.append(", ");
203 |
204 | if (mapModel.getValueModel() == null) {
205 | sb.append(formatPrimitiveValue(mapModel.getValueType(), curNode.asText()));
206 | } else {
207 | getAssignmentValue(sb, curNode, mapModel.getValueModel());
208 | }
209 |
210 | sb.append(")");
211 | }
212 | } else {
213 | sb.append(String.format("new %s()", memberModel.getC2jShape()));
214 |
215 | Iterator> iter = node.fields();
216 | ShapeModel memberShape = model.getShapes().get(memberModel.getC2jShape());
217 |
218 | while (iter.hasNext()) {
219 | Entry field = iter.next();
220 | MemberModel fieldMemberModel = memberShape.getMemberByC2jName(field.getKey());
221 |
222 | if (fieldMemberModel.isMap()) {
223 | getAssignmentValue(sb, field.getValue(), fieldMemberModel);
224 | } else {
225 | sb.append(String.format(".with%s(", firstCharToUpper(field.getKey())));
226 | getAssignmentValue(sb, field.getValue(), fieldMemberModel);
227 | sb.append(")");
228 | }
229 | }
230 | }
231 | }
232 |
233 | private String formatPrimitiveValue(final String type, final String value) {
234 | if (type.equals("String")) {
235 | return String.format("\"%s\"", StringEscapeUtils.escapeJava(value));
236 | } else if (type.equals("Boolean")) {
237 | return value.toLowerCase();
238 | } else if (type.equals("Long")) {
239 | return value + "L";
240 | } else if (type.equals("Double")) {
241 | return value + "d";
242 | } else if (type.equals("Float")) {
243 | return value + "f";
244 | } else if (type.equals("Date")) {
245 | return String.format("new Date(\"%s\")", StringEscapeUtils.escapeJava(value));
246 | } else if (type.equals("ByteBuffer")) {
247 | return String.format("ByteBuffer.wrap(\"%s\".getBytes())", StringEscapeUtils.escapeJava(value));
248 | } else if (type.equals("InputStream")) {
249 | return String.format("new ByteArrayInputStream(\"%s\".getBytes())", StringEscapeUtils.escapeJava(value));
250 | } else {
251 | return value;
252 | }
253 | }
254 |
255 | private void writeLine(final String line) {
256 | sb.append(line.replace("\n", "") + "\n");
257 | }
258 |
259 | private String firstCharToUpper(final String str) {
260 | return str.substring(0, 1).toUpperCase() + str.substring(1);
261 | }
262 |
263 | }
264 |
--------------------------------------------------------------------------------
/aws-java-sdk-generated-samples/src/main/java/com/amazonaws/samples/exception/SampleGenerationException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License").
5 | * You may not use this file except in compliance with the License.
6 | * A copy of the License is located at
7 | *
8 | * http://aws.amazon.com/apache2.0
9 | *
10 | * or in the "license" file accompanying this file. This file is distributed
11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 | * express or implied. See the License for the specific language governing
13 | * permissions and limitations under the License.
14 | */
15 | package com.amazonaws.samples.exception;
16 |
17 | /**
18 | * Thrown to indicate that a problem occurred while generating a sample.
19 | */
20 | public class SampleGenerationException extends RuntimeException {
21 |
22 | private static final long serialVersionUID = 2312211727604383086L;
23 |
24 | /**
25 | * Constructs a SampleGenerationException with the specified error message.
26 | */
27 | public SampleGenerationException(final String message) {
28 | super(message);
29 | }
30 |
31 | /**
32 | * Constructs a SampleGenerationException with the specified error message
33 | * and cause.
34 | */
35 | public SampleGenerationException(final String message, final Throwable cause) {
36 | super(message, cause);
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/aws-java-sdk-generated-samples/src/main/java/com/amazonaws/samples/util/IntermediateModelRetriever.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License").
5 | * You may not use this file except in compliance with the License.
6 | * A copy of the License is located at
7 | *
8 | * http://aws.amazon.com/apache2.0
9 | *
10 | * or in the "license" file accompanying this file. This file is distributed
11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 | * express or implied. See the License for the specific language governing
13 | * permissions and limitations under the License.
14 | */
15 | package com.amazonaws.samples.util;
16 |
17 | import java.io.IOException;
18 | import java.io.InputStream;
19 | import java.net.JarURLConnection;
20 | import java.net.URL;
21 | import java.util.ArrayList;
22 | import java.util.Enumeration;
23 | import java.util.List;
24 | import java.util.jar.JarEntry;
25 | import java.util.jar.JarFile;
26 |
27 | import com.amazonaws.codegen.model.intermediate.IntermediateModel;
28 | import com.fasterxml.jackson.databind.DeserializationFeature;
29 | import com.fasterxml.jackson.databind.ObjectMapper;
30 |
31 | /**
32 | * Uses Jackson to materialize a serialized intermediate model.
33 | */
34 | public class IntermediateModelRetriever {
35 |
36 | /**
37 | * Returns a list of materialized intermediate models from SDK dependencies
38 | * on the classpath.
39 | *
40 | * @return list of materialized intermediate models
41 | * @throws IOException
42 | * if intermediate models cannot be retrieved
43 | */
44 | public static List getDependencyIntermediateModels()
45 | throws IOException {
46 | List intermediateModels = new ArrayList<>();
47 | Enumeration en = IntermediateModelRetriever.class.getClassLoader().getResources(
48 | "META-INF");
49 |
50 | while (en.hasMoreElements()) {
51 | URL url = en.nextElement();
52 | JarURLConnection urlcon = (JarURLConnection) (url.openConnection());
53 | try (JarFile jar = urlcon.getJarFile()) {
54 | Enumeration entries = jar.entries();
55 | while (entries.hasMoreElements()) {
56 | JarEntry entry = entries.nextElement();
57 | if (entry.getName().endsWith("-intermediate.json")) {
58 | intermediateModels.add(deserializeIntermediateModel(jar
59 | .getInputStream(entry)));
60 | }
61 | }
62 | }
63 | }
64 | return intermediateModels;
65 | }
66 |
67 | /**
68 | * Retrieves a serialized intermediate model.
69 | *
70 | * @param in
71 | * stream containing JSON serialized intermediate model
72 | * @return materialized intermediate model POJO
73 | * @throws IOException
74 | * if intermediate model cannot be read or materialized
75 | */
76 | public static IntermediateModel deserializeIntermediateModel(
77 | final InputStream in) throws IOException {
78 | ObjectMapper mapper = new ObjectMapper();
79 | mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
80 | return mapper.readValue(in, IntermediateModel.class);
81 | }
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/aws-java-sdk-handwritten-samples/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4.0.0
4 |
5 | com.amazonaws
6 | aws-java-sdk-samples-pom
7 | 1.1.4-SNAPSHOT
8 |
9 | com.amazonaws
10 | aws-java-sdk-handwritten-samples
11 | 1.1.4-SNAPSHOT
12 | aws-java-sdk-handwritten-samples
13 | http://maven.apache.org
14 |
15 | UTF-8
16 |
17 |
18 |
19 |
20 | com.amazonaws
21 | aws-java-sdk-sample-extractor
22 | 1.1.4-SNAPSHOT
23 |
24 | java
25 | /samples
26 |
27 |
28 |
29 | compile
30 |
31 | ExtractSamples
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 | junit
41 | junit
42 | 3.8.1
43 | test
44 |
45 |
46 | com.amazonaws
47 | aws-java-sdk-s3
48 | ${awsjavasdk.version}
49 | false
50 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/aws-java-sdk-handwritten-samples/src/main/java/com/amazonaws/samples/s3/S3Samples.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.samples.s3;
2 |
3 | import com.amazonaws.services.s3.AmazonS3ClientBuilder;
4 | import java.io.BufferedReader;
5 | import java.io.File;
6 | import java.io.FileOutputStream;
7 | import java.io.IOException;
8 | import java.io.InputStream;
9 | import java.io.InputStreamReader;
10 | import java.io.OutputStreamWriter;
11 | import java.io.Writer;
12 | import java.util.UUID;
13 |
14 | import com.amazonaws.AmazonClientException;
15 | import com.amazonaws.AmazonServiceException;
16 | import com.amazonaws.regions.Region;
17 | import com.amazonaws.regions.Regions;
18 | import com.amazonaws.services.s3.AmazonS3;
19 | import com.amazonaws.services.s3.AmazonS3Client;
20 | import com.amazonaws.services.s3.model.Bucket;
21 | import com.amazonaws.services.s3.model.GetObjectRequest;
22 | import com.amazonaws.services.s3.model.ListObjectsRequest;
23 | import com.amazonaws.services.s3.model.ObjectListing;
24 | import com.amazonaws.services.s3.model.PutObjectRequest;
25 | import com.amazonaws.services.s3.model.S3Object;
26 | import com.amazonaws.services.s3.model.S3ObjectSummary;
27 |
28 | /**
29 | * Handwritten S3 client samples
30 | */
31 | public class S3Samples {
32 |
33 | public static void main(String[] args) throws IOException {
34 | //BEGIN_SAMPLE:AmazonS3.CreateClient
35 | //TITLE:Create an S3 client
36 | //DESCRIPTION:Create your credentials file at ~/.aws/credentials (C:\Users\USER_NAME\.aws\credentials for Windows users)
37 | AmazonS3 s3 = AmazonS3ClientBuilder.standard().build();
38 | Region usWest2 = com.amazonaws.regions.Region.getRegion(Regions.US_WEST_2);
39 | s3.setRegion(usWest2);
40 | //END_SAMPLE
41 |
42 | String bucketName = "my-first-s3-bucket-" + UUID.randomUUID();
43 | String key = "MyObjectKey";
44 |
45 | System.out.println("===========================================");
46 | System.out.println("Getting Started with Amazon S3");
47 | System.out.println("===========================================\n");
48 |
49 | try {
50 | System.out.println("Creating bucket " + bucketName + "\n");
51 |
52 | //BEGIN_SAMPLE:AmazonS3.CreateBucket
53 | //TITLE:Create an S3 bucket
54 | //DESCRIPTION:Amazon S3 bucket names are globally unique, so once a bucket name has been taken by any user, you can't create another bucket with that same name.
55 | s3.createBucket(bucketName);
56 | //END_SAMPLE
57 |
58 |
59 | System.out.println("Listing buckets");
60 | //BEGIN_SAMPLE:AmazonS3.ListBuckets
61 | //TITLE:List buckets
62 | //DESCRIPTION:List the buckets in your account
63 | for (Bucket bucket : s3.listBuckets()) {
64 | System.out.println(" - " + bucket.getName());
65 | }
66 | System.out.println();
67 | //END_SAMPLE
68 |
69 |
70 | System.out.println("Uploading a new object to S3 from a file\n");
71 | //BEGIN_SAMPLE:AmazonS3.PutObject
72 | //TITLE:Upload an object to a bucket
73 | //DESCRIPTION:You can easily upload a file to S3, or upload directly an InputStream if you know the length of the data in the stream.
74 | s3.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));
75 | //END_SAMPLE
76 |
77 | System.out.println("Downloading an object");
78 | //BEGIN_SAMPLE:AmazonS3.GetObject
79 | //TITLE:Download an S3 object.
80 | //DESCRIPTION:When you download an object, you get all of the object's metadata and a stream from which to read the contents.
81 | S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
82 | //END_SAMPLE
83 | System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
84 | displayTextInputStream(object.getObjectContent());
85 |
86 |
87 | System.out.println("Listing objects");
88 |
89 | //BEGIN_SAMPLE:AmazonS3.ListObjects
90 | //TITLE:List S3 objects in bucket
91 | //DESCRIPTION:List objects in your bucket by prefix. Keep in mind that buckets with many objects might truncate their results when listing their objects, so be sure to check if the returned object listing is truncated.
92 | ObjectListing objectListing = s3.listObjects(new ListObjectsRequest()
93 | .withBucketName(bucketName)
94 | .withPrefix("My"));
95 | for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
96 | System.out.println(" - " + objectSummary.getKey() + " " +
97 | "(size = " + objectSummary.getSize() + ")");
98 | }
99 | System.out.println();
100 | //END_SAMPLE
101 |
102 |
103 | System.out.println("Deleting an object\n");
104 |
105 | //BEGIN_SAMPLE:AmazonS3.DeleteObject
106 | //TITLE:Delete an S3 object
107 | //DESCRIPTION:Unless versioning has been turned on for your bucket, there is no way to undelete an object, so use caution when deleting objects.
108 | s3.deleteObject(bucketName, key);
109 | //END_SAMPLE
110 |
111 |
112 | System.out.println("Deleting bucket " + bucketName + "\n");
113 |
114 | //BEGIN_SAMPLE:AmazonS3.DeleteBucket
115 | //TITLE:Delete an S3 bucket
116 | //DESCRIPTION:A bucket must be completely empty before it can be deleted, so remember to delete any objects from your buckets before you try to delete them.
117 | s3.deleteBucket(bucketName);
118 | //END_SAMPLE
119 | } catch (AmazonServiceException ase) {
120 | System.out.println("Caught an AmazonServiceException, which means your request made it "
121 | + "to Amazon S3, but was rejected with an error response for some reason.");
122 | System.out.println("Error Message: " + ase.getMessage());
123 | System.out.println("HTTP Status Code: " + ase.getStatusCode());
124 | System.out.println("AWS Error Code: " + ase.getErrorCode());
125 | System.out.println("Error Type: " + ase.getErrorType());
126 | System.out.println("Request ID: " + ase.getRequestId());
127 | } catch (AmazonClientException ace) {
128 | System.out.println("Caught an AmazonClientException, which means the client encountered "
129 | + "a serious internal problem while trying to communicate with S3, "
130 | + "such as not being able to access the network.");
131 | System.out.println("Error Message: " + ace.getMessage());
132 | }
133 | }
134 |
135 | /**
136 | * Creates a temporary file with text data to demonstrate uploading a file
137 | * to Amazon S3
138 | *
139 | * @return A newly created temporary file with text data.
140 | *
141 | * @throws IOException
142 | */
143 | private static File createSampleFile() throws IOException {
144 | File file = File.createTempFile("aws-java-sdk-", ".txt");
145 | file.deleteOnExit();
146 |
147 | Writer writer = new OutputStreamWriter(new FileOutputStream(file));
148 | writer.write("abcdefghijklmnopqrstuvwxyz\n");
149 | writer.write("01234567890112345678901234\n");
150 | writer.write("!@#$%^&*()-=[]{};':',.<>/?\n");
151 | writer.write("01234567890112345678901234\n");
152 | writer.write("abcdefghijklmnopqrstuvwxyz\n");
153 | writer.close();
154 |
155 | return file;
156 | }
157 |
158 | /**
159 | * Displays the contents of the specified input stream as text.
160 | *
161 | * @param input
162 | * The input stream to display as text.
163 | *
164 | * @throws IOException
165 | */
166 | private static void displayTextInputStream(InputStream input) throws IOException {
167 | BufferedReader reader = new BufferedReader(new InputStreamReader(input));
168 | while (true) {
169 | String line = reader.readLine();
170 | if (line == null) break;
171 |
172 | System.out.println(" " + line);
173 | }
174 | System.out.println();
175 | }
176 |
177 | }
178 |
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4.0.0
4 |
5 | com.amazonaws
6 | aws-java-sdk-samples-pom
7 | 1.1.4-SNAPSHOT
8 |
9 | com.amazonaws
10 | aws-java-sdk-sample-extractor
11 | 1.1.4-SNAPSHOT
12 | maven-plugin
13 | aws-java-sdk-sample-extractor
14 | http://maven.apache.org
15 |
16 | UTF-8
17 |
18 |
19 |
20 | junit
21 | junit
22 | 4.12
23 | test
24 |
25 |
26 | org.apache.maven
27 | maven-plugin-api
28 | 3.0
29 |
30 |
31 | org.apache.maven.plugin-tools
32 | maven-plugin-annotations
33 | 3.4
34 | provided
35 |
36 |
37 | org.hamcrest
38 | hamcrest-library
39 | 1.3
40 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/main/java/com/amazonaws/codesamples/CodeSample.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License").
5 | * You may not use this file except in compliance with the License.
6 | * A copy of the License is located at
7 | *
8 | * http://aws.amazon.com/apache2.0
9 | *
10 | * or in the "license" file accompanying this file. This file is distributed
11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 | * express or implied. See the License for the specific language governing
13 | * permissions and limitations under the License.
14 | */
15 | package com.amazonaws.codesamples;
16 |
17 | import java.util.ArrayList;
18 | import java.util.List;
19 |
20 | import com.amazonaws.util.ParsingUtils;
21 |
22 | /**
23 | * Represents an individual code sample.
24 | */
25 | public class CodeSample {
26 |
27 | private final String id;
28 | private final String serviceName;
29 |
30 | private String title;
31 | private String description;
32 | private List codeLines;
33 |
34 | /**
35 | * Ctor.
36 | *
37 | * @param sampleId
38 | * unique identifier for code sample
39 | * @param serviceName
40 | * service sample is associated with
41 | */
42 | public CodeSample(final String sampleId, final String serviceName) {
43 | if (sampleId == null || sampleId.isEmpty()) {
44 | throw new IllegalArgumentException("Sample ID must be provided!");
45 | }
46 |
47 | if (serviceName == null || serviceName.isEmpty()) {
48 | throw new IllegalArgumentException("Service name must be provided!");
49 | }
50 |
51 | this.id = sampleId;
52 | this.serviceName = serviceName;
53 | this.codeLines = new ArrayList();
54 | }
55 |
56 | /**
57 | * Returns the ID of this sample.
58 | *
59 | * @return sample ID
60 | */
61 | public String getId() {
62 | return id;
63 | }
64 |
65 | /**
66 | * Returns the name of the service this sample was written for.
67 | *
68 | * @return service name
69 | */
70 | public String getServiceName() {
71 | return serviceName;
72 | }
73 |
74 | /**
75 | * Returns the title of this sample.
76 | *
77 | * @return sample title
78 | */
79 | public String getTitle() {
80 | return title;
81 | }
82 |
83 | /**
84 | * Returns the description for this sample, or null if none was provided.
85 | *
86 | * @return description if provided
87 | */
88 | public String getDescription() {
89 | return description;
90 | }
91 |
92 | /**
93 | * Returns source code for this Sample. Code is formatted and shifted to
94 | * avoid extraneous leading whitespace.
95 | *
96 | * @return formatted sample code
97 | */
98 | public String getFormattedCode() {
99 | int offset = ParsingUtils.getMinWhitespace(codeLines);
100 |
101 | return ParsingUtils.formatSampleText(codeLines, offset);
102 | }
103 |
104 | /**
105 | * Set the title for this sample.
106 | *
107 | * @param title
108 | * sample title
109 | */
110 | public void setTitle(final String title) {
111 | this.title = title;
112 | }
113 |
114 | /**
115 | * Set the description for this sample.
116 | *
117 | * @param description
118 | * sample description
119 | */
120 | public void setDescription(final String description) {
121 | this.description = description;
122 | }
123 |
124 | /**
125 | * Append a line of code to this sample.
126 | *
127 | * @param line
128 | * line of code
129 | */
130 | public void appendLine(final String line) {
131 | codeLines.add(line);
132 | }
133 |
134 | }
135 |
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/main/java/com/amazonaws/codesamples/SampleCodeExtractor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License").
5 | * You may not use this file except in compliance with the License.
6 | * A copy of the License is located at
7 | *
8 | * http://aws.amazon.com/apache2.0
9 | *
10 | * or in the "license" file accompanying this file. This file is distributed
11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 | * express or implied. See the License for the specific language governing
13 | * permissions and limitations under the License.
14 | */
15 | package com.amazonaws.codesamples;
16 |
17 | import java.io.File;
18 | import java.util.List;
19 |
20 | import org.apache.maven.plugin.AbstractMojo;
21 | import org.apache.maven.plugin.MojoExecutionException;
22 | import org.apache.maven.plugin.MojoFailureException;
23 | import org.apache.maven.plugins.annotations.Mojo;
24 | import org.apache.maven.plugins.annotations.Parameter;
25 |
26 | /**
27 | * Maven mojo that is responsible for scanning input source files and extracting
28 | * sections marked up as code samples. Output are generated XML files containing
29 | * the samples.
30 | */
31 | @Mojo(name = "ExtractSamples")
32 | public class SampleCodeExtractor extends AbstractMojo {
33 |
34 | @Parameter(property = "sampleSubDir")
35 | private String sampleSubDir;
36 |
37 | @Parameter(property = "sourceExtension")
38 | private String sourceExtension;
39 |
40 | @Parameter(defaultValue = "${project.build.sourceDirectory}")
41 | private String projectSourceDir;
42 |
43 | @Parameter(defaultValue = "${project.build.outputDirectory}")
44 | private String projectOutputDir;
45 |
46 | /**
47 | * Plugin entry point.
48 | */
49 | public void execute() throws MojoExecutionException, MojoFailureException {
50 | if (projectSourceDir == null || projectSourceDir.isEmpty()) {
51 | throw new MojoFailureException(
52 | "Unable to determine project source dir!");
53 | }
54 |
55 | if (projectOutputDir == null || projectOutputDir.isEmpty()) {
56 | throw new MojoFailureException(
57 | "Unable to determine project output dir!");
58 | }
59 |
60 | if (sampleSubDir == null || sampleSubDir.isEmpty()) {
61 | throw new MojoFailureException(
62 | "Sample sub directory was not provided!");
63 | }
64 | File[] sourceFiles = new File(projectSourceDir).listFiles();
65 | String samplesOutputDir = projectOutputDir + sampleSubDir;
66 |
67 | try {
68 | List samples = SamplesParser.getSamples(sourceFiles,
69 | sourceExtension);
70 | SamplesWriter.writeSamples(samples, samplesOutputDir);
71 | } catch (Exception e) {
72 | throw new MojoFailureException("Failed to extract samples", e);
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/main/java/com/amazonaws/codesamples/SamplesParser.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License").
5 | * You may not use this file except in compliance with the License.
6 | * A copy of the License is located at
7 | *
8 | * http://aws.amazon.com/apache2.0
9 | *
10 | * or in the "license" file accompanying this file. This file is distributed
11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 | * express or implied. See the License for the specific language governing
13 | * permissions and limitations under the License.
14 | */
15 | package com.amazonaws.codesamples;
16 |
17 | import java.io.File;
18 | import java.io.FileReader;
19 | import java.io.LineNumberReader;
20 | import java.util.ArrayList;
21 | import java.util.List;
22 | import java.util.regex.Matcher;
23 | import java.util.regex.Pattern;
24 |
25 | import com.amazonaws.codesamples.exception.SampleParsingException;
26 | import com.amazonaws.util.ParsingUtils;
27 |
28 | /**
29 | * Parser that parses out marked up samples from source code files. Samples are
30 | * retained in-memory and returned in a List for additional processing or
31 | * writing.
32 | */
33 | public class SamplesParser {
34 |
35 | /*
36 | * Matching patterns for parsing source files.
37 | */
38 | private static final Pattern BEGIN_SAMPLE_PATTERN = Pattern
39 | .compile("//\\s*BEGIN_SAMPLE:([^.]+)\\.([^.]+)$");
40 | private static final Pattern END_SAMPLE_PATTERN = Pattern
41 | .compile("//\\s*END_SAMPLE");
42 |
43 | private static final Pattern BEGIN_HIDDEN_PATTERN = Pattern
44 | .compile("//\\s*BEGIN_HIDDEN");
45 | private static final Pattern END_HIDDEN_PATTERN = Pattern
46 | .compile("//\\s*END_HIDDEN");
47 |
48 | private static final Pattern TITLE_PATTERN = Pattern
49 | .compile("//\\s*TITLE:(.*)$");
50 | private static final Pattern DESCRIPTION_PATTERN = Pattern
51 | .compile("//\\s*DESCRIPTION:(.*)$");
52 |
53 | /**
54 | * Returns a list of samples parsed from input files.
55 | *
56 | * @param files
57 | * input files
58 | * @param targetExtension
59 | * extension of files to parse
60 | * @return list of samples
61 | * @throws Exception
62 | * if an error occurs while getting samples
63 | */
64 | public static List getSamples(final File[] files,
65 | final String targetExtension) throws Exception {
66 | if (files == null) {
67 | throw new SampleParsingException(
68 | "Must provide a non-null set of files to parse");
69 | }
70 |
71 | List samples = new ArrayList();
72 | parseFiles(files, targetExtension, samples);
73 | return samples;
74 | }
75 |
76 | /**
77 | * Returns a list of samples parsed from a file.
78 | *
79 | * @param file
80 | * input file
81 | * @return list of samples
82 | * @throws Exception
83 | * if an error occurs while getting samples
84 | */
85 | public static List getSamples(final File file)
86 | throws Exception {
87 | if (file == null || !file.exists()) {
88 | throw new SampleParsingException(
89 | "Must provide a valid existing file to parse");
90 | }
91 |
92 | List samples = new ArrayList();
93 | parseFile(file, samples);
94 | return samples;
95 | }
96 |
97 | private static void parseFiles(final File[] files,
98 | final String targetExtension, final List samples)
99 | throws Exception {
100 | for (File file : files) {
101 | if (file.isDirectory()) {
102 | parseFiles(file.listFiles(), targetExtension, samples);
103 | } else {
104 | if (ParsingUtils.fileMatchesExtension(file, targetExtension)) {
105 | parseFile(file, samples);
106 | }
107 | }
108 | }
109 | }
110 |
111 | private static void parseFile(final File sourceFile,
112 | List samples) throws Exception {
113 | String line = null;
114 |
115 | CodeSample curSample = null;
116 | boolean inSample = false;
117 | boolean hidden = false;
118 |
119 | LineNumberReader reader = null;
120 | try {
121 | reader = new LineNumberReader(new FileReader(sourceFile));
122 |
123 | while ((line = reader.readLine()) != null) {
124 | String trimmedLine = line.trim();
125 | Matcher beginSampleMatcher = BEGIN_SAMPLE_PATTERN
126 | .matcher(trimmedLine);
127 | Matcher endSampleMatcher = END_SAMPLE_PATTERN
128 | .matcher(trimmedLine);
129 |
130 | Matcher beginHiddenMatcher = BEGIN_HIDDEN_PATTERN
131 | .matcher(trimmedLine);
132 | Matcher endHiddenMatcher = END_HIDDEN_PATTERN
133 | .matcher(trimmedLine);
134 |
135 | Matcher titleMatcher = TITLE_PATTERN
136 | .matcher(trimmedLine);
137 | Matcher descriptionMatcher = DESCRIPTION_PATTERN
138 | .matcher(trimmedLine);
139 |
140 | if (beginSampleMatcher.find()) {
141 | if (inSample) {
142 | throw new SampleParsingException(
143 | "Found a BEGIN_SAMPLE tag while already within a sample block",
144 | sourceFile, reader.getLineNumber());
145 | }
146 | inSample = true;
147 | String serviceName = beginSampleMatcher.group(1);
148 | String sampleId = beginSampleMatcher.group(2);
149 | curSample = new CodeSample(sampleId, serviceName);
150 | } else if (endSampleMatcher.find()) {
151 | if (inSample) {
152 | if (hidden) {
153 | throw new SampleParsingException(
154 | "Sample was still hidden when END_SAMPLE tag was encountered",
155 | sourceFile, reader.getLineNumber());
156 | }
157 |
158 | String sampleId = curSample.getId();
159 |
160 | boolean valid = !ParsingUtils.checkAndLogIfNoContent(sampleId, "title", curSample.getTitle())
161 | && !ParsingUtils.checkAndLogIfNoContent(sampleId, "description", curSample.getDescription())
162 | && !ParsingUtils.checkAndLogIfNoContent(sampleId, "content", curSample.getFormattedCode());
163 | if (valid) {
164 | samples.add(curSample);
165 | } else {
166 | System.err.println(String.format("Omitted sample '%s' for service '%s'"
167 | + " because it does not contain all required fields",
168 | sampleId, curSample.getServiceName()));
169 | }
170 | inSample = false;
171 | } else {
172 | throw new SampleParsingException(
173 | "Found a END_SAMPLE tag while not within a sample block",
174 | sourceFile, reader.getLineNumber());
175 | }
176 | } else if (beginHiddenMatcher.find()) {
177 | if (hidden == true) {
178 | throw new SampleParsingException(
179 | "Found a BEGIN_HIDDEN tag while already within a hidden block",
180 | sourceFile, reader.getLineNumber());
181 | }
182 |
183 | hidden = true;
184 | } else if (endHiddenMatcher.find()) {
185 | if (hidden == false) {
186 | throw new SampleParsingException(
187 | "Found a END_HIDDEN tag while not within a hidden block",
188 | sourceFile, reader.getLineNumber());
189 | }
190 |
191 | hidden = false;
192 | } else if (titleMatcher.find()) {
193 | if (!inSample) {
194 | throw new SampleParsingException(
195 | "Found a TITLE tag while not within a sample block",
196 | sourceFile, reader.getLineNumber());
197 | }
198 | curSample.setTitle(titleMatcher.group(1));
199 | } else if (descriptionMatcher.find()) {
200 | if (!inSample) {
201 | throw new SampleParsingException(
202 | "Found a DESCRIPTION tag while not within a sample block",
203 | sourceFile, reader.getLineNumber());
204 | }
205 | curSample.setDescription(descriptionMatcher.group(1));
206 | } else if (inSample && !hidden) {
207 | curSample.appendLine(line);
208 | }
209 | }
210 |
211 | if (inSample) {
212 | throw new SampleParsingException(
213 | "Hit EOF with sample still open: "
214 | + curSample.getId(), sourceFile,
215 | reader.getLineNumber());
216 | }
217 | } finally {
218 | if (reader != null) {
219 | reader.close();
220 | }
221 | }
222 | }
223 | }
224 |
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/main/java/com/amazonaws/codesamples/SamplesWriter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License").
5 | * You may not use this file except in compliance with the License.
6 | * A copy of the License is located at
7 | *
8 | * http://aws.amazon.com/apache2.0
9 | *
10 | * or in the "license" file accompanying this file. This file is distributed
11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 | * express or implied. See the License for the specific language governing
13 | * permissions and limitations under the License.
14 | */
15 | package com.amazonaws.codesamples;
16 |
17 | import java.io.File;
18 | import java.util.HashMap;
19 | import java.util.List;
20 | import java.util.Map;
21 | import java.util.Map.Entry;
22 |
23 | import javax.xml.parsers.DocumentBuilder;
24 | import javax.xml.parsers.DocumentBuilderFactory;
25 | import javax.xml.parsers.ParserConfigurationException;
26 | import javax.xml.transform.OutputKeys;
27 | import javax.xml.transform.Transformer;
28 | import javax.xml.transform.TransformerFactory;
29 | import javax.xml.transform.dom.DOMSource;
30 | import javax.xml.transform.stream.StreamResult;
31 |
32 | import org.w3c.dom.Document;
33 | import org.w3c.dom.Element;
34 |
35 | /**
36 | * Sample writer which takes samples and writes them out to XML files.
37 | */
38 | public class SamplesWriter {
39 |
40 | /**
41 | * Output XML constants.
42 | */
43 | static final String ROOT_ELEMENT = "codeSamples";
44 | static final String SAMPLE_ELEMENT = "sample";
45 | static final String CONTENT_ELEMENT = "content";
46 | static final String ID_ATTRIBUTE = "id";
47 | static final String TITLE_ATTRIBUTE = "title";
48 | static final String DESC_ATTRIBUTE = "description";
49 |
50 | /**
51 | * Writes samples. Samples are split up by service, injected into a service
52 | * specific DOM, and finally written out to XML files split up by service.
53 | * Sample DOMs are held in memory until being written to file.
54 | *
55 | * @param samples
56 | * list of samples to write
57 | * @param outputDir
58 | * sample output directory
59 | * @throws Exception
60 | * if an error occurs while writing samples
61 | */
62 | public static void writeSamples(final List samples,
63 | final String outputDir) throws Exception {
64 | Map serviceDocMap = generateSampleDocuments(samples);
65 |
66 | new File(outputDir).mkdirs();
67 |
68 | TransformerFactory transformerFactory = TransformerFactory
69 | .newInstance();
70 | Transformer transformer = transformerFactory.newTransformer();
71 | transformer.setOutputProperty(OutputKeys.INDENT, "yes");
72 |
73 | for (Entry entry : serviceDocMap.entrySet()) {
74 | DOMSource source = new DOMSource(entry.getValue());
75 | File outputFile = new File(String.format("%s/%s.xml", outputDir,
76 | entry.getKey()));
77 | StreamResult result = new StreamResult(outputFile);
78 | transformer.transform(source, result);
79 | }
80 | }
81 |
82 | static Map generateSampleDocuments(
83 | final List samples) throws Exception {
84 | Map serviceDocMap = new HashMap();
85 |
86 | for (CodeSample sample : samples) {
87 | String sampleServiceName = sample.getServiceName();
88 |
89 | if (!serviceDocMap.containsKey(sampleServiceName)) {
90 | serviceDocMap.put(sampleServiceName, createSampleDoc());
91 | }
92 | Document doc = serviceDocMap.get(sampleServiceName);
93 | appendSampleToDoc(sample, doc);
94 | }
95 |
96 | return serviceDocMap;
97 | }
98 |
99 | private static Document createSampleDoc()
100 | throws ParserConfigurationException {
101 | DocumentBuilderFactory docFactory = DocumentBuilderFactory
102 | .newInstance();
103 | DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
104 |
105 | Document doc = docBuilder.newDocument();
106 | Element rootElement = doc.createElement(ROOT_ELEMENT);
107 | doc.appendChild(rootElement);
108 |
109 | return doc;
110 | }
111 |
112 | private static void appendSampleToDoc(final CodeSample sample,
113 | final Document doc) {
114 | Element sampleElement = doc.createElement(SAMPLE_ELEMENT);
115 | sampleElement.setAttribute(DESC_ATTRIBUTE, sample.getDescription());
116 | sampleElement.setAttribute(TITLE_ATTRIBUTE, sample.getTitle());
117 | sampleElement.setAttribute(ID_ATTRIBUTE, sample.getId());
118 |
119 | Element codeElement = doc.createElement(CONTENT_ELEMENT);
120 | codeElement.appendChild(doc.createTextNode(sample.getFormattedCode()));
121 | sampleElement.appendChild(codeElement);
122 |
123 | Element rootElement = (Element) doc.getElementsByTagName(ROOT_ELEMENT)
124 | .item(0);
125 | rootElement.appendChild(sampleElement);
126 | }
127 | }
128 |
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/main/java/com/amazonaws/codesamples/exception/SampleParsingException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License").
5 | * You may not use this file except in compliance with the License.
6 | * A copy of the License is located at
7 | *
8 | * http://aws.amazon.com/apache2.0
9 | *
10 | * or in the "license" file accompanying this file. This file is distributed
11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 | * express or implied. See the License for the specific language governing
13 | * permissions and limitations under the License.
14 | */
15 | package com.amazonaws.codesamples.exception;
16 |
17 | import java.io.File;
18 |
19 | /**
20 | * Exception thrown when an error occurs while parsing a source file for code
21 | * samples.
22 | */
23 | public class SampleParsingException extends RuntimeException {
24 |
25 | private static final long serialVersionUID = 1474663474079249583L;
26 |
27 | /**
28 | * Constructs a SampleParsingException with a specified message and
29 | * referencing a file and line number being processed when the error
30 | * occurred.
31 | *
32 | * @param message
33 | * exception detail message
34 | * @param file
35 | * file being parsed when exception occurred
36 | * @param lineNum
37 | * line being parsed when exeception occurred
38 | */
39 | public SampleParsingException(final String message, final File file,
40 | final int lineNum) {
41 | this(message
42 | + String.format(" (File: %s, Line: %s)", file.getName(),
43 | lineNum));
44 | }
45 |
46 | /**
47 | * Constructs a SampleParsingException with a specified message.
48 | *
49 | * @param message
50 | * exception detail message
51 | */
52 | public SampleParsingException(final String message) {
53 | super(message);
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/main/java/com/amazonaws/util/ParsingUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License").
5 | * You may not use this file except in compliance with the License.
6 | * A copy of the License is located at
7 | *
8 | * http://aws.amazon.com/apache2.0
9 | *
10 | * or in the "license" file accompanying this file. This file is distributed
11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 | * express or implied. See the License for the specific language governing
13 | * permissions and limitations under the License.
14 | */
15 | package com.amazonaws.util;
16 |
17 | import java.io.File;
18 | import java.util.List;
19 |
20 | import com.amazonaws.codesamples.exception.SampleParsingException;
21 |
22 | /**
23 | * Utility methods to assist in sample parsing.
24 | */
25 | public final class ParsingUtils {
26 |
27 | /**
28 | * Determine if a given file matches the target extension.
29 | *
30 | * @param file
31 | * file to check
32 | * @param targetExtension
33 | * target extension
34 | * @return true if file has target extension
35 | */
36 | public static boolean fileMatchesExtension(final File file,
37 | final String targetExtension) {
38 | String fileName = file.getName();
39 | int i = fileName.lastIndexOf(".");
40 | if (i > 0) {
41 | String actualExtension = fileName.substring(i + 1);
42 | if (targetExtension.equals(actualExtension)) {
43 | return true;
44 | }
45 | }
46 | return false;
47 | }
48 |
49 | /**
50 | * Formats a section of sample text by removing leading whitespace
51 | * characters up to a given maximum and by flattening lines into a single
52 | * string.
53 | *
54 | * @param lines
55 | * list where each element represents an individual line of
56 | * sample text
57 | * @param maxTrim
58 | * maximum number of leading whitespace characters to trim from
59 | * each line
60 | * @return formatted sample text string
61 | */
62 | public static String formatSampleText(final List lines,
63 | final int maxTrim) {
64 | StringBuilder sb = new StringBuilder();
65 | for (int i = 0; i < lines.size(); i++) {
66 | sb.append(trimLeadingWhitespace(lines.get(i), maxTrim));
67 | if (i + 1 < lines.size()) {
68 | sb.append("\n");
69 | }
70 | }
71 | return sb.toString();
72 | }
73 |
74 | /**
75 | * Gets the minimum amount of leading whitespace in a text block.
76 | *
77 | * @param lines
78 | * list where each element represents an individual line of
79 | * sample text
80 | *
81 | * @return minimum amount of leading whitespace
82 | */
83 | public static int getMinWhitespace(final List lines) {
84 | int minWhitespace = 0;
85 | for (String line : lines) {
86 | int lineLeadingWhitespace = getLeadingWhitespace(line);
87 | if (lineLeadingWhitespace < minWhitespace || minWhitespace == 0) {
88 | minWhitespace = lineLeadingWhitespace;
89 | }
90 | }
91 | return minWhitespace;
92 | }
93 |
94 | /**
95 | * Returns the number of leading whitespace characters in a given string.
96 | *
97 | * @param str
98 | * string to check
99 | * @return number of leading whitespace characters
100 | */
101 | public static int getLeadingWhitespace(final String str) {
102 | int pos = 0;
103 | while ((pos < str.length()) && (str.charAt(pos) == ' ')) {
104 | pos++;
105 | }
106 | return pos;
107 | }
108 |
109 | /**
110 | * Trims up to a certain number of leading whitespace characters from a
111 | * string.
112 | *
113 | * @param str
114 | * string to process
115 | * @param max
116 | * maximum number of whitespace characters to trim
117 | * @return trimmed String
118 | */
119 | public static String trimLeadingWhitespace(final String str, final int max) {
120 | int pos = Math.min(getLeadingWhitespace(str), max);
121 | if (pos > 0) {
122 | return str.substring(pos);
123 | } else {
124 | return str;
125 | }
126 | }
127 |
128 | /**
129 | * Asserts that a specified field contains a non-null, non-empty value.
130 | *
131 | * @param field
132 | * name of field
133 | * @param value
134 | * value from field
135 | * @return original value of field, if valid
136 | */
137 | public static String assertFieldHasContent(final String field,
138 | final String value) {
139 | if (!hasContent(value)) {
140 | throw new SampleParsingException(
141 | String.format("Required field %s was not provided!",
142 | field));
143 | }
144 | return value;
145 | }
146 |
147 | /**
148 | * Checks if the specified sample property value is null or empty, and logs
149 | * it as missing if it is.
150 | *
151 | * @param sampleId
152 | * The sampleId
153 | * @param field
154 | * name of field
155 | * @param value
156 | * value of field
157 | * @return True if the value was empty, false otherwise.
158 | */
159 | public static boolean checkAndLogIfNoContent(String sampleId, String field, String value) {
160 | if (!hasContent(value)) {
161 | System.err.println(String.format("Warning: Sample '%s' does not provide field '%s'",
162 | sampleId, field));
163 | return true;
164 | }
165 | return false;
166 | }
167 |
168 | /**
169 | * True if the given string is not null and not empty.
170 | *
171 | * @param str
172 | * The string.
173 | * @return True if the string is not null and not empty.
174 | */
175 | private static boolean hasContent(String str) {
176 | return str != null && !str.isEmpty();
177 | }
178 | }
179 |
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/test/java/com/amazonaws/codesamples/CodeSampleTest.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.codesamples;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import org.junit.Test;
6 |
7 | public class CodeSampleTest {
8 |
9 | @Test(expected = IllegalArgumentException.class)
10 | public void codeSampleNullName() {
11 | new CodeSample(null, "Service");
12 | }
13 |
14 | @Test(expected = IllegalArgumentException.class)
15 | public void codeSampleEmptyName() {
16 | new CodeSample("", "Service");
17 | }
18 |
19 | @Test(expected = IllegalArgumentException.class)
20 | public void codeSampleNullService() {
21 | new CodeSample("Name", null);
22 | }
23 |
24 | @Test(expected = IllegalArgumentException.class)
25 | public void codeSampleEmptyService() {
26 | new CodeSample("Name", "");
27 | }
28 |
29 | @Test
30 | public void getId() {
31 | CodeSample sample = new CodeSample("ID", "Service");
32 | assertEquals(sample.getId(), "ID");
33 | }
34 |
35 | @Test
36 | public void getService() {
37 | CodeSample sample = new CodeSample("ID", "Service");
38 | assertEquals(sample.getServiceName(), "Service");
39 | }
40 |
41 | @Test
42 | public void setGetTitle() {
43 | CodeSample sample = new CodeSample("ID", "Service");
44 | sample.setTitle("SampleTitle");
45 | assertEquals(sample.getTitle(), "SampleTitle");
46 | }
47 |
48 | @Test
49 | public void setGetDescription() {
50 | CodeSample sample = new CodeSample("ID", "Service");
51 | sample.setDescription("Description");
52 | assertEquals(sample.getDescription(), "Description");
53 | }
54 |
55 | @Test
56 | public void setGetSampleContent() {
57 | CodeSample sample = new CodeSample("ID", "Service");
58 | sample.setTitle("Title");
59 | sample.setDescription("Description");
60 |
61 | sample.appendLine("One");
62 | sample.appendLine("Two");
63 | sample.appendLine("Three");
64 |
65 | assertEquals(sample.getFormattedCode(), "One\nTwo\nThree");
66 | }
67 |
68 | }
69 |
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/test/java/com/amazonaws/codesamples/SampleExtractorTestUtils.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.codesamples;
2 |
3 | import java.io.File;
4 | import java.net.URISyntaxException;
5 | import java.net.URL;
6 |
7 | public final class SampleExtractorTestUtils {
8 |
9 | public static File getSampleFile(final String sampleFile)
10 | throws URISyntaxException {
11 | URL url = SampleExtractorTestUtils.class.getResource("/testsamples/"
12 | + sampleFile);
13 | return new File(url.toURI());
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/test/java/com/amazonaws/codesamples/SampleWriterTest.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.codesamples;
2 |
3 | import static org.junit.Assert.assertEquals;
4 | import static org.junit.Assert.assertNotNull;
5 | import static org.hamcrest.Matchers.hasKey;
6 | import static org.hamcrest.MatcherAssert.assertThat;
7 | import static com.amazonaws.codesamples.SampleExtractorTestUtils.getSampleFile;
8 |
9 | import java.io.File;
10 | import java.util.List;
11 | import java.util.Map;
12 |
13 | import org.junit.Test;
14 | import org.w3c.dom.Document;
15 | import org.w3c.dom.Element;
16 | import org.w3c.dom.NamedNodeMap;
17 | import org.w3c.dom.Node;
18 | import org.w3c.dom.NodeList;
19 |
20 | import static com.amazonaws.codesamples.SamplesWriter.ROOT_ELEMENT;
21 | import static com.amazonaws.codesamples.SamplesWriter.SAMPLE_ELEMENT;
22 | import static com.amazonaws.codesamples.SamplesWriter.ID_ATTRIBUTE;
23 | import static com.amazonaws.codesamples.SamplesWriter.TITLE_ATTRIBUTE;
24 | import static com.amazonaws.codesamples.SamplesWriter.DESC_ATTRIBUTE;
25 | import static com.amazonaws.codesamples.SamplesWriter.CONTENT_ELEMENT;
26 |
27 | public class SampleWriterTest {
28 |
29 | @Test
30 | public void generateAndRetrieveSamplesFunctionalTest() throws Exception {
31 | File sampleFile = getSampleFile("TestSamples.java");
32 | List samples = SamplesParser.getSamples(sampleFile);
33 |
34 | Map sampleDocuments = SamplesWriter
35 | .generateSampleDocuments(samples);
36 | assertNotNull(sampleDocuments);
37 | assertEquals(sampleDocuments.size(), 3);
38 |
39 | assertThat(sampleDocuments, hasKey("Test1"));
40 | assertThat(sampleDocuments, hasKey("Test2"));
41 | assertThat(sampleDocuments, hasKey("Test3"));
42 |
43 | Document sampleDocument = sampleDocuments.get("Test1");
44 | Element rootElement = sampleDocument.getDocumentElement();
45 | assertNotNull(rootElement);
46 | assertEquals(rootElement.getNodeName(), ROOT_ELEMENT);
47 |
48 | NodeList sampleNodes = rootElement.getChildNodes();
49 | assertNotNull(sampleNodes);
50 | assertEquals(sampleNodes.getLength(), 1);
51 |
52 | Node sampleNode = sampleNodes.item(0);
53 | assertEquals(sampleNode.getNodeName(), SAMPLE_ELEMENT);
54 | NamedNodeMap map = sampleNode.getAttributes();
55 | assertNotNull(map);
56 |
57 | Node idAttr = map.getNamedItem(ID_ATTRIBUTE);
58 | assertEquals(idAttr.getNodeValue(), "Sample1");
59 |
60 | Node titleAttr = map.getNamedItem(TITLE_ATTRIBUTE);
61 | assertEquals(titleAttr.getNodeValue(), "First sample");
62 |
63 | Node descAttr = map.getNamedItem(DESC_ATTRIBUTE);
64 | assertEquals(descAttr.getNodeValue(), "The first sample");
65 |
66 | NodeList sampleChildNodes = sampleNode.getChildNodes();
67 | assertNotNull(sampleChildNodes);
68 | assertEquals(sampleChildNodes.getLength(), 1);
69 |
70 | Node contentNode = sampleChildNodes.item(0);
71 | assertEquals(contentNode.getNodeName(), CONTENT_ELEMENT);
72 | assertEquals(contentNode.getTextContent(), "String foo = \"foo!\";");
73 | }
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/test/java/com/amazonaws/codesamples/SamplesParserTest.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.codesamples;
2 |
3 | import static org.junit.Assert.assertEquals;
4 | import static org.junit.Assert.assertTrue;
5 | import static com.amazonaws.codesamples.SampleExtractorTestUtils.getSampleFile;
6 |
7 | import java.io.File;
8 | import java.util.List;
9 |
10 | import org.junit.Test;
11 |
12 | import com.amazonaws.codesamples.exception.SampleParsingException;
13 |
14 | public class SamplesParserTest {
15 |
16 | @Test
17 | public void parseSamples() throws Exception {
18 | File sampleFile = getSampleFile("TestSamples.java");
19 | List samples = SamplesParser.getSamples(sampleFile);
20 | assertEquals(samples.size(), 3);
21 |
22 | CodeSample firstSample = samples.get(0);
23 | assertEquals(firstSample.getId(), "Sample1");
24 | assertEquals(firstSample.getServiceName(), "Test1");
25 | assertEquals(firstSample.getTitle(), "First sample");
26 | assertEquals(firstSample.getDescription(), "The first sample");
27 | assertEquals(firstSample.getFormattedCode(), "String foo = \"foo!\";");
28 |
29 | CodeSample secondSample = samples.get(1);
30 | assertEquals(secondSample.getId(), "Sample2");
31 | assertEquals(secondSample.getServiceName(), "Test2");
32 | assertEquals(secondSample.getTitle(), "Second sample");
33 | assertEquals(secondSample.getDescription(), "The second sample");
34 | assertEquals(secondSample.getFormattedCode(),
35 | "String bar = \"bar!\";\nString baz = \"baz!\";");
36 |
37 | CodeSample thirdSample = samples.get(2);
38 | assertEquals(thirdSample.getId(), "Sample3");
39 | assertEquals(thirdSample.getServiceName(), "Test3");
40 | assertEquals(thirdSample.getTitle(), "Third sample");
41 | assertEquals(thirdSample.getDescription(), "The third sample");
42 | assertEquals(thirdSample.getFormattedCode(),
43 | "String visible = \"this should be visible\";");
44 | }
45 |
46 | @Test
47 | public void fileNoSamples() throws Exception {
48 | File sampleFile = getSampleFile("EmptySamples.java");
49 | List samples = SamplesParser.getSamples(sampleFile);
50 | assertEquals(samples.size(), 0);
51 | }
52 |
53 | @Test(expected = SampleParsingException.class)
54 | public void sampleBadStartTag() throws Exception {
55 | File sampleFile = getSampleFile("BadStartTagSample.java");
56 | SamplesParser.getSamples(sampleFile);
57 | }
58 |
59 | @Test(expected = SampleParsingException.class)
60 | public void sampleBadEndTag() throws Exception {
61 | File sampleFile = getSampleFile("BadEndTagSample.java");
62 | SamplesParser.getSamples(sampleFile);
63 | }
64 |
65 | @Test(expected = SampleParsingException.class)
66 | public void sampleBadBeginHiddenTag() throws Exception {
67 | File sampleFile = getSampleFile("BadBeginHiddenTagSample.java");
68 | SamplesParser.getSamples(sampleFile);
69 | }
70 |
71 | @Test(expected = SampleParsingException.class)
72 | public void sampleBadEndHiddenTag() throws Exception {
73 | File sampleFile = getSampleFile("BadEndHiddenTagSample.java");
74 | SamplesParser.getSamples(sampleFile);
75 | }
76 |
77 | @Test(expected = SampleParsingException.class)
78 | public void sampleBadTitleTag() throws Exception {
79 | File sampleFile = getSampleFile("BadTitleTagSample.java");
80 | SamplesParser.getSamples(sampleFile);
81 | }
82 |
83 | @Test(expected = SampleParsingException.class)
84 | public void sampleBadDescriptionTag() throws Exception {
85 | File sampleFile = getSampleFile("BadDescriptionTagSample.java");
86 | SamplesParser.getSamples(sampleFile);
87 | }
88 |
89 | @Test(expected = SampleParsingException.class)
90 | public void unclosedSample() throws Exception {
91 | File sampleFile = getSampleFile("UnclosedSample.java");
92 | SamplesParser.getSamples(sampleFile);
93 | }
94 |
95 | @Test
96 | public void sampleNoDescription() throws Exception {
97 | File sampleFile = getSampleFile("NoDescriptionSample.java");
98 | assertTrue(SamplesParser.getSamples(sampleFile).isEmpty());
99 | }
100 |
101 | @Test
102 | public void sampleNoTitle() throws Exception {
103 | File sampleFile = getSampleFile("NoTitleSample.java");
104 | assertTrue(SamplesParser.getSamples(sampleFile).isEmpty());
105 | }
106 |
107 | @Test
108 | public void sampleNoContent() throws Exception {
109 | File sampleFile = getSampleFile("NoContentSample.java");
110 | assertTrue(SamplesParser.getSamples(sampleFile).isEmpty());
111 | }
112 |
113 | }
114 |
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/test/java/com/amazonaws/util/ParsingUtilsTest.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.util;
2 |
3 | import static org.junit.Assert.assertEquals;
4 | import static org.junit.Assert.assertFalse;
5 | import static org.junit.Assert.assertTrue;
6 | import static com.amazonaws.codesamples.SampleExtractorTestUtils.getSampleFile;
7 |
8 | import java.io.File;
9 | import java.util.ArrayList;
10 | import java.util.List;
11 |
12 | import org.junit.Test;
13 |
14 | public class ParsingUtilsTest {
15 |
16 | @Test
17 | public void fileMatchesExtension() throws Exception {
18 | File sampleFile = getSampleFile("EmptySamples.java");
19 | assertTrue(ParsingUtils.fileMatchesExtension(sampleFile, "java"));
20 | }
21 |
22 | @Test
23 | public void fileDoesNotMatchExtension() throws Exception {
24 | File sampleFile = getSampleFile("BadExtension.cpp");
25 | assertFalse(ParsingUtils.fileMatchesExtension(sampleFile, "java"));
26 | }
27 |
28 | @Test
29 | public void getLeadingWhitespace() {
30 | assertEquals(ParsingUtils.getLeadingWhitespace("ZERO"), 0);
31 | assertEquals(ParsingUtils.getLeadingWhitespace(" THREE"), 3);
32 | }
33 |
34 | @Test
35 | public void trimLeadingWhitespace() {
36 | String foo = " FOO";
37 | assertEquals(ParsingUtils.trimLeadingWhitespace(foo, 1), " FOO");
38 | assertEquals(ParsingUtils.trimLeadingWhitespace(foo, 3), "FOO");
39 | }
40 |
41 | @Test
42 | public void getMinWhitespace() {
43 | List lines = new ArrayList();
44 | lines.add(" FOO");
45 | lines.add(" BAR");
46 | lines.add(" BAZ");
47 | assertEquals(ParsingUtils.getMinWhitespace(lines), 1);
48 | }
49 |
50 | @Test
51 | public void formatSampleText() {
52 | List lines = new ArrayList();
53 | lines.add(" ONE");
54 | lines.add(" TWO");
55 | lines.add(" THREE");
56 |
57 | assertEquals(ParsingUtils.formatSampleText(lines, 1),
58 | "ONE\n TWO\nTHREE");
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/test/resources/testsamples/BadBeginHiddenTagSample.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.codesamples.test;
2 |
3 | public class BadBeginHiddenTagSample {
4 |
5 | public void sample() {
6 | //BEGIN_SAMPLE:Test.Sample
7 | //DESCRIPTION:A sample
8 | String foo = "foo!";
9 | //BEGIN_HIDDEN
10 | //BEGIN_HIDDEN
11 | String bar = "bar!";
12 | //END_HIDDEN
13 | //END_SAMPLE
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/test/resources/testsamples/BadDescriptionTagSample.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.codesamples.test;
2 |
3 | public class BadDescriptionTagSample {
4 |
5 | public void sample() {
6 | //DESCRIPTION:Orphaned description
7 | }
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/test/resources/testsamples/BadEndHiddenTagSample.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.codesamples.test;
2 |
3 | public class BadEndHiddenTagSample {
4 |
5 | public void sample() {
6 | //BEGIN_SAMPLE:Test.Sample
7 | //DESCRIPTION:A sample
8 | String foo = "foo!";
9 | //END_HIDDEN
10 | //BEGIN_HIDDEN
11 | String bar = "bar!";
12 | //END_HIDDEN
13 | //END_SAMPLE
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/test/resources/testsamples/BadEndTagSample.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.codesamples.test;
2 |
3 | public class BadEndTagSample {
4 |
5 | public void sample() {
6 | //END_SAMPLE
7 |
8 | //BEGIN_SAMPLE:Test.Sample
9 | //DESCRIPTION:A sample
10 | String foo = "foo!";
11 | //END_SAMPLE
12 | }
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/test/resources/testsamples/BadExtension.cpp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amazon-archives/aws-sdk-java-samples/9a013d92d33c4a3dadb0f40ef93d9ab8316b2465/aws-java-sdk-sample-extractor/src/test/resources/testsamples/BadExtension.cpp
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/test/resources/testsamples/BadStartTagSample.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.codesamples.test;
2 |
3 | public class BadStartTagSample {
4 |
5 | public void sample() {
6 | //BEGIN_SAMPLE:Test.Sample
7 | //DESCRIPTION:A sample
8 | String foo = "foo!";
9 | //BEGIN_SAMPLE:Bad.Tag
10 | //END_SAMPLE
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/test/resources/testsamples/BadTitleTagSample.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.codesamples.test;
2 |
3 | public class BadTitleTagSample {
4 |
5 | public void sample() {
6 | //TITLE:Orphaned title
7 | }
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/test/resources/testsamples/EmptySamples.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.codesamples.test;
2 |
3 | public class EmptySamples {
4 |
5 | }
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/test/resources/testsamples/NoContentSample.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.codesamples.test;
2 |
3 | public class NoContentSample {
4 |
5 | public void sample() {
6 | //BEGIN_SAMPLE:Test.Sample
7 | //TITLE:Test Sample
8 | //DESCRIPTION:A sample
9 | //END_SAMPLE
10 | }
11 |
12 | }
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/test/resources/testsamples/NoDescriptionSample.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.codesamples.test;
2 |
3 | public class NoDescriptionSample {
4 |
5 | public void sample() {
6 | //BEGIN_SAMPLE:Test.Sample
7 | //TITLE:Test Sample
8 | String foo = "foo!";
9 | //END_SAMPLE
10 | }
11 |
12 | }
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/test/resources/testsamples/NoTitleSample.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.codesamples.test;
2 |
3 | public class NoTitleSample {
4 |
5 | public void sample() {
6 | //BEGIN_SAMPLE:Test.Sample
7 | //DESCRIPTION:A sample
8 | String foo = "foo!";
9 | //END_SAMPLE
10 | }
11 |
12 | }
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/test/resources/testsamples/TestSamples.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.codesamples.test;
2 |
3 | public class TestSamples {
4 |
5 | public void samples() {
6 | //BEGIN_SAMPLE:Test1.Sample1
7 | //TITLE:First sample
8 | //DESCRIPTION:The first sample
9 | String foo = "foo!";
10 | //END_SAMPLE
11 |
12 | //BEGIN_SAMPLE:Test2.Sample2
13 | //TITLE:Second sample
14 | //DESCRIPTION:The second sample
15 | String bar = "bar!";
16 | String baz = "baz!";
17 | //END_SAMPLE
18 |
19 | //BEGIN_SAMPLE:Test3.Sample3
20 | //TITLE:Third sample
21 | //DESCRIPTION:The third sample
22 | String visible = "this should be visible";
23 | //BEGIN_HIDDEN
24 | String hidden = "this should be hidden";
25 | //END_HIDDEN
26 | //END_SAMPLE
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/aws-java-sdk-sample-extractor/src/test/resources/testsamples/UnclosedSample.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.codesamples.test;
2 |
3 | public class UnclosedSample {
4 |
5 | public void sample() {
6 | //BEGIN_SAMPLE:Test.Sample
7 | //DESCRIPTION:A sample
8 | String foo = "foo!";
9 | }
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/aws-java-sdk-samples/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4.0.0
4 |
5 | com.amazonaws
6 | aws-java-sdk-samples-pom
7 | 1.1.4-SNAPSHOT
8 |
9 | com.amazonaws
10 | aws-java-sdk-samples
11 | 1.1.4-SNAPSHOT
12 | aws-java-sdk-samples
13 | http://maven.apache.org
14 |
15 | UTF-8
16 |
17 |
18 |
19 |
20 | com.amazonaws
21 | aws-java-sdk-generated-samples
22 | 1.1.4-SNAPSHOT
23 |
24 |
25 | compile
26 |
27 | GenerateSamples
28 |
29 |
30 |
31 |
32 |
33 | org.apache.maven.plugins
34 | maven-compiler-plugin
35 | 3.3
36 |
37 |
38 | compile
39 |
40 | compile
41 |
42 |
43 |
44 |
45 |
46 | org.apache.maven.plugins
47 | maven-clean-plugin
48 | 3.0.0
49 |
50 | true
51 |
52 |
53 | ${project.build.sourceDirectory}/samples
54 |
55 | *.java
56 |
57 | false
58 |
59 |
60 |
61 |
62 |
63 | compile
64 |
65 | clean
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 | junit
75 | junit
76 | 4.12
77 | test
78 |
79 |
80 | com.amazonaws
81 | aws-java-sdk-handwritten-samples
82 | 1.1.4-SNAPSHOT
83 | false
84 |
85 |
86 | com.amazonaws
87 | aws-java-sdk
88 | ${awsjavasdk.version}
89 | false
90 |
91 |
92 | sun.jdk
93 | tools
94 | 1.8
95 | system
96 | ${java.home}/../lib/tools.jar
97 |
98 |
99 |
100 |
--------------------------------------------------------------------------------
/aws-java-sdk-samples/src/main/java/com/amazonaws/codesamples/RetrievedCodeSample.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.codesamples;
2 |
3 | import com.amazonaws.codesamples.util.ValidationUtils;
4 |
5 | /**
6 | * Represents a code sample retrieved from an XML code samples file.
7 | */
8 | public class RetrievedCodeSample {
9 |
10 | private final String id;
11 | private final String service;
12 | private final String title;
13 | private final String description;
14 | private final String content;
15 |
16 | /**
17 | * Ctor.
18 | *
19 | * @param id
20 | * sample id
21 | * @param service
22 | * name of service sample associated with
23 | * @param title
24 | * title of the sample
25 | * @param description
26 | * description of the sample
27 | * @param content
28 | * code sample content
29 | */
30 | public RetrievedCodeSample(final String id, final String service,
31 | final String title, final String description, final String content) {
32 | this.id = ValidationUtils.assertInputNotEmpty(id,
33 | "Sample ID must be provided");
34 | this.service = ValidationUtils.assertInputNotEmpty(service,
35 | "Sample service name must be provided");
36 | this.title = ValidationUtils.assertInputNotEmpty(title,
37 | "Sample title must be provided");
38 | this.description = ValidationUtils.assertInputNotEmpty(description,
39 | "Sample description must be provided");
40 | this.content = ValidationUtils.assertInputNotEmpty(content,
41 | "Sample content must be provided");
42 | }
43 |
44 | /**
45 | * Returns the id of the sample.
46 | *
47 | * @return id of the sample
48 | */
49 | public String getId() {
50 | return id;
51 | }
52 |
53 | /**
54 | * Returns the name of the service the sample is associated with.
55 | *
56 | * @return name of service sample is associated with
57 | */
58 | public String getService() {
59 | return service;
60 | }
61 |
62 | /**
63 | * Returns the title of the sample.
64 | *
65 | * @return title of the sample
66 | */
67 | public String getTitle() {
68 | return title;
69 | }
70 |
71 | /**
72 | * Returns the description of the sample.
73 | *
74 | * @return description of the sample
75 | */
76 | public String getDescription() {
77 | return description;
78 | }
79 |
80 | /**
81 | * Returns the code sample content
82 | *
83 | * @return sample content
84 | */
85 | public String getContent() {
86 | return content;
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/aws-java-sdk-samples/src/main/java/com/amazonaws/codesamples/SampleCodeReader.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License").
5 | * You may not use this file except in compliance with the License.
6 | * A copy of the License is located at
7 | *
8 | * http://aws.amazon.com/apache2.0
9 | *
10 | * or in the "license" file accompanying this file. This file is distributed
11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 | * express or implied. See the License for the specific language governing
13 | * permissions and limitations under the License.
14 | */
15 | package com.amazonaws.codesamples;
16 |
17 | import java.io.InputStream;
18 |
19 | import javax.xml.parsers.SAXParser;
20 | import javax.xml.parsers.SAXParserFactory;
21 |
22 | import com.amazonaws.codesamples.util.ValidationUtils;
23 | import com.amazonaws.codesamples.exception.SampleRetrievalException;
24 |
25 | /**
26 | * Reads code samples from a source directory containing processed sample code
27 | * XML files.
28 | */
29 | public class SampleCodeReader {
30 |
31 | private static final SAXParserFactory parserFactory = SAXParserFactory
32 | .newInstance();
33 |
34 | private final String sampleDir;
35 | private final SAXParser saxParser;
36 |
37 | /**
38 | * Ctor.
39 | *
40 | * @param sampleDir
41 | * directory containing code sample XML files
42 | * @throws Exception
43 | * if SAX Parser cannot be initialized
44 | */
45 | public SampleCodeReader(final String sampleDir) throws Exception {
46 | this.sampleDir = ValidationUtils.assertInputNotEmpty(sampleDir,
47 | "Sample directory must be provided");
48 | this.saxParser = parserFactory.newSAXParser();
49 | }
50 |
51 | /**
52 | * Retrieves a specified code sample.
53 | *
54 | * @param serviceName
55 | * service sample belongs to
56 | * @param sampleId
57 | * unique id of sample
58 | * @return retrieved code sample or null if sample does not exist
59 | * or is incomplete
60 | * @throws SampleRetrievalException
61 | * if sample cannot be retrieved due to an error
62 | */
63 | public RetrievedCodeSample readSample(final String serviceName,
64 | final String sampleId) throws SampleRetrievalException {
65 | ValidationUtils.assertInputNotEmpty(serviceName,
66 | "Sample service name must be provided");
67 | ValidationUtils.assertInputNotEmpty(sampleId,
68 | "Sample ID must be provided");
69 |
70 | String targetSampleFile = String.format("/%s/%s.xml", sampleDir,
71 | serviceName);
72 | InputStream in = getClass().getResourceAsStream(targetSampleFile);
73 |
74 | if (in == null) {
75 | // sample file does not exist. typically this means that this service
76 | // does not yet have any samples. quietly handle this case.
77 | return null;
78 | }
79 |
80 | SampleCodeXMLParser parser = new SampleCodeXMLParser(sampleId);
81 | try {
82 | saxParser.parse(in, parser);
83 | } catch (Exception e) {
84 | throw new SampleRetrievalException("Could not parse sample",
85 | serviceName, sampleId, e);
86 | }
87 |
88 | String sampleContent = parser.getSampleContent();
89 | String sampleTitle = parser.getSampleTitle();
90 | String sampleDescription = parser.getSampleDescription();
91 |
92 | if (ValidationUtils.areNullOrEmpty(sampleContent, sampleTitle,
93 | sampleDescription)) {
94 | // quietly handle missing or incomplete samples
95 | return null;
96 | }
97 |
98 | return new RetrievedCodeSample(sampleId, serviceName,
99 | sampleTitle, sampleDescription, sampleContent);
100 | }
101 |
102 | }
103 |
--------------------------------------------------------------------------------
/aws-java-sdk-samples/src/main/java/com/amazonaws/codesamples/SampleCodeTaglet.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License").
5 | * You may not use this file except in compliance with the License.
6 | * A copy of the License is located at
7 | *
8 | * http://aws.amazon.com/apache2.0
9 | *
10 | * or in the "license" file accompanying this file. This file is distributed
11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 | * express or implied. See the License for the specific language governing
13 | * permissions and limitations under the License.
14 | */
15 | package com.amazonaws.codesamples;
16 |
17 | import com.amazonaws.codesamples.util.SampleHTMLTemplates;
18 | import com.sun.javadoc.Tag;
19 | import com.sun.tools.doclets.Taglet;
20 |
21 | import java.util.ArrayList;
22 | import java.util.List;
23 | import java.util.Map;
24 | import java.util.regex.Matcher;
25 | import java.util.regex.Pattern;
26 |
27 | import javax.xml.parsers.SAXParser;
28 | import javax.xml.parsers.SAXParserFactory;
29 |
30 | import java.net.URL;
31 | import java.net.URLClassLoader;
32 |
33 | /**
34 | * Taglet that retrieves and injects sample code blocks into sections of
35 | * Javadocs marked with @sample tags. Samples are retrieved from an
36 | * intermediate XML format, formatted into HTML blocks, and inserted
37 | * into the final Javadoc.
38 | *
39 | * Example tag: @sample S3.FooSample
40 | */
41 | public class SampleCodeTaglet implements Taglet {
42 |
43 | private static final String SAMPLE_TAG = "sample";
44 | private static final String SAMPLES_DIRECTORY = "samples";
45 | private static final Pattern SAMPLE_TAG_PATTERN = Pattern
46 | .compile("([^\\s.]+)\\.([^\\s.]+)$");
47 |
48 | private SampleCodeReader reader;
49 |
50 | public SampleCodeTaglet() {
51 | try {
52 | reader = new SampleCodeReader(SAMPLES_DIRECTORY);
53 | } catch (Exception e) {
54 | System.err.println("Could not initialize sample reader for taglet"
55 | + " processor. Code samples will not be injected.");
56 | e.printStackTrace();
57 | }
58 | }
59 |
60 | @Override
61 | public String getName() {
62 | return SAMPLE_TAG;
63 | }
64 |
65 | @Override
66 | public boolean inConstructor() {
67 | return true;
68 | }
69 |
70 | @Override
71 | public boolean inField() {
72 | return true;
73 | }
74 |
75 | @Override
76 | public boolean inMethod() {
77 | return true;
78 | }
79 |
80 | @Override
81 | public boolean inOverview() {
82 | return true;
83 | }
84 |
85 | @Override
86 | public boolean inPackage() {
87 | return true;
88 | }
89 |
90 | @Override
91 | public boolean inType() {
92 | return true;
93 | }
94 |
95 | @Override
96 | public boolean isInlineTag() {
97 | return false;
98 | }
99 |
100 | public static void register(final Map tagletMap) {
101 | Taglet taglet = tagletMap.get(SAMPLE_TAG);
102 | if (taglet != null) {
103 | tagletMap.remove(SAMPLE_TAG);
104 | }
105 | tagletMap.put(SAMPLE_TAG, new SampleCodeTaglet());
106 | }
107 |
108 | @Override
109 | public String toString(Tag tag) {
110 | Tag[] singletonTag = { tag };
111 | return toString(singletonTag);
112 | }
113 |
114 | @Override
115 | public String toString(Tag[] tags) {
116 | if (tags.length == 0) {
117 | return null;
118 | }
119 |
120 | List samples = new ArrayList();
121 |
122 | for (int i = 0; i < tags.length; i++) {
123 | String tagText = tags[i].text();
124 |
125 | Matcher sampleTagMatcher = SAMPLE_TAG_PATTERN
126 | .matcher(tagText);
127 |
128 | if (sampleTagMatcher.find()) {
129 | String serviceName = sampleTagMatcher.group(1);
130 | String sampleId = sampleTagMatcher.group(2);
131 |
132 | try {
133 | RetrievedCodeSample sample = reader.readSample(serviceName, sampleId);
134 | if (sample != null) {
135 | samples.add(sample);
136 | }
137 | } catch (Exception e) {
138 | System.err.println("Could not parse tag: " + tagText);
139 | e.printStackTrace();
140 | }
141 | } else {
142 | System.err.println("Sample tag did not match expected format: "
143 | + tagText);
144 | }
145 | }
146 |
147 | /*
148 | * Only render the sample block if we've actually got valid samples
149 | * to display.
150 | */
151 | if (!samples.isEmpty()) {
152 | return SampleHTMLTemplates.getSampleSectionHTML(samples);
153 | } else {
154 | return "";
155 | }
156 | }
157 | }
158 |
--------------------------------------------------------------------------------
/aws-java-sdk-samples/src/main/java/com/amazonaws/codesamples/SampleCodeXMLParser.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License").
5 | * You may not use this file except in compliance with the License.
6 | * A copy of the License is located at
7 | *
8 | * http://aws.amazon.com/apache2.0
9 | *
10 | * or in the "license" file accompanying this file. This file is distributed
11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 | * express or implied. See the License for the specific language governing
13 | * permissions and limitations under the License.
14 | */
15 | package com.amazonaws.codesamples;
16 |
17 | import org.xml.sax.Attributes;
18 | import org.xml.sax.helpers.DefaultHandler;
19 |
20 | /**
21 | * SAX handler for parsing XML formatted Javadoc sample files.
22 | */
23 | public class SampleCodeXMLParser extends DefaultHandler {
24 |
25 | private static final String SAMPLE_ELEMENT = "sample";
26 | private static final String CONTENT_ELEMENT = "content";
27 | private static final String ID_ATTRIBUTE = "id";
28 | private static final String TITLE_ATTRIBUTE = "title";
29 | private static final String DESCRIPTION_ATTRIBUTE = "description";
30 |
31 | private boolean inTargetSample;
32 | private boolean inTargetContent;
33 | private StringBuffer sampleBuffer;
34 |
35 | private final String sampleId;
36 |
37 | private String sampleTitle;
38 | private String sampleDescription;
39 | private String sampleContent;
40 |
41 | public SampleCodeXMLParser(final String sampleId) {
42 | this.inTargetSample = false;
43 | this.inTargetContent = false;
44 | this.sampleBuffer = new StringBuffer();
45 | this.sampleId = sampleId;
46 | }
47 |
48 | @Override
49 | public void startElement(String uri, String localName, String qName,
50 | Attributes attributes) {
51 | if (qName.equals(SAMPLE_ELEMENT)) {
52 | String idAttr = attributes.getValue(ID_ATTRIBUTE);
53 | if (idAttr != null && idAttr.equals(sampleId)) {
54 | inTargetSample = true;
55 | sampleTitle = attributes.getValue(TITLE_ATTRIBUTE);
56 | sampleDescription = attributes.getValue(DESCRIPTION_ATTRIBUTE);
57 | }
58 | }
59 |
60 | if (qName.equals(CONTENT_ELEMENT) && inTargetSample) {
61 | inTargetContent = true;
62 | }
63 |
64 | }
65 |
66 | @Override
67 | public void characters(char ch[], int start, int length) {
68 | if (inTargetContent) {
69 | sampleBuffer.append(ch, start, length);
70 | }
71 | }
72 |
73 | @Override
74 | public void endElement(String uri, String localName, String qName) {
75 | if (inTargetContent) {
76 | sampleContent = sampleBuffer.toString();
77 | inTargetContent = false;
78 | }
79 | inTargetSample = false;
80 | }
81 |
82 | public String getSampleTitle() {
83 | return sampleTitle;
84 | }
85 |
86 | public String getSampleDescription() {
87 | return sampleDescription;
88 | }
89 |
90 | public String getSampleContent() {
91 | return sampleContent;
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/aws-java-sdk-samples/src/main/java/com/amazonaws/codesamples/exception/SampleRetrievalException.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.codesamples.exception;
2 |
3 | /**
4 | * Exception thrown when an error occurs while retrieving a code sample.
5 | */
6 | public class SampleRetrievalException extends RuntimeException {
7 |
8 | private static final long serialVersionUID = 4855855418438710812L;
9 |
10 | /**
11 | * Constructs a SampleRetrievalException with the specified message.
12 | *
13 | * @param serviceName
14 | * name of source service for sample
15 | * @param sampleId
16 | * id of sample being retrieved
17 | * @param message
18 | * exception detail message
19 | */
20 | public SampleRetrievalException(final String message,
21 | final String serviceName, final String sampleId) {
22 | super(formatExceptionMessage(message, serviceName, sampleId));
23 | }
24 |
25 | /**
26 | * Constructs a SampleRetrievalException with the specified message and
27 | * cause.
28 | *
29 | * @param serviceName
30 | * name of source service for sample
31 | * @param sampleId
32 | * id of sample being retrieved
33 | * @param message
34 | * exception detail message
35 | * @param cause
36 | * exception cause
37 | */
38 | public SampleRetrievalException(final String message,
39 | final String serviceName, final String sampleId,
40 | final Throwable cause) {
41 | super(formatExceptionMessage(message, serviceName, sampleId), cause);
42 | }
43 |
44 | private static String formatExceptionMessage(final String message,
45 | final String serviceName, final String sampleId) {
46 | return String.format("%s (Service Name: %s, Sample ID: %s)", message,
47 | serviceName, sampleId);
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/aws-java-sdk-samples/src/main/java/com/amazonaws/codesamples/util/SampleHTMLTemplates.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License").
5 | * You may not use this file except in compliance with the License.
6 | * A copy of the License is located at
7 | *
8 | * http://aws.amazon.com/apache2.0
9 | *
10 | * or in the "license" file accompanying this file. This file is distributed
11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 | * express or implied. See the License for the specific language governing
13 | * permissions and limitations under the License.
14 | */
15 | package com.amazonaws.codesamples.util;
16 |
17 | import java.util.List;
18 |
19 | import com.amazonaws.codesamples.RetrievedCodeSample;
20 |
21 | /**
22 | * Templates used to insert raw code samples into Javadoc HTML blocks.
23 | */
24 | public class SampleHTMLTemplates {
25 |
26 | private static final String SAMPLE_TAG = "${SAMPLES}";
27 | private static final String TITLE_TAG = "${TITLE}";
28 | private static final String DESCRIPTION_TAG = "${DESCRIPTION}";
29 | private static final String CONTENT_TAG = "${CONTENT}";
30 |
31 | private static final String SAMPLES_SECTION = "
"
32 | + "Samples:"
33 | + "- "
34 | + SAMPLE_TAG
35 | + "
";
36 |
37 | private static final String SAMPLE = "" + TITLE_TAG + "
"
38 | + "" + DESCRIPTION_TAG + "
"
39 | + "
" + CONTENT_TAG + "
";
40 | /**
41 | * Parses a given raw code sample into a HTML sample block.
42 | *
43 | * @param title
44 | * code sample title
45 | * @param description
46 | * code sample description
47 | * @param content
48 | * code sample content
49 | * @return formatted HTML code sample block
50 | */
51 | public static String getSampleHTML(final String title,
52 | final String description, final String content) {
53 | return SAMPLE.replace(TITLE_TAG, title)
54 | .replace(DESCRIPTION_TAG, description)
55 | .replace(CONTENT_TAG, content);
56 | }
57 |
58 | /**
59 | * Injects HTML formatted samples into an outer samples HTML block.
60 | *
61 | * @param samples
62 | * HTML formatted samples
63 | * @return formatted outer HTML samples block
64 | */
65 | public static String getSampleSectionHTML(
66 | final List samples) {
67 | StringBuilder samplesHTML = new StringBuilder();
68 |
69 | for (RetrievedCodeSample sample : samples) {
70 | samplesHTML.append(getSampleHTML(sample.getTitle(),
71 | sample.getDescription(),
72 | sample.getContent()));
73 | }
74 |
75 | return SAMPLES_SECTION.replace(SAMPLE_TAG, samplesHTML.toString());
76 | }
77 |
78 | }
79 |
--------------------------------------------------------------------------------
/aws-java-sdk-samples/src/main/java/com/amazonaws/codesamples/util/ValidationUtils.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.codesamples.util;
2 |
3 | import com.amazonaws.codesamples.exception.SampleRetrievalException;
4 |
5 | /**
6 | * Sample retrieval validation helper methods.
7 | */
8 | public class ValidationUtils {
9 |
10 | public static String assertInputNotEmpty(final String input,
11 | final String message) {
12 | if (input == null || input.isEmpty()) {
13 | throw new IllegalArgumentException(message);
14 | }
15 | return input;
16 | }
17 |
18 | public static String assertResultNotEmpty(final String result,
19 | final String serviceName, final String sampleId,
20 | final String message) {
21 | if (result == null || result.isEmpty()) {
22 | throw new SampleRetrievalException(message, serviceName, sampleId);
23 | }
24 | return result;
25 | }
26 |
27 | public static boolean areNullOrEmpty(final String... strings) {
28 | for (String str : strings) {
29 | if (isNullOrEmpty(str)) {
30 | return true;
31 | }
32 | }
33 | return false;
34 | }
35 |
36 | public static boolean isNullOrEmpty(final String string) {
37 | return string == null || string.length() == 0;
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/aws-java-sdk-samples/src/test/java/com/amazonaws/codesamples/RetrievedCodeSampleTest.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.codesamples;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import org.junit.Test;
6 |
7 | public class RetrievedCodeSampleTest {
8 |
9 | private static final String SAMPLE_ID = "FooSample";
10 | private static final String SERVICE_NAME = "FooService";
11 | private static final String TITLE = "FooTitle";
12 | private static final String DESCRIPTION = "FooDesc";
13 | private static final String CONTENT = "FooContent";
14 |
15 | @Test
16 | public void testRetrievedCodeSample() {
17 | RetrievedCodeSample sample = new RetrievedCodeSample(SAMPLE_ID,
18 | SERVICE_NAME, TITLE, DESCRIPTION, CONTENT);
19 | assertEquals(SAMPLE_ID, sample.getId());
20 | assertEquals(SERVICE_NAME, sample.getService());
21 | assertEquals(TITLE, sample.getTitle());
22 | assertEquals(DESCRIPTION, sample.getDescription());
23 | assertEquals(CONTENT, sample.getContent());
24 | }
25 |
26 | @Test(expected = IllegalArgumentException.class)
27 | public void testRetrievedCodeSampleNullId() {
28 | new RetrievedCodeSample(null, SERVICE_NAME, TITLE, DESCRIPTION, CONTENT);
29 | }
30 |
31 | @Test(expected = IllegalArgumentException.class)
32 | public void testRetrievedCodeSampleEmptyId() {
33 | new RetrievedCodeSample("", SERVICE_NAME, TITLE, DESCRIPTION, CONTENT);
34 | }
35 |
36 | @Test(expected = IllegalArgumentException.class)
37 | public void testRetrievedCodeSampleNullServiceName() {
38 | new RetrievedCodeSample(SAMPLE_ID, null, TITLE, DESCRIPTION, CONTENT);
39 | }
40 |
41 | @Test(expected = IllegalArgumentException.class)
42 | public void testRetrievedCodeSampleEmptyServiceName() {
43 | new RetrievedCodeSample(SAMPLE_ID, "", TITLE, DESCRIPTION, CONTENT);
44 | }
45 |
46 | @Test(expected = IllegalArgumentException.class)
47 | public void testRetrievedCodeSampleNullTitle() {
48 | new RetrievedCodeSample(SAMPLE_ID, SERVICE_NAME, null, DESCRIPTION, CONTENT);
49 | }
50 |
51 | @Test(expected = IllegalArgumentException.class)
52 | public void testRetrievedCodeSampleEmptyTitle() {
53 | new RetrievedCodeSample(SAMPLE_ID, SERVICE_NAME, "", DESCRIPTION, CONTENT);
54 | }
55 |
56 | @Test(expected = IllegalArgumentException.class)
57 | public void testRetrievedCodeSampleNullDescription() {
58 | new RetrievedCodeSample(SAMPLE_ID, SERVICE_NAME, TITLE, null, CONTENT);
59 | }
60 |
61 | @Test(expected = IllegalArgumentException.class)
62 | public void testRetrievedCodeSampleEmptyDescription() {
63 | new RetrievedCodeSample(SAMPLE_ID, SERVICE_NAME, TITLE, "", CONTENT);
64 | }
65 |
66 | @Test(expected = IllegalArgumentException.class)
67 | public void testRetrievedCodeSampleNullContent() {
68 | new RetrievedCodeSample(SAMPLE_ID, SERVICE_NAME, TITLE, DESCRIPTION, null);
69 | }
70 |
71 | @Test(expected = IllegalArgumentException.class)
72 | public void testRetrievedCodeSampleEmptyContent() {
73 | new RetrievedCodeSample(SAMPLE_ID, SERVICE_NAME, TITLE, DESCRIPTION, "");
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/aws-java-sdk-samples/src/test/java/com/amazonaws/codesamples/SampleCodeReaderTest.java:
--------------------------------------------------------------------------------
1 | package com.amazonaws.codesamples;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import org.junit.Before;
6 | import org.junit.Test;
7 | import org.junit.Assert;
8 |
9 | import com.amazonaws.codesamples.exception.SampleRetrievalException;
10 |
11 | public class SampleCodeReaderTest {
12 |
13 | private static final String SAMPLE_ID = "FooSample";
14 | private static final String SERVICE_NAME = "FooService";
15 |
16 | private SampleCodeReader reader;
17 |
18 | @Before
19 | public void setUp() throws Exception {
20 | reader = new SampleCodeReader("testsamples");
21 | }
22 |
23 | @Test
24 | public void testRetrieveValidSample() throws Exception {
25 | RetrievedCodeSample sample = reader.readSample(SERVICE_NAME,
26 | SAMPLE_ID);
27 | assertEquals(sample.getId(), SAMPLE_ID);
28 | assertEquals(sample.getService(), SERVICE_NAME);
29 | assertEquals(sample.getTitle(), "Foo Sample");
30 | assertEquals(sample.getDescription(), "A foo sample!");
31 | assertEquals(sample.getContent(), "String foo = \"foo!\";");
32 | }
33 |
34 | @Test(expected = IllegalArgumentException.class)
35 | public void testRetrieveSampleNullService() throws SampleRetrievalException {
36 | reader.readSample(null, SAMPLE_ID);
37 | }
38 |
39 | @Test(expected = IllegalArgumentException.class)
40 | public void testRetrieveSampleEmptyService()
41 | throws SampleRetrievalException {
42 | reader.readSample("", SAMPLE_ID);
43 | }
44 |
45 | @Test(expected = IllegalArgumentException.class)
46 | public void testRetrieveSampleNullSample() throws SampleRetrievalException {
47 | reader.readSample(SERVICE_NAME, null);
48 | }
49 |
50 | @Test(expected = IllegalArgumentException.class)
51 | public void testRetrieveSampleEmptySample() throws SampleRetrievalException {
52 | reader.readSample(SERVICE_NAME, "");
53 | }
54 |
55 | @Test
56 | public void testRetrieveNonExistantSample() throws SampleRetrievalException {
57 | Assert.assertNull(reader.readSample(SERVICE_NAME, "BogusSample"));
58 | }
59 |
60 | @Test
61 | public void testRetrieveSampleWithMissingTitle()
62 | throws SampleRetrievalException {
63 | Assert.assertNull(reader.readSample(SERVICE_NAME, "MissingTitleSample"));
64 | }
65 |
66 | @Test
67 | public void testRetrieveSampleWithEmptyTitle()
68 | throws SampleRetrievalException {
69 | Assert.assertNull(reader.readSample(SERVICE_NAME, "EmptyTitleSample"));
70 | }
71 |
72 | @Test
73 | public void testRetrieveSampleWithMissingDescription()
74 | throws SampleRetrievalException {
75 | Assert.assertNull(reader.readSample(SERVICE_NAME, "MissingDescriptionSample"));
76 | }
77 |
78 | @Test
79 | public void testRetrieveSampleWithEmptyDescription()
80 | throws SampleRetrievalException {
81 | Assert.assertNull(reader.readSample(SERVICE_NAME, "EmptyDescriptionSample"));
82 | }
83 |
84 | @Test
85 | public void testRetrieveSampleWithMissingContent()
86 | throws SampleRetrievalException {
87 | Assert.assertNull(reader.readSample(SERVICE_NAME, "MissingContentSample"));
88 | }
89 |
90 | @Test
91 | public void testRetrieveSampleWithEmptyContent()
92 | throws SampleRetrievalException {
93 | Assert.assertNull(reader.readSample(SERVICE_NAME, "EmptyContentSample"));
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/aws-java-sdk-samples/src/test/resources/testsamples/FooService.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | String foo = "foo!";
5 |
6 |
7 | String foo = "foo!";
8 |
9 |
10 | String foo = "foo!";
11 |
12 |
13 | String foo = "foo!";
14 |
15 |
16 | String foo = "foo!";
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4.0.0
4 |
5 |
6 | org.sonatype.oss
7 | oss-parent
8 | 9
9 |
10 |
11 | com.amazonaws
12 | aws-java-sdk-samples-pom
13 | 1.1.4-SNAPSHOT
14 | pom
15 | AWS SDK for Java Samples
16 | https://aws.amazon.com/sdkforjava
17 |
18 |
19 | Apache License, Version 2.0
20 | https://aws.amazon.com/apache2.0
21 | repo
22 |
23 |
24 |
25 |
26 | amazonwebservices
27 | Amazon Web Services
28 | https://aws.amazon.com
29 |
30 | developer
31 |
32 |
33 |
34 |
35 | aws-java-sdk-generated-samples
36 | aws-java-sdk-handwritten-samples
37 | aws-java-sdk-sample-extractor
38 | aws-java-sdk-samples
39 |
40 |
41 | scm:git:git@github.com:aws/aws-sdk-java-samples.git
42 | HEAD
43 |
44 |
45 | RELEASE
46 |
47 |
48 |
49 | sonatype-nexus-staging
50 | https://oss.sonatype.org/service/local/staging/deploy/maven2/
51 |
52 |
53 |
54 |
55 |
56 |
57 | maven-compiler-plugin
58 | 2.3
59 |
60 | UTF-8
61 |
62 |
63 |
64 | org.apache.maven.plugins
65 | maven-source-plugin
66 | 2.2.1
67 |
68 |
69 | attach-sources
70 |
71 | jar
72 |
73 |
74 |
75 |
76 |
77 | org.apache.maven.plugins
78 | maven-javadoc-plugin
79 | 2.10.3
80 |
81 |
82 | attach-javadocs
83 |
84 | jar
85 |
86 |
87 |
88 |
89 |
90 | org.apache.maven.plugins
91 | maven-release-plugin
92 | 2.5
93 |
94 | @{project.version}
95 | true
96 | publishing
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 | publishing
105 |
106 |
107 |
108 | maven-gpg-plugin
109 |
110 |
111 | sign-artifacts
112 | verify
113 |
114 | sign
115 |
116 |
117 |
118 |
119 |
120 | org.sonatype.plugins
121 | nexus-staging-maven-plugin
122 | 1.5.1
123 |
124 |
125 | default-deploy
126 | deploy
127 |
128 | deploy
129 |
130 |
131 |
132 |
133 | sonatype-nexus-staging
134 | https://oss.sonatype.org
135 | true
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
--------------------------------------------------------------------------------