diff --git a/README.md b/README.md index a753a96c8b21..6bd1e7211f2c 100644 --- a/README.md +++ b/README.md @@ -30,16 +30,16 @@ If you are using Maven, add this to your pom.xml file com.google.gcloud gcloud-java - 0.1.5 + 0.1.7 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.gcloud:gcloud-java:0.1.5' +compile 'com.google.gcloud:gcloud-java:0.1.7' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.gcloud" % "gcloud-java" % "0.1.5" +libraryDependencies += "com.google.gcloud" % "gcloud-java" % "0.1.7" ``` Example Applications @@ -84,8 +84,9 @@ Most `gcloud-java` libraries require a project ID. There are multiple ways to s 1. Project ID supplied when building the service options 2. Project ID specified by the environment variable `GCLOUD_PROJECT` 3. App Engine project ID -4. Google Cloud SDK project ID -5. Compute Engine project ID +4. Project ID specified in the JSON credentials file pointed by the `GOOGLE_APPLICATION_CREDENTIALS` environment variable +5. Google Cloud SDK project ID +6. Compute Engine project ID Authentication -------------- @@ -249,13 +250,13 @@ ZoneInfo zoneInfo = ZoneInfo.of(zoneName, domainName, description); Zone zone = dns.create(zoneInfo); ``` -The second snippet shows how to create records inside a zone. The complete code can be found on [CreateOrUpdateDnsRecords.java](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateDnsRecords.java). +The second snippet shows how to create records inside a zone. The complete code can be found on [CreateOrUpdateRecordSets.java](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateRecordSets.java). ```java -import com.google.gcloud.dns.ChangeRequest; +import com.google.gcloud.dns.ChangeRequestInfo; import com.google.gcloud.dns.Dns; import com.google.gcloud.dns.DnsOptions; -import com.google.gcloud.dns.DnsRecord; +import com.google.gcloud.dns.RecordSet; import com.google.gcloud.dns.Zone; import java.util.Iterator; @@ -265,24 +266,24 @@ Dns dns = DnsOptions.defaultInstance().service(); String zoneName = "my-unique-zone"; Zone zone = dns.getZone(zoneName); String ip = "12.13.14.15"; -DnsRecord toCreate = DnsRecord.builder("www.someexampledomain.com.", DnsRecord.Type.A) +RecordSet toCreate = RecordSet.builder("www.someexampledomain.com.", RecordSet.Type.A) .ttl(24, TimeUnit.HOURS) .addRecord(ip) .build(); -ChangeRequest.Builder changeBuilder = ChangeRequest.builder().add(toCreate); +ChangeRequestInfo.Builder changeBuilder = ChangeRequestInfo.builder().add(toCreate); // Verify that the record does not exist yet. // If it does exist, we will overwrite it with our prepared record. -Iterator recordIterator = zone.listDnsRecords().iterateAll(); -while (recordIterator.hasNext()) { - DnsRecord current = recordIterator.next(); +Iterator recordSetIterator = zone.listRecordSets().iterateAll(); +while (recordSetIterator.hasNext()) { + RecordSet current = recordSetIterator.next(); if (toCreate.name().equals(current.name()) && toCreate.type().equals(current.type())) { changeBuilder.delete(current); } } -ChangeRequest changeRequest = changeBuilder.build(); +ChangeRequestInfo changeRequest = changeBuilder.build(); zone.applyChangeRequest(changeRequest); ``` diff --git a/RELEASING.md b/RELEASING.md index 5e2d6202062e..81a7bcd06129 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -7,8 +7,8 @@ Most of the release process is handled by the `after_success.sh` script, trigger 1. Run `utilities/update_pom_version.sh` from the repository's base directory. This script takes an optional argument denoting the new version. By default, if the current version is X.Y.Z-SNAPSHOT, the script will update the version in all the pom.xml files to X.Y.Z. If desired, another version can be supplied via command line argument instead. -2. Create a PR to update the pom.xml version. -The PR should look something like [#225](https://github.com/GoogleCloudPlatform/gcloud-java/pull/225). After this PR is merged into GoogleCloudPlatform/gcloud-java, Travis CI will push a new website to GoogleCloudPlatform/gh-pages, push a new artifact to the Maven Central Repository, and update versions in the README files. +2. Create a PR to update the pom.xml version. If releasing a new client library, this PR should also update javadoc grouping in the base directory's [pom.xml](./pom.xml). +PRs that don't release new modules should look something like [#225](https://github.com/GoogleCloudPlatform/gcloud-java/pull/225). PRs that do release a new module should also add the appropriate packages to the javadoc groups "SPI" and "Test helpers", as shown in [#802](https://github.com/GoogleCloudPlatform/gcloud-java/pull/802) for `gcloud-java-dns`. After this PR is merged into GoogleCloudPlatform/gcloud-java, Travis CI will push a new website to GoogleCloudPlatform/gh-pages, push a new artifact to the Maven Central Repository, and update versions in the README files. 3. Before moving on, verify that the artifacts have successfully been pushed to the Maven Central Repository. Open Travis CI, click the ["Build History" tab](https://travis-ci.org/GoogleCloudPlatform/gcloud-java/builds), and open the second build's logs for Step 2's PR. Be sure that you are not opening the "Pull Request" build logs. When the build finishes, scroll to the end of the log and verify that the artifacts were successfully staged and deployed. You can also search for `gcloud-java` on the [Sonatype website](https://oss.sonatype.org/#nexus-search;quick~gcloud-java) and check the latest version number. If the deployment didn't succeed because of a flaky test, rerun the build. diff --git a/codacy-conf.json b/codacy-conf.json index e8c819684c9c..47998a3870d7 100644 --- a/codacy-conf.json +++ b/codacy-conf.json @@ -1 +1 @@ -{"patterns":[{"patternId":"Custom_Javascript_Scopes","enabled":true},{"patternId":"Custom_Javascript_EvalWith","enabled":true},{"patternId":"Custom_Javascript_TryCatch","enabled":true},{"patternId":"Custom_Scala_NonFatal","enabled":true},{"patternId":"bitwise","enabled":true},{"patternId":"maxparams","enabled":true},{"patternId":"CSSLint_universal_selector","enabled":true},{"patternId":"CSSLint_unqualified_attributes","enabled":true},{"patternId":"CSSLint_zero_units","enabled":true},{"patternId":"CSSLint_overqualified_elements","enabled":true},{"patternId":"CSSLint_shorthand","enabled":true},{"patternId":"CSSLint_duplicate_background_images","enabled":true},{"patternId":"CSSLint_box_model","enabled":true},{"patternId":"CSSLint_compatible_vendor_prefixes","enabled":true},{"patternId":"CSSLint_display_property_grouping","enabled":true},{"patternId":"CSSLint_duplicate_properties","enabled":true},{"patternId":"CSSLint_empty_rules","enabled":true},{"patternId":"CSSLint_errors","enabled":true},{"patternId":"CSSLint_gradients","enabled":true},{"patternId":"CSSLint_important","enabled":true},{"patternId":"CSSLint_known_properties","enabled":true},{"patternId":"CSSLint_text_indent","enabled":true},{"patternId":"CSSLint_unique_headings","enabled":true},{"patternId":"PyLint_E0100","enabled":true},{"patternId":"PyLint_E0101","enabled":true},{"patternId":"PyLint_E0102","enabled":true},{"patternId":"PyLint_E0103","enabled":true},{"patternId":"PyLint_E0104","enabled":true},{"patternId":"PyLint_E0105","enabled":true},{"patternId":"PyLint_E0106","enabled":true},{"patternId":"PyLint_E0107","enabled":true},{"patternId":"PyLint_E0108","enabled":true},{"patternId":"PyLint_E0202","enabled":true},{"patternId":"PyLint_E0203","enabled":true},{"patternId":"PyLint_E0211","enabled":true},{"patternId":"PyLint_E0601","enabled":true},{"patternId":"PyLint_E0603","enabled":true},{"patternId":"PyLint_E0604","enabled":true},{"patternId":"PyLint_E0701","enabled":true},{"patternId":"PyLint_E0702","enabled":true},{"patternId":"PyLint_E0710","enabled":true},{"patternId":"PyLint_E0711","enabled":true},{"patternId":"PyLint_E0712","enabled":true},{"patternId":"PyLint_E1003","enabled":true},{"patternId":"PyLint_E1102","enabled":true},{"patternId":"PyLint_E1111","enabled":true},{"patternId":"PyLint_E1120","enabled":true},{"patternId":"PyLint_E1121","enabled":true},{"patternId":"PyLint_E1123","enabled":true},{"patternId":"PyLint_E1124","enabled":true},{"patternId":"PyLint_E1200","enabled":true},{"patternId":"PyLint_E1201","enabled":true},{"patternId":"PyLint_E1205","enabled":true},{"patternId":"PyLint_E1206","enabled":true},{"patternId":"PyLint_E1300","enabled":true},{"patternId":"PyLint_E1301","enabled":true},{"patternId":"PyLint_E1302","enabled":true},{"patternId":"PyLint_E1303","enabled":true},{"patternId":"PyLint_E1304","enabled":true},{"patternId":"PyLint_E1305","enabled":true},{"patternId":"PyLint_E1306","enabled":true},{"patternId":"rulesets-codesize.xml-CyclomaticComplexity","enabled":true},{"patternId":"rulesets-codesize.xml-NPathComplexity","enabled":true},{"patternId":"rulesets-codesize.xml-ExcessiveMethodLength","enabled":true},{"patternId":"rulesets-codesize.xml-ExcessiveClassLength","enabled":true},{"patternId":"rulesets-codesize.xml-ExcessiveParameterList","enabled":true},{"patternId":"rulesets-codesize.xml-ExcessivePublicCount","enabled":true},{"patternId":"rulesets-codesize.xml-TooManyFields","enabled":true},{"patternId":"rulesets-codesize.xml-TooManyMethods","enabled":true},{"patternId":"rulesets-codesize.xml-ExcessiveClassComplexity","enabled":true},{"patternId":"rulesets-controversial.xml-Superglobals","enabled":true},{"patternId":"rulesets-design.xml-ExitExpression","enabled":true},{"patternId":"rulesets-design.xml-EvalExpression","enabled":true},{"patternId":"rulesets-design.xml-GotoStatement","enabled":true},{"patternId":"rulesets-design.xml-NumberOfChildren","enabled":true},{"patternId":"rulesets-design.xml-DepthOfInheritance","enabled":true},{"patternId":"rulesets-unusedcode.xml-UnusedPrivateField","enabled":true},{"patternId":"rulesets-unusedcode.xml-UnusedLocalVariable","enabled":true},{"patternId":"rulesets-unusedcode.xml-UnusedPrivateMethod","enabled":true},{"patternId":"rulesets-unusedcode.xml-UnusedFormalParameter","enabled":true},{"patternId":"PyLint_C0303","enabled":true},{"patternId":"PyLint_C1001","enabled":true},{"patternId":"rulesets-naming.xml-ShortVariable","enabled":true},{"patternId":"rulesets-naming.xml-LongVariable","enabled":true},{"patternId":"rulesets-naming.xml-ShortMethodName","enabled":true},{"patternId":"rulesets-naming.xml-ConstantNamingConventions","enabled":true},{"patternId":"rulesets-naming.xml-BooleanGetMethodName","enabled":true},{"patternId":"PyLint_W0101","enabled":true},{"patternId":"PyLint_W0102","enabled":true},{"patternId":"PyLint_W0104","enabled":true},{"patternId":"PyLint_W0105","enabled":true},{"patternId":"Custom_Scala_GetCalls","enabled":true},{"patternId":"ScalaStyle_EqualsHashCodeChecker","enabled":true},{"patternId":"ScalaStyle_ParameterNumberChecker","enabled":true},{"patternId":"ScalaStyle_ReturnChecker","enabled":true},{"patternId":"ScalaStyle_NullChecker","enabled":true},{"patternId":"ScalaStyle_NoCloneChecker","enabled":true},{"patternId":"ScalaStyle_NoFinalizeChecker","enabled":true},{"patternId":"ScalaStyle_CovariantEqualsChecker","enabled":true},{"patternId":"ScalaStyle_StructuralTypeChecker","enabled":true},{"patternId":"ScalaStyle_MethodLengthChecker","enabled":true},{"patternId":"ScalaStyle_NumberOfMethodsInTypeChecker","enabled":true},{"patternId":"ScalaStyle_WhileChecker","enabled":true},{"patternId":"ScalaStyle_VarFieldChecker","enabled":true},{"patternId":"ScalaStyle_VarLocalChecker","enabled":true},{"patternId":"ScalaStyle_RedundantIfChecker","enabled":true},{"patternId":"ScalaStyle_DeprecatedJavaChecker","enabled":true},{"patternId":"ScalaStyle_EmptyClassChecker","enabled":true},{"patternId":"ScalaStyle_NotImplementedErrorUsage","enabled":true},{"patternId":"Custom_Scala_GroupImports","enabled":true},{"patternId":"Custom_Scala_ReservedKeywords","enabled":true},{"patternId":"Custom_Scala_ElseIf","enabled":true},{"patternId":"Custom_Scala_CallByNameAsLastArguments","enabled":true},{"patternId":"Custom_Scala_WildcardImportOnMany","enabled":true},{"patternId":"Custom_Scala_UtilTryForTryCatch","enabled":true},{"patternId":"Custom_Scala_ProhibitObjectName","enabled":true},{"patternId":"Custom_Scala_ImportsAtBeginningOfPackage","enabled":true},{"patternId":"Custom_Scala_NameResultsAndParameters","enabled":true},{"patternId":"Custom_Scala_IncompletePatternMatching","enabled":true},{"patternId":"Custom_Scala_UsefulTypeAlias","enabled":true},{"patternId":"Custom_Scala_JavaThreads","enabled":true},{"patternId":"Custom_Scala_DirectPromiseCreation","enabled":true},{"patternId":"Custom_Scala_StructuralTypes","enabled":true},{"patternId":"Custom_Scala_CollectionLastHead","enabled":true},{"patternId":"PyLint_W0106","enabled":true},{"patternId":"PyLint_W0107","enabled":true},{"patternId":"PyLint_W0108","enabled":true},{"patternId":"PyLint_W0109","enabled":true},{"patternId":"PyLint_W0110","enabled":true},{"patternId":"PyLint_W0120","enabled":true},{"patternId":"PyLint_W0122","enabled":true},{"patternId":"PyLint_W0150","enabled":true},{"patternId":"PyLint_W0199","enabled":true},{"patternId":"rulesets-cleancode.xml-ElseExpression","enabled":true},{"patternId":"rulesets-cleancode.xml-StaticAccess","enabled":true},{"patternId":"ScalaStyle_NonASCIICharacterChecker","enabled":true},{"patternId":"ScalaStyle_FieldNamesChecker","enabled":true},{"patternId":"Custom_Scala_WithNameCalls","enabled":true},{"patternId":"strictexception_AvoidRethrowingException","enabled":true},{"patternId":"strings_AppendCharacterWithChar","enabled":true},{"patternId":"braces_IfElseStmtsMustUseBraces","enabled":true},{"patternId":"basic_AvoidDecimalLiteralsInBigDecimalConstructor","enabled":true},{"patternId":"basic_CheckSkipResult","enabled":true},{"patternId":"javabeans_MissingSerialVersionUID","enabled":true},{"patternId":"migrating_ShortInstantiation","enabled":true},{"patternId":"design_AvoidInstanceofChecksInCatchClause","enabled":true},{"patternId":"naming_LongVariable","enabled":true},{"patternId":"migrating_ReplaceEnumerationWithIterator","enabled":true},{"patternId":"j2ee_DoNotCallSystemExit","enabled":true},{"patternId":"unusedcode_UnusedLocalVariable","enabled":true},{"patternId":"strings_InefficientStringBuffering","enabled":true},{"patternId":"basic_DontUseFloatTypeForLoopIndices","enabled":true},{"patternId":"basic_AvoidBranchingStatementAsLastInLoop","enabled":true},{"patternId":"migrating_JUnit4TestShouldUseTestAnnotation","enabled":true},{"patternId":"optimizations_AddEmptyString","enabled":true},{"patternId":"logging-jakarta-commons_ProperLogger","enabled":true},{"patternId":"optimizations_RedundantFieldInitializer","enabled":true},{"patternId":"logging-java_AvoidPrintStackTrace","enabled":true},{"patternId":"empty_EmptyFinallyBlock","enabled":true},{"patternId":"design_CompareObjectsWithEquals","enabled":true},{"patternId":"basic_ClassCastExceptionWithToArray","enabled":true},{"patternId":"strictexception_DoNotExtendJavaLangError","enabled":true},{"patternId":"junit_UnnecessaryBooleanAssertion","enabled":true},{"patternId":"design_SimplifyBooleanExpressions","enabled":true},{"patternId":"basic_ForLoopShouldBeWhileLoop","enabled":true},{"patternId":"basic_BigIntegerInstantiation","enabled":true},{"patternId":"optimizations_UseArrayListInsteadOfVector","enabled":true},{"patternId":"optimizations_UnnecessaryWrapperObjectCreation","enabled":true},{"patternId":"strings_StringBufferInstantiationWithChar","enabled":true},{"patternId":"basic_JumbledIncrementer","enabled":true},{"patternId":"design_SwitchStmtsShouldHaveDefault","enabled":true},{"patternId":"strictexception_AvoidThrowingRawExceptionTypes","enabled":true},{"patternId":"migrating_LongInstantiation","enabled":true},{"patternId":"design_SimplifyBooleanReturns","enabled":true},{"patternId":"empty_EmptyInitializer","enabled":true},{"patternId":"design_FieldDeclarationsShouldBeAtStartOfClass","enabled":true},{"patternId":"unnecessary_UnnecessaryConversionTemporary","enabled":true},{"patternId":"design_AvoidProtectedFieldInFinalClass","enabled":true},{"patternId":"junit_UseAssertTrueInsteadOfAssertEquals","enabled":true},{"patternId":"naming_PackageCase","enabled":true},{"patternId":"migrating_JUnitUseExpected","enabled":true},{"patternId":"controversial_UnnecessaryConstructor","enabled":true},{"patternId":"naming_MethodNamingConventions","enabled":true},{"patternId":"design_DefaultLabelNotLastInSwitchStmt","enabled":true},{"patternId":"basic_UnconditionalIfStatement","enabled":true},{"patternId":"design_SingularField","enabled":true},{"patternId":"design_AssignmentToNonFinalStatic","enabled":true},{"patternId":"braces_WhileLoopsMustUseBraces","enabled":true},{"patternId":"logging-java_SystemPrintln","enabled":true},{"patternId":"strings_UseStringBufferLength","enabled":true},{"patternId":"controversial_AvoidUsingNativeCode","enabled":true},{"patternId":"strictexception_AvoidLosingExceptionInformation","enabled":true},{"patternId":"imports_ImportFromSamePackage","enabled":true},{"patternId":"finalizers_AvoidCallingFinalize","enabled":true},{"patternId":"finalizers_FinalizeOverloaded","enabled":true},{"patternId":"naming_ClassNamingConventions","enabled":true},{"patternId":"logging-java_LoggerIsNotStaticFinal","enabled":true},{"patternId":"finalizers_FinalizeOnlyCallsSuperFinalize","enabled":true},{"patternId":"unnecessary_UselessOverridingMethod","enabled":true},{"patternId":"naming_SuspiciousConstantFieldName","enabled":true},{"patternId":"design_OptimizableToArrayCall","enabled":true},{"patternId":"imports_UnnecessaryFullyQualifiedName","enabled":true},{"patternId":"migrating_ReplaceHashtableWithMap","enabled":true},{"patternId":"unusedcode_UnusedPrivateField","enabled":true},{"patternId":"strings_UnnecessaryCaseChange","enabled":true},{"patternId":"migrating_IntegerInstantiation","enabled":true},{"patternId":"design_NonStaticInitializer","enabled":true},{"patternId":"design_MissingBreakInSwitch","enabled":true},{"patternId":"design_AvoidReassigningParameters","enabled":true},{"patternId":"basic_AvoidThreadGroup","enabled":true},{"patternId":"empty_EmptyCatchBlock","parameters":{"allowCommentedBlocks":"true"},"enabled":true},{"patternId":"codesize_ExcessiveParameterList","parameters":{"minimum":"8","violationSuppressRegex":"\"\"","violationSuppressXPath":"\"\""},"enabled":true},{"patternId":"naming_SuspiciousHashcodeMethodName","enabled":true},{"patternId":"migrating_JUnit4TestShouldUseBeforeAnnotation","enabled":true},{"patternId":"design_UncommentedEmptyMethodBody","enabled":true},{"patternId":"basic_BrokenNullCheck","enabled":true},{"patternId":"strings_ConsecutiveLiteralAppends","enabled":true},{"patternId":"strings_StringInstantiation","enabled":true},{"patternId":"design_EqualsNull","enabled":true},{"patternId":"basic_OverrideBothEqualsAndHashcode","enabled":true},{"patternId":"design_InstantiationToGetClass","enabled":true},{"patternId":"basic_BooleanInstantiation","enabled":true},{"patternId":"strings_AvoidStringBufferField","enabled":true},{"patternId":"basic_ReturnFromFinallyBlock","enabled":true},{"patternId":"empty_EmptyTryBlock","enabled":true},{"patternId":"naming_SuspiciousEqualsMethodName","enabled":true},{"patternId":"basic_ExtendsObject","enabled":true},{"patternId":"strings_UselessStringValueOf","enabled":true},{"patternId":"design_UnsynchronizedStaticDateFormatter","enabled":true},{"patternId":"design_UseCollectionIsEmpty","enabled":true},{"patternId":"controversial_AvoidFinalLocalVariable","enabled":true},{"patternId":"strictexception_AvoidThrowingNullPointerException","enabled":true},{"patternId":"design_AvoidProtectedMethodInFinalClassNotExtending","enabled":true},{"patternId":"optimizations_PrematureDeclaration","enabled":true},{"patternId":"empty_EmptySwitchStatements","enabled":true},{"patternId":"basic_MisplacedNullCheck","enabled":true},{"patternId":"optimizations_UseStringBufferForStringAppends","enabled":true},{"patternId":"strings_StringToString","enabled":true},{"patternId":"naming_MethodWithSameNameAsEnclosingClass","enabled":true},{"patternId":"migrating_ReplaceVectorWithList","enabled":true},{"patternId":"imports_UnusedImports","enabled":true},{"patternId":"unnecessary_UnnecessaryFinalModifier","enabled":true},{"patternId":"basic_AvoidMultipleUnaryOperators","enabled":true},{"patternId":"junit_SimplifyBooleanAssertion","enabled":true},{"patternId":"unnecessary_UselessParentheses","enabled":true},{"patternId":"design_IdempotentOperations","enabled":true},{"patternId":"braces_IfStmtsMustUseBraces","enabled":true},{"patternId":"strings_UseIndexOfChar","enabled":true},{"patternId":"naming_NoPackage","enabled":true},{"patternId":"finalizers_FinalizeDoesNotCallSuperFinalize","enabled":true},{"patternId":"design_UseVarargs","enabled":true},{"patternId":"unusedcode_UnusedFormalParameter","enabled":true},{"patternId":"design_ReturnEmptyArrayRatherThanNull","enabled":true},{"patternId":"junit_UseAssertNullInsteadOfAssertTrue","enabled":true},{"patternId":"design_UseUtilityClass","enabled":true},{"patternId":"design_AvoidDeeplyNestedIfStmts","enabled":true},{"patternId":"empty_EmptyStatementNotInLoop","enabled":true},{"patternId":"junit_UseAssertSameInsteadOfAssertTrue","enabled":true},{"patternId":"braces_ForLoopsMustUseBraces","enabled":true},{"patternId":"controversial_DoNotCallGarbageCollectionExplicitly","enabled":true},{"patternId":"naming_GenericsNaming","enabled":true},{"patternId":"strings_UseEqualsToCompareStrings","enabled":true},{"patternId":"optimizations_AvoidArrayLoops","enabled":true},{"patternId":"empty_EmptyStaticInitializer","enabled":true},{"patternId":"design_UncommentedEmptyConstructor","enabled":true},{"patternId":"empty_EmptyStatementBlock","enabled":true},{"patternId":"basic_CollapsibleIfStatements","enabled":true},{"patternId":"design_FinalFieldCouldBeStatic","enabled":true},{"patternId":"logging-java_MoreThanOneLogger","enabled":true},{"patternId":"codesize_ExcessiveClassLength","enabled":true},{"patternId":"design_ImmutableField","enabled":true},{"patternId":"controversial_OneDeclarationPerLine","enabled":true},{"patternId":"empty_EmptyWhileStmt","enabled":true},{"patternId":"unnecessary_UnnecessaryReturn","enabled":true},{"patternId":"strings_InefficientEmptyStringCheck","enabled":true},{"patternId":"design_UseNotifyAllInsteadOfNotify","enabled":true},{"patternId":"strictexception_DoNotThrowExceptionInFinally","enabled":true},{"patternId":"junit_UseAssertEqualsInsteadOfAssertTrue","enabled":true},{"patternId":"typeresolution_CloneMethodMustImplementCloneable","enabled":true},{"patternId":"codesize_NPathComplexity","enabled":true},{"patternId":"imports_DontImportJavaLang","enabled":true},{"patternId":"empty_EmptySynchronizedBlock","enabled":true},{"patternId":"migrating_JUnit4TestShouldUseAfterAnnotation","enabled":true},{"patternId":"design_AvoidConstantsInterface","enabled":true},{"patternId":"unnecessary_UselessOperationOnImmutable","enabled":true},{"patternId":"design_PositionLiteralsFirstInComparisons","enabled":true},{"patternId":"migrating_ByteInstantiation","enabled":true},{"patternId":"junit_JUnitSpelling","enabled":true},{"patternId":"junit_JUnitTestsShouldIncludeAssert","enabled":true},{"patternId":"finalizers_EmptyFinalizer","enabled":true},{"patternId":"design_NonCaseLabelInSwitchStatement","enabled":true},{"patternId":"android_DoNotHardCodeSDCard","enabled":true},{"patternId":"design_LogicInversion","enabled":true},{"patternId":"unusedcode_UnusedPrivateMethod","enabled":true},{"patternId":"naming_AvoidDollarSigns","enabled":true},{"patternId":"finalizers_FinalizeShouldBeProtected","enabled":true},{"patternId":"clone_ProperCloneImplementation","enabled":true},{"patternId":"basic_CheckResultSet","enabled":true},{"patternId":"controversial_AvoidPrefixingMethodParameters","enabled":true},{"patternId":"migrating_JUnit4SuitesShouldUseSuiteAnnotation","enabled":true},{"patternId":"empty_EmptyIfStmt","enabled":true},{"patternId":"basic_DontCallThreadRun","enabled":true},{"patternId":"junit_JUnitStaticSuite","enabled":true},{"patternId":"optimizations_UseArraysAsList","enabled":true},{"patternId":"design_MissingStaticMethodInNonInstantiatableClass","enabled":true},{"patternId":"unusedcode_UnusedModifier","enabled":true},{"patternId":"Style_MethodName","enabled":true},{"patternId":"Metrics_CyclomaticComplexity","enabled":true},{"patternId":"Lint_DuplicateMethods","enabled":true},{"patternId":"Style_Lambda","enabled":true},{"patternId":"Lint_UselessSetterCall","enabled":true},{"patternId":"Style_VariableName","enabled":true},{"patternId":"Lint_AmbiguousOperator","enabled":true},{"patternId":"Style_LeadingCommentSpace","enabled":true},{"patternId":"Style_CaseEquality","enabled":true},{"patternId":"Lint_StringConversionInInterpolation","enabled":true},{"patternId":"Performance_ReverseEach","enabled":true},{"patternId":"Lint_LiteralInCondition","enabled":true},{"patternId":"Performance_Sample","enabled":true},{"patternId":"Style_NonNilCheck","enabled":true},{"patternId":"Lint_RescueException","enabled":true},{"patternId":"Lint_UselessElseWithoutRescue","enabled":true},{"patternId":"Style_ConstantName","enabled":true},{"patternId":"Lint_LiteralInInterpolation","enabled":true},{"patternId":"Lint_NestedMethodDefinition","enabled":true},{"patternId":"Style_DoubleNegation","enabled":true},{"patternId":"Lint_SpaceBeforeFirstArg","enabled":true},{"patternId":"Lint_Debugger","enabled":true},{"patternId":"Style_ClassVars","enabled":true},{"patternId":"Lint_EmptyEnsure","enabled":true},{"patternId":"Style_MultilineBlockLayout","enabled":true},{"patternId":"Lint_UnusedBlockArgument","enabled":true},{"patternId":"Lint_UselessAccessModifier","enabled":true},{"patternId":"Performance_Size","enabled":true},{"patternId":"Lint_EachWithObjectArgument","enabled":true},{"patternId":"Style_Alias","enabled":true},{"patternId":"Lint_Loop","enabled":true},{"patternId":"Style_NegatedWhile","enabled":true},{"patternId":"Style_ColonMethodCall","enabled":true},{"patternId":"Lint_AmbiguousRegexpLiteral","enabled":true},{"patternId":"Lint_UnusedMethodArgument","enabled":true},{"patternId":"Style_MultilineIfThen","enabled":true},{"patternId":"Lint_EnsureReturn","enabled":true},{"patternId":"Style_NegatedIf","enabled":true},{"patternId":"Lint_Eval","enabled":true},{"patternId":"Style_NilComparison","enabled":true},{"patternId":"Style_ArrayJoin","enabled":true},{"patternId":"Lint_ConditionPosition","enabled":true},{"patternId":"Lint_UnreachableCode","enabled":true},{"patternId":"Performance_Count","enabled":true},{"patternId":"Lint_EmptyInterpolation","enabled":true},{"patternId":"Style_LambdaCall","enabled":true},{"patternId":"Lint_HandleExceptions","enabled":true},{"patternId":"Lint_ShadowingOuterLocalVariable","enabled":true},{"patternId":"Lint_EndAlignment","enabled":true},{"patternId":"Style_MultilineTernaryOperator","enabled":true},{"patternId":"Style_AutoResourceCleanup","enabled":true},{"patternId":"Lint_ElseLayout","enabled":true},{"patternId":"Style_NestedTernaryOperator","enabled":true},{"patternId":"Style_OneLineConditional","enabled":true},{"patternId":"Style_EmptyElse","enabled":true},{"patternId":"Lint_UselessComparison","enabled":true},{"patternId":"Metrics_PerceivedComplexity","enabled":true},{"patternId":"Style_InfiniteLoop","enabled":true},{"patternId":"Rails_Date","enabled":true},{"patternId":"Style_EvenOdd","enabled":true},{"patternId":"Style_IndentationConsistency","enabled":true},{"patternId":"Style_ModuleFunction","enabled":true},{"patternId":"Lint_UselessAssignment","enabled":true},{"patternId":"Style_EachWithObject","enabled":true},{"patternId":"Performance_Detect","enabled":true},{"patternId":"duplicate_key","enabled":true},{"patternId":"no_interpolation_in_single_quotes","enabled":true},{"patternId":"no_backticks","enabled":true},{"patternId":"no_unnecessary_fat_arrows","enabled":true},{"patternId":"indentation","enabled":true},{"patternId":"ensure_comprehensions","enabled":true},{"patternId":"no_stand_alone_at","enabled":true},{"patternId":"cyclomatic_complexity","enabled":true},{"patternId":"Deserialize","enabled":true},{"patternId":"SymbolDoS","enabled":true},{"patternId":"SkipBeforeFilter","enabled":true},{"patternId":"SanitizeMethods","enabled":true},{"patternId":"SelectTag","enabled":true},{"patternId":"XMLDoS","enabled":true},{"patternId":"SimpleFormat","enabled":true},{"patternId":"Evaluation","enabled":true},{"patternId":"BasicAuth","enabled":true},{"patternId":"JRubyXML","enabled":true},{"patternId":"RenderInline","enabled":true},{"patternId":"YAMLParsing","enabled":true},{"patternId":"Redirect","enabled":true},{"patternId":"UnsafeReflection","enabled":true},{"patternId":"SSLVerify","enabled":true},{"patternId":"HeaderDoS","enabled":true},{"patternId":"TranslateBug","enabled":true},{"patternId":"Execute","enabled":true},{"patternId":"JSONParsing","enabled":true},{"patternId":"LinkTo","enabled":true},{"patternId":"FileDisclosure","enabled":true},{"patternId":"SafeBufferManipulation","enabled":true},{"patternId":"ModelAttributes","enabled":true},{"patternId":"ResponseSplitting","enabled":true},{"patternId":"DigestDoS","enabled":true},{"patternId":"Send","enabled":true},{"patternId":"MailTo","enabled":true},{"patternId":"SymbolDoSCVE","enabled":true},{"patternId":"StripTags","enabled":true},{"patternId":"MassAssignment","enabled":true},{"patternId":"RegexDoS","enabled":true},{"patternId":"SelectVulnerability","enabled":true},{"patternId":"FileAccess","enabled":true},{"patternId":"ContentTag","enabled":true},{"patternId":"SessionSettings","enabled":true},{"patternId":"FilterSkipping","enabled":true},{"patternId":"CreateWith","enabled":true},{"patternId":"JSONEncoding","enabled":true},{"patternId":"SQLCVEs","enabled":true},{"patternId":"ForgerySetting","enabled":true},{"patternId":"QuoteTableName","enabled":true},{"patternId":"I18nXSS","enabled":true},{"patternId":"WithoutProtection","enabled":true},{"patternId":"CrossSiteScripting","enabled":true},{"patternId":"SingleQuotes","enabled":true},{"patternId":"NestedAttributes","enabled":true},{"patternId":"DetailedExceptions","enabled":true},{"patternId":"LinkToHref","enabled":true},{"patternId":"RenderDoS","enabled":true},{"patternId":"ModelSerialize","enabled":true},{"patternId":"SQL","enabled":true},{"patternId":"Render","enabled":true},{"patternId":"UnscopedFind","enabled":true},{"patternId":"ValidationRegex","enabled":true},{"patternId":"EscapeFunction","enabled":true},{"patternId":"Custom_Scala_FieldNamesChecker","enabled":true},{"patternId":"Custom_Scala_ObjDeserialization","enabled":true},{"patternId":"Custom_Scala_RSAPadding","enabled":true},{"patternId":"ESLint_no-extra-boolean-cast","enabled":true},{"patternId":"ESLint_no-iterator","enabled":true},{"patternId":"ESLint_no-invalid-regexp","enabled":true},{"patternId":"ESLint_no-obj-calls","enabled":true},{"patternId":"ESLint_no-sparse-arrays","enabled":true},{"patternId":"ESLint_no-unreachable","enabled":true},{"patternId":"ESLint_no-dupe-keys","enabled":true},{"patternId":"ESLint_no-multi-str","enabled":true},{"patternId":"ESLint_no-extend-native","enabled":true},{"patternId":"ESLint_guard-for-in","enabled":true},{"patternId":"ESLint_no-func-assign","enabled":true},{"patternId":"ESLint_no-extra-semi","enabled":true},{"patternId":"ESLint_camelcase","enabled":true},{"patternId":"ESLint_no-mixed-spaces-and-tabs","enabled":true},{"patternId":"ESLint_no-undef","enabled":true},{"patternId":"ESLint_semi","enabled":true},{"patternId":"ESLint_no-empty-character-class","enabled":true},{"patternId":"ESLint_complexity","enabled":true},{"patternId":"ESLint_no-dupe-class-members","enabled":true},{"patternId":"ESLint_no-debugger","enabled":true},{"patternId":"ESLint_block-scoped-var","enabled":true},{"patternId":"ESLint_no-loop-func","enabled":true},{"patternId":"ESLint_no-use-before-define","enabled":true},{"patternId":"ESLint_no-console","enabled":true},{"patternId":"ESLint_require-yield","enabled":true},{"patternId":"ESLint_no-redeclare","enabled":true},{"patternId":"ESLint_no-undefined","enabled":true},{"patternId":"ESLint_use-isnan","enabled":true},{"patternId":"ESLint_no-control-regex","enabled":true},{"patternId":"ESLint_no-const-assign","enabled":true},{"patternId":"ESLint_no-new","enabled":true},{"patternId":"ESLint_new-cap","enabled":true},{"patternId":"ESLint_no-irregular-whitespace","enabled":true},{"patternId":"ESLint_object-shorthand","enabled":true},{"patternId":"ESLint_no-ex-assign","enabled":true},{"patternId":"ESLint_wrap-iife","enabled":true},{"patternId":"ESLint_arrow-parens","enabled":true},{"patternId":"ESLint_no-constant-condition","enabled":true},{"patternId":"ESLint_no-octal","enabled":true},{"patternId":"ESLint_no-dupe-args","enabled":true},{"patternId":"ESLint_quotes","enabled":true},{"patternId":"ESLint_no-fallthrough","enabled":true},{"patternId":"ESLint_no-delete-var","enabled":true},{"patternId":"ESLint_no-caller","enabled":true},{"patternId":"ESLint_no-cond-assign","enabled":true},{"patternId":"ESLint_no-this-before-super","enabled":true},{"patternId":"ESLint_no-negated-in-lhs","enabled":true},{"patternId":"ESLint_no-inner-declarations","enabled":true},{"patternId":"ESLint_eqeqeq","enabled":true},{"patternId":"ESLint_curly","enabled":true},{"patternId":"ESLint_arrow-spacing","enabled":true},{"patternId":"ESLint_no-empty","enabled":true},{"patternId":"ESLint_no-unused-vars","enabled":true},{"patternId":"ESLint_generator-star-spacing","enabled":true},{"patternId":"ESLint_no-duplicate-case","enabled":true},{"patternId":"ESLint_valid-typeof","enabled":true},{"patternId":"ESLint_no-regex-spaces","enabled":true},{"patternId":"ESLint_no-class-assign","enabled":true},{"patternId":"PyLint_W0221","enabled":true},{"patternId":"PyLint_E0117","enabled":true},{"patternId":"PyLint_E0001","enabled":true},{"patternId":"PyLint_E0241","enabled":true},{"patternId":"PyLint_W0404","enabled":true},{"patternId":"PyLint_E0704","enabled":true},{"patternId":"PyLint_E0703","enabled":true},{"patternId":"PyLint_E0302","enabled":true},{"patternId":"PyLint_W1301","enabled":true},{"patternId":"PyLint_R0201","enabled":true},{"patternId":"PyLint_E0113","enabled":true},{"patternId":"PyLint_W0410","enabled":true},{"patternId":"PyLint_C0123","enabled":true},{"patternId":"PyLint_E0115","enabled":true},{"patternId":"PyLint_E0114","enabled":true},{"patternId":"PyLint_E1126","enabled":true},{"patternId":"PyLint_W0702","enabled":true},{"patternId":"PyLint_W1303","enabled":true},{"patternId":"PyLint_W0622","enabled":true},{"patternId":"PyLint_W0222","enabled":true},{"patternId":"PyLint_W0233","enabled":true},{"patternId":"PyLint_W1305","enabled":true},{"patternId":"PyLint_E1127","enabled":true},{"patternId":"PyLint_E0112","enabled":true},{"patternId":"PyLint_W0611","enabled":true},{"patternId":"PyLint_W0601","enabled":true},{"patternId":"PyLint_W1300","enabled":true},{"patternId":"PyLint_W0124","enabled":true},{"patternId":"PyLint_R0203","enabled":true},{"patternId":"PyLint_E0236","enabled":true},{"patternId":"PyLint_W0612","enabled":true},{"patternId":"PyLint_W0604","enabled":true},{"patternId":"PyLint_W0705","enabled":true},{"patternId":"PyLint_E0238","enabled":true},{"patternId":"PyLint_W0602","enabled":true},{"patternId":"PyLint_R0102","enabled":true},{"patternId":"PyLint_R0202","enabled":true},{"patternId":"PyLint_E0240","enabled":true},{"patternId":"PyLint_W0623","enabled":true},{"patternId":"PyLint_W0711","enabled":true},{"patternId":"PyLint_E0116","enabled":true},{"patternId":"PyLint_E0239","enabled":true},{"patternId":"PyLint_E1132","enabled":true},{"patternId":"PyLint_W1307","enabled":true},{"patternId":"PyLint_C0200","enabled":true},{"patternId":"PyLint_E0301","enabled":true},{"patternId":"PyLint_W1306","enabled":true},{"patternId":"PyLint_W1302","enabled":true},{"patternId":"PyLint_E0110","enabled":true},{"patternId":"PyLint_E1125","enabled":true}]} \ No newline at end of file +{"patterns":[{"patternId":"Custom_Javascript_Scopes","enabled":true},{"patternId":"Custom_Javascript_EvalWith","enabled":true},{"patternId":"Custom_Javascript_TryCatch","enabled":true},{"patternId":"Custom_Scala_NonFatal","enabled":true},{"patternId":"bitwise","enabled":true},{"patternId":"maxparams","enabled":true},{"patternId":"CSSLint_universal_selector","enabled":true},{"patternId":"CSSLint_unqualified_attributes","enabled":true},{"patternId":"CSSLint_zero_units","enabled":true},{"patternId":"CSSLint_overqualified_elements","enabled":true},{"patternId":"CSSLint_shorthand","enabled":true},{"patternId":"CSSLint_duplicate_background_images","enabled":true},{"patternId":"CSSLint_box_model","enabled":true},{"patternId":"CSSLint_compatible_vendor_prefixes","enabled":true},{"patternId":"CSSLint_display_property_grouping","enabled":true},{"patternId":"CSSLint_duplicate_properties","enabled":true},{"patternId":"CSSLint_empty_rules","enabled":true},{"patternId":"CSSLint_errors","enabled":true},{"patternId":"CSSLint_gradients","enabled":true},{"patternId":"CSSLint_important","enabled":true},{"patternId":"CSSLint_known_properties","enabled":true},{"patternId":"CSSLint_text_indent","enabled":true},{"patternId":"CSSLint_unique_headings","enabled":true},{"patternId":"PyLint_E0100","enabled":true},{"patternId":"PyLint_E0101","enabled":true},{"patternId":"PyLint_E0102","enabled":true},{"patternId":"PyLint_E0103","enabled":true},{"patternId":"PyLint_E0104","enabled":true},{"patternId":"PyLint_E0105","enabled":true},{"patternId":"PyLint_E0106","enabled":true},{"patternId":"PyLint_E0107","enabled":true},{"patternId":"PyLint_E0108","enabled":true},{"patternId":"PyLint_E0202","enabled":true},{"patternId":"PyLint_E0203","enabled":true},{"patternId":"PyLint_E0211","enabled":true},{"patternId":"PyLint_E0601","enabled":true},{"patternId":"PyLint_E0603","enabled":true},{"patternId":"PyLint_E0604","enabled":true},{"patternId":"PyLint_E0701","enabled":true},{"patternId":"PyLint_E0702","enabled":true},{"patternId":"PyLint_E0710","enabled":true},{"patternId":"PyLint_E0711","enabled":true},{"patternId":"PyLint_E0712","enabled":true},{"patternId":"PyLint_E1003","enabled":true},{"patternId":"PyLint_E1102","enabled":true},{"patternId":"PyLint_E1111","enabled":true},{"patternId":"PyLint_E1120","enabled":true},{"patternId":"PyLint_E1121","enabled":true},{"patternId":"PyLint_E1123","enabled":true},{"patternId":"PyLint_E1124","enabled":true},{"patternId":"PyLint_E1200","enabled":true},{"patternId":"PyLint_E1201","enabled":true},{"patternId":"PyLint_E1205","enabled":true},{"patternId":"PyLint_E1206","enabled":true},{"patternId":"PyLint_E1300","enabled":true},{"patternId":"PyLint_E1301","enabled":true},{"patternId":"PyLint_E1302","enabled":true},{"patternId":"PyLint_E1303","enabled":true},{"patternId":"PyLint_E1304","enabled":true},{"patternId":"PyLint_E1305","enabled":true},{"patternId":"PyLint_E1306","enabled":true},{"patternId":"rulesets-codesize.xml-CyclomaticComplexity","enabled":true},{"patternId":"rulesets-codesize.xml-NPathComplexity","enabled":true},{"patternId":"rulesets-codesize.xml-ExcessiveMethodLength","enabled":true},{"patternId":"rulesets-codesize.xml-ExcessiveClassLength","enabled":true},{"patternId":"rulesets-codesize.xml-ExcessiveParameterList","enabled":true},{"patternId":"rulesets-codesize.xml-ExcessivePublicCount","enabled":true},{"patternId":"rulesets-codesize.xml-TooManyFields","enabled":true},{"patternId":"rulesets-codesize.xml-TooManyMethods","enabled":true},{"patternId":"rulesets-codesize.xml-ExcessiveClassComplexity","enabled":true},{"patternId":"rulesets-controversial.xml-Superglobals","enabled":true},{"patternId":"rulesets-design.xml-ExitExpression","enabled":true},{"patternId":"rulesets-design.xml-EvalExpression","enabled":true},{"patternId":"rulesets-design.xml-GotoStatement","enabled":true},{"patternId":"rulesets-design.xml-NumberOfChildren","enabled":true},{"patternId":"rulesets-design.xml-DepthOfInheritance","enabled":true},{"patternId":"rulesets-unusedcode.xml-UnusedPrivateField","enabled":true},{"patternId":"rulesets-unusedcode.xml-UnusedLocalVariable","enabled":true},{"patternId":"rulesets-unusedcode.xml-UnusedPrivateMethod","enabled":true},{"patternId":"rulesets-unusedcode.xml-UnusedFormalParameter","enabled":true},{"patternId":"PyLint_C0303","enabled":true},{"patternId":"PyLint_C1001","enabled":true},{"patternId":"rulesets-naming.xml-ShortVariable","enabled":true},{"patternId":"rulesets-naming.xml-LongVariable","enabled":true},{"patternId":"rulesets-naming.xml-ShortMethodName","enabled":true},{"patternId":"rulesets-naming.xml-ConstantNamingConventions","enabled":true},{"patternId":"rulesets-naming.xml-BooleanGetMethodName","enabled":true},{"patternId":"PyLint_W0101","enabled":true},{"patternId":"PyLint_W0102","enabled":true},{"patternId":"PyLint_W0104","enabled":true},{"patternId":"PyLint_W0105","enabled":true},{"patternId":"Custom_Scala_GetCalls","enabled":true},{"patternId":"ScalaStyle_EqualsHashCodeChecker","enabled":true},{"patternId":"ScalaStyle_ParameterNumberChecker","enabled":true},{"patternId":"ScalaStyle_ReturnChecker","enabled":true},{"patternId":"ScalaStyle_NullChecker","enabled":true},{"patternId":"ScalaStyle_NoCloneChecker","enabled":true},{"patternId":"ScalaStyle_NoFinalizeChecker","enabled":true},{"patternId":"ScalaStyle_CovariantEqualsChecker","enabled":true},{"patternId":"ScalaStyle_StructuralTypeChecker","enabled":true},{"patternId":"ScalaStyle_MethodLengthChecker","enabled":true},{"patternId":"ScalaStyle_NumberOfMethodsInTypeChecker","enabled":true},{"patternId":"ScalaStyle_WhileChecker","enabled":true},{"patternId":"ScalaStyle_VarFieldChecker","enabled":true},{"patternId":"ScalaStyle_VarLocalChecker","enabled":true},{"patternId":"ScalaStyle_RedundantIfChecker","enabled":true},{"patternId":"ScalaStyle_DeprecatedJavaChecker","enabled":true},{"patternId":"ScalaStyle_EmptyClassChecker","enabled":true},{"patternId":"ScalaStyle_NotImplementedErrorUsage","enabled":true},{"patternId":"Custom_Scala_GroupImports","enabled":true},{"patternId":"Custom_Scala_ReservedKeywords","enabled":true},{"patternId":"Custom_Scala_ElseIf","enabled":true},{"patternId":"Custom_Scala_CallByNameAsLastArguments","enabled":true},{"patternId":"Custom_Scala_WildcardImportOnMany","enabled":true},{"patternId":"Custom_Scala_UtilTryForTryCatch","enabled":true},{"patternId":"Custom_Scala_ProhibitObjectName","enabled":true},{"patternId":"Custom_Scala_ImportsAtBeginningOfPackage","enabled":true},{"patternId":"Custom_Scala_NameResultsAndParameters","enabled":true},{"patternId":"Custom_Scala_IncompletePatternMatching","enabled":true},{"patternId":"Custom_Scala_UsefulTypeAlias","enabled":true},{"patternId":"Custom_Scala_JavaThreads","enabled":true},{"patternId":"Custom_Scala_DirectPromiseCreation","enabled":true},{"patternId":"Custom_Scala_StructuralTypes","enabled":true},{"patternId":"Custom_Scala_CollectionLastHead","enabled":true},{"patternId":"PyLint_W0106","enabled":true},{"patternId":"PyLint_W0107","enabled":true},{"patternId":"PyLint_W0108","enabled":true},{"patternId":"PyLint_W0109","enabled":true},{"patternId":"PyLint_W0110","enabled":true},{"patternId":"PyLint_W0120","enabled":true},{"patternId":"PyLint_W0122","enabled":true},{"patternId":"PyLint_W0150","enabled":true},{"patternId":"PyLint_W0199","enabled":true},{"patternId":"rulesets-cleancode.xml-ElseExpression","enabled":true},{"patternId":"rulesets-cleancode.xml-StaticAccess","enabled":true},{"patternId":"ScalaStyle_NonASCIICharacterChecker","enabled":true},{"patternId":"ScalaStyle_FieldNamesChecker","enabled":true},{"patternId":"Custom_Scala_WithNameCalls","enabled":true},{"patternId":"strictexception_AvoidRethrowingException","enabled":true},{"patternId":"strings_AppendCharacterWithChar","enabled":true},{"patternId":"braces_IfElseStmtsMustUseBraces","enabled":true},{"patternId":"basic_AvoidDecimalLiteralsInBigDecimalConstructor","enabled":true},{"patternId":"basic_CheckSkipResult","enabled":true},{"patternId":"javabeans_MissingSerialVersionUID","enabled":true},{"patternId":"migrating_ShortInstantiation","enabled":true},{"patternId":"design_AvoidInstanceofChecksInCatchClause","enabled":true},{"patternId":"migrating_ReplaceEnumerationWithIterator","enabled":true},{"patternId":"j2ee_DoNotCallSystemExit","enabled":true},{"patternId":"unusedcode_UnusedLocalVariable","enabled":true},{"patternId":"strings_InefficientStringBuffering","enabled":true},{"patternId":"basic_DontUseFloatTypeForLoopIndices","enabled":true},{"patternId":"basic_AvoidBranchingStatementAsLastInLoop","enabled":true},{"patternId":"migrating_JUnit4TestShouldUseTestAnnotation","enabled":true},{"patternId":"optimizations_AddEmptyString","enabled":true},{"patternId":"logging-jakarta-commons_ProperLogger","enabled":true},{"patternId":"optimizations_RedundantFieldInitializer","enabled":true},{"patternId":"logging-java_AvoidPrintStackTrace","enabled":true},{"patternId":"empty_EmptyFinallyBlock","enabled":true},{"patternId":"design_CompareObjectsWithEquals","enabled":true},{"patternId":"basic_ClassCastExceptionWithToArray","enabled":true},{"patternId":"strictexception_DoNotExtendJavaLangError","enabled":true},{"patternId":"junit_UnnecessaryBooleanAssertion","enabled":true},{"patternId":"design_SimplifyBooleanExpressions","enabled":true},{"patternId":"basic_ForLoopShouldBeWhileLoop","enabled":true},{"patternId":"basic_BigIntegerInstantiation","enabled":true},{"patternId":"optimizations_UseArrayListInsteadOfVector","enabled":true},{"patternId":"optimizations_UnnecessaryWrapperObjectCreation","enabled":true},{"patternId":"strings_StringBufferInstantiationWithChar","enabled":true},{"patternId":"basic_JumbledIncrementer","enabled":true},{"patternId":"design_SwitchStmtsShouldHaveDefault","enabled":true},{"patternId":"strictexception_AvoidThrowingRawExceptionTypes","enabled":true},{"patternId":"migrating_LongInstantiation","enabled":true},{"patternId":"design_SimplifyBooleanReturns","enabled":true},{"patternId":"empty_EmptyInitializer","enabled":true},{"patternId":"design_FieldDeclarationsShouldBeAtStartOfClass","enabled":true},{"patternId":"unnecessary_UnnecessaryConversionTemporary","enabled":true},{"patternId":"design_AvoidProtectedFieldInFinalClass","enabled":true},{"patternId":"junit_UseAssertTrueInsteadOfAssertEquals","enabled":true},{"patternId":"naming_PackageCase","enabled":true},{"patternId":"migrating_JUnitUseExpected","enabled":true},{"patternId":"controversial_UnnecessaryConstructor","enabled":true},{"patternId":"naming_MethodNamingConventions","parameters":{"violationSuppressRegex":"\"\"","violationSuppressXPath":"\"//MethodDeclarator[contains(@Image, 'test')]\""},"enabled":true},{"patternId":"design_DefaultLabelNotLastInSwitchStmt","enabled":true},{"patternId":"basic_UnconditionalIfStatement","enabled":true},{"patternId":"design_SingularField","enabled":true},{"patternId":"design_AssignmentToNonFinalStatic","enabled":true},{"patternId":"braces_WhileLoopsMustUseBraces","enabled":true},{"patternId":"logging-java_SystemPrintln","enabled":true},{"patternId":"strings_UseStringBufferLength","enabled":true},{"patternId":"controversial_AvoidUsingNativeCode","enabled":true},{"patternId":"strictexception_AvoidLosingExceptionInformation","enabled":true},{"patternId":"imports_ImportFromSamePackage","enabled":true},{"patternId":"finalizers_AvoidCallingFinalize","enabled":true},{"patternId":"finalizers_FinalizeOverloaded","enabled":true},{"patternId":"naming_ClassNamingConventions","enabled":true},{"patternId":"logging-java_LoggerIsNotStaticFinal","enabled":true},{"patternId":"finalizers_FinalizeOnlyCallsSuperFinalize","enabled":true},{"patternId":"unnecessary_UselessOverridingMethod","enabled":true},{"patternId":"naming_SuspiciousConstantFieldName","enabled":true},{"patternId":"design_OptimizableToArrayCall","enabled":true},{"patternId":"imports_UnnecessaryFullyQualifiedName","enabled":true},{"patternId":"migrating_ReplaceHashtableWithMap","enabled":true},{"patternId":"unusedcode_UnusedPrivateField","enabled":true},{"patternId":"strings_UnnecessaryCaseChange","enabled":true},{"patternId":"migrating_IntegerInstantiation","enabled":true},{"patternId":"design_NonStaticInitializer","enabled":true},{"patternId":"design_MissingBreakInSwitch","enabled":true},{"patternId":"design_AvoidReassigningParameters","enabled":true},{"patternId":"basic_AvoidThreadGroup","enabled":true},{"patternId":"empty_EmptyCatchBlock","parameters":{"allowCommentedBlocks":"true"},"enabled":true},{"patternId":"codesize_ExcessiveParameterList","parameters":{"minimum":"8","violationSuppressRegex":"\"\"","violationSuppressXPath":"\"\""},"enabled":true},{"patternId":"naming_SuspiciousHashcodeMethodName","enabled":true},{"patternId":"migrating_JUnit4TestShouldUseBeforeAnnotation","enabled":true},{"patternId":"design_UncommentedEmptyMethodBody","enabled":true},{"patternId":"basic_BrokenNullCheck","enabled":true},{"patternId":"strings_ConsecutiveLiteralAppends","enabled":true},{"patternId":"strings_StringInstantiation","enabled":true},{"patternId":"design_EqualsNull","enabled":true},{"patternId":"basic_OverrideBothEqualsAndHashcode","enabled":true},{"patternId":"design_InstantiationToGetClass","enabled":true},{"patternId":"basic_BooleanInstantiation","enabled":true},{"patternId":"strings_AvoidStringBufferField","enabled":true},{"patternId":"basic_ReturnFromFinallyBlock","enabled":true},{"patternId":"empty_EmptyTryBlock","enabled":true},{"patternId":"naming_SuspiciousEqualsMethodName","enabled":true},{"patternId":"basic_ExtendsObject","enabled":true},{"patternId":"strings_UselessStringValueOf","enabled":true},{"patternId":"design_UnsynchronizedStaticDateFormatter","enabled":true},{"patternId":"design_UseCollectionIsEmpty","enabled":true},{"patternId":"controversial_AvoidFinalLocalVariable","enabled":true},{"patternId":"strictexception_AvoidThrowingNullPointerException","enabled":true},{"patternId":"design_AvoidProtectedMethodInFinalClassNotExtending","enabled":true},{"patternId":"optimizations_PrematureDeclaration","enabled":true},{"patternId":"empty_EmptySwitchStatements","enabled":true},{"patternId":"basic_MisplacedNullCheck","enabled":true},{"patternId":"optimizations_UseStringBufferForStringAppends","enabled":true},{"patternId":"strings_StringToString","enabled":true},{"patternId":"naming_MethodWithSameNameAsEnclosingClass","enabled":true},{"patternId":"migrating_ReplaceVectorWithList","enabled":true},{"patternId":"imports_UnusedImports","enabled":true},{"patternId":"unnecessary_UnnecessaryFinalModifier","enabled":true},{"patternId":"basic_AvoidMultipleUnaryOperators","enabled":true},{"patternId":"junit_SimplifyBooleanAssertion","enabled":true},{"patternId":"unnecessary_UselessParentheses","enabled":true},{"patternId":"design_IdempotentOperations","enabled":true},{"patternId":"braces_IfStmtsMustUseBraces","enabled":true},{"patternId":"strings_UseIndexOfChar","enabled":true},{"patternId":"naming_NoPackage","enabled":true},{"patternId":"finalizers_FinalizeDoesNotCallSuperFinalize","enabled":true},{"patternId":"design_UseVarargs","enabled":true},{"patternId":"unusedcode_UnusedFormalParameter","enabled":true},{"patternId":"design_ReturnEmptyArrayRatherThanNull","enabled":true},{"patternId":"junit_UseAssertNullInsteadOfAssertTrue","enabled":true},{"patternId":"design_UseUtilityClass","enabled":true},{"patternId":"design_AvoidDeeplyNestedIfStmts","enabled":true},{"patternId":"empty_EmptyStatementNotInLoop","enabled":true},{"patternId":"junit_UseAssertSameInsteadOfAssertTrue","enabled":true},{"patternId":"braces_ForLoopsMustUseBraces","enabled":true},{"patternId":"controversial_DoNotCallGarbageCollectionExplicitly","enabled":true},{"patternId":"naming_GenericsNaming","enabled":true},{"patternId":"strings_UseEqualsToCompareStrings","enabled":true},{"patternId":"optimizations_AvoidArrayLoops","enabled":true},{"patternId":"empty_EmptyStaticInitializer","enabled":true},{"patternId":"design_UncommentedEmptyConstructor","enabled":true},{"patternId":"empty_EmptyStatementBlock","enabled":true},{"patternId":"basic_CollapsibleIfStatements","enabled":true},{"patternId":"design_FinalFieldCouldBeStatic","enabled":true},{"patternId":"logging-java_MoreThanOneLogger","enabled":true},{"patternId":"codesize_ExcessiveClassLength","enabled":true},{"patternId":"design_ImmutableField","enabled":true},{"patternId":"controversial_OneDeclarationPerLine","enabled":true},{"patternId":"empty_EmptyWhileStmt","enabled":true},{"patternId":"unnecessary_UnnecessaryReturn","enabled":true},{"patternId":"strings_InefficientEmptyStringCheck","enabled":true},{"patternId":"design_UseNotifyAllInsteadOfNotify","enabled":true},{"patternId":"strictexception_DoNotThrowExceptionInFinally","enabled":true},{"patternId":"junit_UseAssertEqualsInsteadOfAssertTrue","enabled":true},{"patternId":"typeresolution_CloneMethodMustImplementCloneable","enabled":true},{"patternId":"codesize_NPathComplexity","enabled":true},{"patternId":"imports_DontImportJavaLang","enabled":true},{"patternId":"empty_EmptySynchronizedBlock","enabled":true},{"patternId":"migrating_JUnit4TestShouldUseAfterAnnotation","enabled":true},{"patternId":"design_AvoidConstantsInterface","enabled":true},{"patternId":"unnecessary_UselessOperationOnImmutable","enabled":true},{"patternId":"design_PositionLiteralsFirstInComparisons","enabled":true},{"patternId":"migrating_ByteInstantiation","enabled":true},{"patternId":"junit_JUnitSpelling","enabled":true},{"patternId":"finalizers_EmptyFinalizer","enabled":true},{"patternId":"design_NonCaseLabelInSwitchStatement","enabled":true},{"patternId":"android_DoNotHardCodeSDCard","enabled":true},{"patternId":"design_LogicInversion","enabled":true},{"patternId":"unusedcode_UnusedPrivateMethod","enabled":true},{"patternId":"naming_AvoidDollarSigns","enabled":true},{"patternId":"finalizers_FinalizeShouldBeProtected","enabled":true},{"patternId":"clone_ProperCloneImplementation","enabled":true},{"patternId":"basic_CheckResultSet","enabled":true},{"patternId":"controversial_AvoidPrefixingMethodParameters","enabled":true},{"patternId":"migrating_JUnit4SuitesShouldUseSuiteAnnotation","enabled":true},{"patternId":"empty_EmptyIfStmt","enabled":true},{"patternId":"basic_DontCallThreadRun","enabled":true},{"patternId":"junit_JUnitStaticSuite","enabled":true},{"patternId":"optimizations_UseArraysAsList","enabled":true},{"patternId":"design_MissingStaticMethodInNonInstantiatableClass","enabled":true},{"patternId":"unusedcode_UnusedModifier","enabled":true},{"patternId":"Style_MethodName","enabled":true},{"patternId":"Metrics_CyclomaticComplexity","enabled":true},{"patternId":"Lint_DuplicateMethods","enabled":true},{"patternId":"Style_Lambda","enabled":true},{"patternId":"Lint_UselessSetterCall","enabled":true},{"patternId":"Style_VariableName","enabled":true},{"patternId":"Lint_AmbiguousOperator","enabled":true},{"patternId":"Style_LeadingCommentSpace","enabled":true},{"patternId":"Style_CaseEquality","enabled":true},{"patternId":"Lint_StringConversionInInterpolation","enabled":true},{"patternId":"Performance_ReverseEach","enabled":true},{"patternId":"Lint_LiteralInCondition","enabled":true},{"patternId":"Performance_Sample","enabled":true},{"patternId":"Style_NonNilCheck","enabled":true},{"patternId":"Lint_RescueException","enabled":true},{"patternId":"Lint_UselessElseWithoutRescue","enabled":true},{"patternId":"Style_ConstantName","enabled":true},{"patternId":"Lint_LiteralInInterpolation","enabled":true},{"patternId":"Lint_NestedMethodDefinition","enabled":true},{"patternId":"Style_DoubleNegation","enabled":true},{"patternId":"Lint_SpaceBeforeFirstArg","enabled":true},{"patternId":"Lint_Debugger","enabled":true},{"patternId":"Style_ClassVars","enabled":true},{"patternId":"Lint_EmptyEnsure","enabled":true},{"patternId":"Style_MultilineBlockLayout","enabled":true},{"patternId":"Lint_UnusedBlockArgument","enabled":true},{"patternId":"Lint_UselessAccessModifier","enabled":true},{"patternId":"Performance_Size","enabled":true},{"patternId":"Lint_EachWithObjectArgument","enabled":true},{"patternId":"Style_Alias","enabled":true},{"patternId":"Lint_Loop","enabled":true},{"patternId":"Style_NegatedWhile","enabled":true},{"patternId":"Style_ColonMethodCall","enabled":true},{"patternId":"Lint_AmbiguousRegexpLiteral","enabled":true},{"patternId":"Lint_UnusedMethodArgument","enabled":true},{"patternId":"Style_MultilineIfThen","enabled":true},{"patternId":"Lint_EnsureReturn","enabled":true},{"patternId":"Style_NegatedIf","enabled":true},{"patternId":"Lint_Eval","enabled":true},{"patternId":"Style_NilComparison","enabled":true},{"patternId":"Style_ArrayJoin","enabled":true},{"patternId":"Lint_ConditionPosition","enabled":true},{"patternId":"Lint_UnreachableCode","enabled":true},{"patternId":"Performance_Count","enabled":true},{"patternId":"Lint_EmptyInterpolation","enabled":true},{"patternId":"Style_LambdaCall","enabled":true},{"patternId":"Lint_HandleExceptions","enabled":true},{"patternId":"Lint_ShadowingOuterLocalVariable","enabled":true},{"patternId":"Lint_EndAlignment","enabled":true},{"patternId":"Style_MultilineTernaryOperator","enabled":true},{"patternId":"Style_AutoResourceCleanup","enabled":true},{"patternId":"Lint_ElseLayout","enabled":true},{"patternId":"Style_NestedTernaryOperator","enabled":true},{"patternId":"Style_OneLineConditional","enabled":true},{"patternId":"Style_EmptyElse","enabled":true},{"patternId":"Lint_UselessComparison","enabled":true},{"patternId":"Metrics_PerceivedComplexity","enabled":true},{"patternId":"Style_InfiniteLoop","enabled":true},{"patternId":"Rails_Date","enabled":true},{"patternId":"Style_EvenOdd","enabled":true},{"patternId":"Style_IndentationConsistency","enabled":true},{"patternId":"Style_ModuleFunction","enabled":true},{"patternId":"Lint_UselessAssignment","enabled":true},{"patternId":"Style_EachWithObject","enabled":true},{"patternId":"Performance_Detect","enabled":true},{"patternId":"duplicate_key","enabled":true},{"patternId":"no_interpolation_in_single_quotes","enabled":true},{"patternId":"no_backticks","enabled":true},{"patternId":"no_unnecessary_fat_arrows","enabled":true},{"patternId":"indentation","enabled":true},{"patternId":"ensure_comprehensions","enabled":true},{"patternId":"no_stand_alone_at","enabled":true},{"patternId":"cyclomatic_complexity","enabled":true},{"patternId":"Deserialize","enabled":true},{"patternId":"SymbolDoS","enabled":true},{"patternId":"SkipBeforeFilter","enabled":true},{"patternId":"SanitizeMethods","enabled":true},{"patternId":"SelectTag","enabled":true},{"patternId":"XMLDoS","enabled":true},{"patternId":"SimpleFormat","enabled":true},{"patternId":"Evaluation","enabled":true},{"patternId":"BasicAuth","enabled":true},{"patternId":"JRubyXML","enabled":true},{"patternId":"RenderInline","enabled":true},{"patternId":"YAMLParsing","enabled":true},{"patternId":"Redirect","enabled":true},{"patternId":"UnsafeReflection","enabled":true},{"patternId":"SSLVerify","enabled":true},{"patternId":"HeaderDoS","enabled":true},{"patternId":"TranslateBug","enabled":true},{"patternId":"Execute","enabled":true},{"patternId":"JSONParsing","enabled":true},{"patternId":"LinkTo","enabled":true},{"patternId":"FileDisclosure","enabled":true},{"patternId":"SafeBufferManipulation","enabled":true},{"patternId":"ModelAttributes","enabled":true},{"patternId":"ResponseSplitting","enabled":true},{"patternId":"DigestDoS","enabled":true},{"patternId":"Send","enabled":true},{"patternId":"MailTo","enabled":true},{"patternId":"SymbolDoSCVE","enabled":true},{"patternId":"StripTags","enabled":true},{"patternId":"MassAssignment","enabled":true},{"patternId":"RegexDoS","enabled":true},{"patternId":"SelectVulnerability","enabled":true},{"patternId":"FileAccess","enabled":true},{"patternId":"ContentTag","enabled":true},{"patternId":"SessionSettings","enabled":true},{"patternId":"FilterSkipping","enabled":true},{"patternId":"CreateWith","enabled":true},{"patternId":"JSONEncoding","enabled":true},{"patternId":"SQLCVEs","enabled":true},{"patternId":"ForgerySetting","enabled":true},{"patternId":"QuoteTableName","enabled":true},{"patternId":"I18nXSS","enabled":true},{"patternId":"WithoutProtection","enabled":true},{"patternId":"CrossSiteScripting","enabled":true},{"patternId":"SingleQuotes","enabled":true},{"patternId":"NestedAttributes","enabled":true},{"patternId":"DetailedExceptions","enabled":true},{"patternId":"LinkToHref","enabled":true},{"patternId":"RenderDoS","enabled":true},{"patternId":"ModelSerialize","enabled":true},{"patternId":"SQL","enabled":true},{"patternId":"Render","enabled":true},{"patternId":"UnscopedFind","enabled":true},{"patternId":"ValidationRegex","enabled":true},{"patternId":"EscapeFunction","enabled":true},{"patternId":"Custom_Scala_FieldNamesChecker","enabled":true},{"patternId":"Custom_Scala_ObjDeserialization","enabled":true},{"patternId":"Custom_Scala_RSAPadding","enabled":true},{"patternId":"ESLint_no-extra-boolean-cast","enabled":true},{"patternId":"ESLint_no-iterator","enabled":true},{"patternId":"ESLint_no-invalid-regexp","enabled":true},{"patternId":"ESLint_no-obj-calls","enabled":true},{"patternId":"ESLint_no-sparse-arrays","enabled":true},{"patternId":"ESLint_no-unreachable","enabled":true},{"patternId":"ESLint_no-dupe-keys","enabled":true},{"patternId":"ESLint_no-multi-str","enabled":true},{"patternId":"ESLint_no-extend-native","enabled":true},{"patternId":"ESLint_guard-for-in","enabled":true},{"patternId":"ESLint_no-func-assign","enabled":true},{"patternId":"ESLint_no-extra-semi","enabled":true},{"patternId":"ESLint_camelcase","enabled":true},{"patternId":"ESLint_no-mixed-spaces-and-tabs","enabled":true},{"patternId":"ESLint_no-undef","enabled":true},{"patternId":"ESLint_semi","enabled":true},{"patternId":"ESLint_no-empty-character-class","enabled":true},{"patternId":"ESLint_complexity","enabled":true},{"patternId":"ESLint_no-dupe-class-members","enabled":true},{"patternId":"ESLint_no-debugger","enabled":true},{"patternId":"ESLint_block-scoped-var","enabled":true},{"patternId":"ESLint_no-loop-func","enabled":true},{"patternId":"ESLint_no-use-before-define","enabled":true},{"patternId":"ESLint_no-console","enabled":true},{"patternId":"ESLint_require-yield","enabled":true},{"patternId":"ESLint_no-redeclare","enabled":true},{"patternId":"ESLint_no-undefined","enabled":true},{"patternId":"ESLint_use-isnan","enabled":true},{"patternId":"ESLint_no-control-regex","enabled":true},{"patternId":"ESLint_no-const-assign","enabled":true},{"patternId":"ESLint_no-new","enabled":true},{"patternId":"ESLint_new-cap","enabled":true},{"patternId":"ESLint_no-irregular-whitespace","enabled":true},{"patternId":"ESLint_object-shorthand","enabled":true},{"patternId":"ESLint_no-ex-assign","enabled":true},{"patternId":"ESLint_wrap-iife","enabled":true},{"patternId":"ESLint_arrow-parens","enabled":true},{"patternId":"ESLint_no-constant-condition","enabled":true},{"patternId":"ESLint_no-octal","enabled":true},{"patternId":"ESLint_no-dupe-args","enabled":true},{"patternId":"ESLint_quotes","enabled":true},{"patternId":"ESLint_no-fallthrough","enabled":true},{"patternId":"ESLint_no-delete-var","enabled":true},{"patternId":"ESLint_no-caller","enabled":true},{"patternId":"ESLint_no-cond-assign","enabled":true},{"patternId":"ESLint_no-this-before-super","enabled":true},{"patternId":"ESLint_no-negated-in-lhs","enabled":true},{"patternId":"ESLint_no-inner-declarations","enabled":true},{"patternId":"ESLint_eqeqeq","enabled":true},{"patternId":"ESLint_curly","enabled":true},{"patternId":"ESLint_arrow-spacing","enabled":true},{"patternId":"ESLint_no-empty","enabled":true},{"patternId":"ESLint_no-unused-vars","enabled":true},{"patternId":"ESLint_generator-star-spacing","enabled":true},{"patternId":"ESLint_no-duplicate-case","enabled":true},{"patternId":"ESLint_valid-typeof","enabled":true},{"patternId":"ESLint_no-regex-spaces","enabled":true},{"patternId":"ESLint_no-class-assign","enabled":true},{"patternId":"PyLint_W0221","enabled":true},{"patternId":"PyLint_E0117","enabled":true},{"patternId":"PyLint_E0001","enabled":true},{"patternId":"PyLint_E0241","enabled":true},{"patternId":"PyLint_W0404","enabled":true},{"patternId":"PyLint_E0704","enabled":true},{"patternId":"PyLint_E0703","enabled":true},{"patternId":"PyLint_E0302","enabled":true},{"patternId":"PyLint_W1301","enabled":true},{"patternId":"PyLint_R0201","enabled":true},{"patternId":"PyLint_E0113","enabled":true},{"patternId":"PyLint_W0410","enabled":true},{"patternId":"PyLint_C0123","enabled":true},{"patternId":"PyLint_E0115","enabled":true},{"patternId":"PyLint_E0114","enabled":true},{"patternId":"PyLint_E1126","enabled":true},{"patternId":"PyLint_W0702","enabled":true},{"patternId":"PyLint_W1303","enabled":true},{"patternId":"PyLint_W0622","enabled":true},{"patternId":"PyLint_W0222","enabled":true},{"patternId":"PyLint_W0233","enabled":true},{"patternId":"PyLint_W1305","enabled":true},{"patternId":"PyLint_E1127","enabled":true},{"patternId":"PyLint_E0112","enabled":true},{"patternId":"PyLint_W0611","enabled":true},{"patternId":"PyLint_W0601","enabled":true},{"patternId":"PyLint_W1300","enabled":true},{"patternId":"PyLint_W0124","enabled":true},{"patternId":"PyLint_R0203","enabled":true},{"patternId":"PyLint_E0236","enabled":true},{"patternId":"PyLint_W0612","enabled":true},{"patternId":"PyLint_W0604","enabled":true},{"patternId":"PyLint_W0705","enabled":true},{"patternId":"PyLint_E0238","enabled":true},{"patternId":"PyLint_W0602","enabled":true},{"patternId":"PyLint_R0102","enabled":true},{"patternId":"PyLint_R0202","enabled":true},{"patternId":"PyLint_E0240","enabled":true},{"patternId":"PyLint_W0623","enabled":true},{"patternId":"PyLint_W0711","enabled":true},{"patternId":"PyLint_E0116","enabled":true},{"patternId":"PyLint_E0239","enabled":true},{"patternId":"PyLint_E1132","enabled":true},{"patternId":"PyLint_W1307","enabled":true},{"patternId":"PyLint_C0200","enabled":true},{"patternId":"PyLint_E0301","enabled":true},{"patternId":"PyLint_W1306","enabled":true},{"patternId":"PyLint_W1302","enabled":true},{"patternId":"PyLint_E0110","enabled":true},{"patternId":"PyLint_E1125","enabled":true}]} \ No newline at end of file diff --git a/gcloud-java-bigquery/README.md b/gcloud-java-bigquery/README.md index 81b5db71bcac..d300d3969c40 100644 --- a/gcloud-java-bigquery/README.md +++ b/gcloud-java-bigquery/README.md @@ -22,16 +22,16 @@ If you are using Maven, add this to your pom.xml file com.google.gcloud gcloud-java-bigquery - 0.1.5 + 0.1.7 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.gcloud:gcloud-java-bigquery:0.1.5' +compile 'com.google.gcloud:gcloud-java-bigquery:0.1.7' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.gcloud" % "gcloud-java-bigquery" % "0.1.5" +libraryDependencies += "com.google.gcloud" % "gcloud-java-bigquery" % "0.1.7" ``` Example Application diff --git a/gcloud-java-bigquery/pom.xml b/gcloud-java-bigquery/pom.xml index 5c79f150c722..39b0d6fc4e37 100644 --- a/gcloud-java-bigquery/pom.xml +++ b/gcloud-java-bigquery/pom.xml @@ -10,7 +10,7 @@ com.google.gcloud gcloud-java-pom - 0.1.6-SNAPSHOT + 0.1.8-SNAPSHOT gcloud-java-bigquery diff --git a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/BigQuery.java b/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/BigQuery.java index 14e324a43370..d40cc8145feb 100644 --- a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/BigQuery.java +++ b/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/BigQuery.java @@ -19,16 +19,15 @@ import static com.google.common.base.Preconditions.checkArgument; import com.google.common.base.Function; -import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; -import com.google.common.collect.Sets; +import com.google.gcloud.FieldSelector; +import com.google.gcloud.FieldSelector.Helper; import com.google.gcloud.Page; import com.google.gcloud.Service; import com.google.gcloud.bigquery.spi.BigQueryRpc; import java.util.List; -import java.util.Set; /** * An interface for Google Cloud BigQuery. @@ -43,7 +42,7 @@ public interface BigQuery extends Service { * @see Dataset * Resource */ - enum DatasetField { + enum DatasetField implements FieldSelector { ACCESS("access"), CREATION_TIME("creationTime"), DATASET_REFERENCE("datasetReference"), @@ -56,24 +55,19 @@ enum DatasetField { LOCATION("location"), SELF_LINK("selfLink"); + static final List REQUIRED_FIELDS = + ImmutableList.of(DATASET_REFERENCE); + private final String selector; DatasetField(String selector) { this.selector = selector; } + @Override public String selector() { return selector; } - - static String selector(DatasetField... fields) { - Set fieldStrings = Sets.newHashSetWithExpectedSize(fields.length + 1); - fieldStrings.add(DATASET_REFERENCE.selector()); - for (DatasetField field : fields) { - fieldStrings.add(field.selector()); - } - return Joiner.on(',').join(fieldStrings); - } } /** @@ -82,7 +76,7 @@ static String selector(DatasetField... fields) { * @see Table * Resource */ - enum TableField { + enum TableField implements FieldSelector { CREATION_TIME("creationTime"), DESCRIPTION("description"), ETAG("etag"), @@ -101,25 +95,19 @@ enum TableField { TYPE("type"), VIEW("view"); + static final List REQUIRED_FIELDS = + ImmutableList.of(TABLE_REFERENCE, TYPE); + private final String selector; TableField(String selector) { this.selector = selector; } + @Override public String selector() { return selector; } - - static String selector(TableField... fields) { - Set fieldStrings = Sets.newHashSetWithExpectedSize(fields.length + 2); - fieldStrings.add(TABLE_REFERENCE.selector()); - fieldStrings.add(TYPE.selector()); - for (TableField field : fields) { - fieldStrings.add(field.selector()); - } - return Joiner.on(',').join(fieldStrings); - } } /** @@ -128,7 +116,7 @@ static String selector(TableField... fields) { * @see Job Resource * */ - enum JobField { + enum JobField implements FieldSelector { CONFIGURATION("configuration"), ETAG("etag"), ID("id"), @@ -138,25 +126,19 @@ enum JobField { STATUS("status"), USER_EMAIL("user_email"); + static final List REQUIRED_FIELDS = + ImmutableList.of(JOB_REFERENCE, CONFIGURATION); + private final String selector; JobField(String selector) { this.selector = selector; } + @Override public String selector() { return selector; } - - static String selector(JobField... fields) { - Set fieldStrings = Sets.newHashSetWithExpectedSize(fields.length + 2); - fieldStrings.add(JOB_REFERENCE.selector()); - fieldStrings.add(CONFIGURATION.selector()); - for (JobField field : fields) { - fieldStrings.add(field.selector()); - } - return Joiner.on(',').join(fieldStrings); - } } /** @@ -210,7 +192,8 @@ private DatasetOption(BigQueryRpc.Option option, Object value) { * returned, even if not specified. */ public static DatasetOption fields(DatasetField... fields) { - return new DatasetOption(BigQueryRpc.Option.FIELDS, DatasetField.selector(fields)); + return new DatasetOption(BigQueryRpc.Option.FIELDS, + Helper.selector(DatasetField.REQUIRED_FIELDS, fields)); } } @@ -279,7 +262,8 @@ private TableOption(BigQueryRpc.Option option, Object value) { * of {@link Table#definition()}) are always returned, even if not specified. */ public static TableOption fields(TableField... fields) { - return new TableOption(BigQueryRpc.Option.FIELDS, TableField.selector(fields)); + return new TableOption(BigQueryRpc.Option.FIELDS, + Helper.selector(TableField.REQUIRED_FIELDS, fields)); } } @@ -376,10 +360,8 @@ public static JobListOption pageToken(String pageToken) { * listing jobs. */ public static JobListOption fields(JobField... fields) { - String selector = JobField.selector(fields); - StringBuilder builder = new StringBuilder(); - builder.append("etag,jobs(").append(selector).append(",state,errorResult),nextPageToken"); - return new JobListOption(BigQueryRpc.Option.FIELDS, builder.toString()); + return new JobListOption(BigQueryRpc.Option.FIELDS, + Helper.listSelector("jobs", JobField.REQUIRED_FIELDS, fields, "state", "errorResult")); } } @@ -402,7 +384,8 @@ private JobOption(BigQueryRpc.Option option, Object value) { * returned, even if not specified. */ public static JobOption fields(JobField... fields) { - return new JobOption(BigQueryRpc.Option.FIELDS, JobField.selector(fields)); + return new JobOption(BigQueryRpc.Option.FIELDS, + Helper.selector(JobField.REQUIRED_FIELDS, fields)); } } @@ -488,9 +471,10 @@ public static QueryResultsOption maxWaitTime(long maxWaitTime) { Dataset getDataset(DatasetId datasetId, DatasetOption... options); /** - * Lists the project's datasets. This method returns partial information on each dataset - * ({@link Dataset#datasetId()}, {@link Dataset#friendlyName()} and {@link Dataset#id()}). To get - * complete information use either {@link #getDataset(String, DatasetOption...)} or + * Lists the project's datasets. This method returns partial information on each dataset: + * ({@link Dataset#datasetId()}, {@link Dataset#friendlyName()} and + * {@link Dataset#generatedId()}). To get complete information use either + * {@link #getDataset(String, DatasetOption...)} or * {@link #getDataset(DatasetId, DatasetOption...)}. * * @throws BigQueryException upon failure @@ -558,9 +542,9 @@ public static QueryResultsOption maxWaitTime(long maxWaitTime) { Table getTable(TableId tableId, TableOption... options); /** - * Lists the tables in the dataset. This method returns partial information on each table - * ({@link Table#tableId()}, {@link Table#friendlyName()}, {@link Table#id()} and type, which - * is part of {@link Table#definition()}). To get complete information use either + * Lists the tables in the dataset. This method returns partial information on each table: + * ({@link Table#tableId()}, {@link Table#friendlyName()}, {@link Table#generatedId()} and type, + * which is part of {@link Table#definition()}). To get complete information use either * {@link #getTable(TableId, TableOption...)} or * {@link #getTable(String, String, TableOption...)}. * @@ -569,9 +553,9 @@ public static QueryResultsOption maxWaitTime(long maxWaitTime) { Page listTables(String datasetId, TableListOption... options); /** - * Lists the tables in the dataset. This method returns partial information on each table - * ({@link Table#tableId()}, {@link Table#friendlyName()}, {@link Table#id()} and type, which - * is part of {@link Table#definition()}). To get complete information use either + * Lists the tables in the dataset. This method returns partial information on each table: + * ({@link Table#tableId()}, {@link Table#friendlyName()}, {@link Table#generatedId()} and type, + * which is part of {@link Table#definition()}). To get complete information use either * {@link #getTable(TableId, TableOption...)} or * {@link #getTable(String, String, TableOption...)}. * diff --git a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/Dataset.java b/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/Dataset.java index e17d3e82c4ef..215a0c662c3b 100644 --- a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/Dataset.java +++ b/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/Dataset.java @@ -103,8 +103,8 @@ public Builder friendlyName(String friendlyName) { } @Override - Builder id(String id) { - infoBuilder.id(id); + Builder generatedId(String generatedId) { + infoBuilder.generatedId(generatedId); return this; } diff --git a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/DatasetInfo.java b/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/DatasetInfo.java index aa767b97631b..9f1d25f05925 100644 --- a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/DatasetInfo.java +++ b/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/DatasetInfo.java @@ -55,8 +55,7 @@ public Dataset apply(DatasetInfo datasetInfo) { return datasetInfo.toPb(); } }; - - private static final long serialVersionUID = -6615133444520365839L; + private static final long serialVersionUID = 8469473744160758489L; private final DatasetId datasetId; private final List acl; @@ -65,7 +64,7 @@ public Dataset apply(DatasetInfo datasetInfo) { private final String description; private final String etag; private final String friendlyName; - private final String id; + private final String generatedId; private final Long lastModified; private final String location; private final String selfLink; @@ -114,7 +113,7 @@ public abstract static class Builder { */ public abstract Builder friendlyName(String friendlyName); - abstract Builder id(String id); + abstract Builder generatedId(String generatedId); abstract Builder lastModified(Long lastModified); @@ -144,7 +143,7 @@ static final class BuilderImpl extends Builder { private String description; private String etag; private String friendlyName; - private String id; + private String generatedId; private Long lastModified; private String location; private String selfLink; @@ -159,7 +158,7 @@ static final class BuilderImpl extends Builder { this.description = datasetInfo.description; this.etag = datasetInfo.etag; this.friendlyName = datasetInfo.friendlyName; - this.id = datasetInfo.id; + this.generatedId = datasetInfo.generatedId; this.lastModified = datasetInfo.lastModified; this.location = datasetInfo.location; this.selfLink = datasetInfo.selfLink; @@ -182,7 +181,7 @@ public Acl apply(Dataset.Access accessPb) { this.description = datasetPb.getDescription(); this.etag = datasetPb.getEtag(); this.friendlyName = datasetPb.getFriendlyName(); - this.id = datasetPb.getId(); + this.generatedId = datasetPb.getId(); this.lastModified = datasetPb.getLastModifiedTime(); this.location = datasetPb.getLocation(); this.selfLink = datasetPb.getSelfLink(); @@ -232,8 +231,8 @@ public Builder friendlyName(String friendlyName) { } @Override - Builder id(String id) { - this.id = id; + Builder generatedId(String generatedId) { + this.generatedId = generatedId; return this; } @@ -269,7 +268,7 @@ public DatasetInfo build() { description = builder.description; etag = builder.etag; friendlyName = builder.friendlyName; - id = builder.id; + generatedId = builder.generatedId; lastModified = builder.lastModified; location = builder.location; selfLink = builder.selfLink; @@ -333,10 +332,10 @@ public String friendlyName() { } /** - * Returns an opaque id for the dataset. + * Returns the service-generated id for the dataset. */ - public String id() { - return id; + public String generatedId() { + return generatedId; } /** @@ -381,7 +380,7 @@ public String toString() { .add("description", description) .add("etag", etag) .add("friendlyName", friendlyName) - .add("id", id) + .add("generatedId", generatedId) .add("lastModified", lastModified) .add("location", location) .add("selfLink", selfLink) @@ -431,7 +430,7 @@ Dataset toPb() { datasetPb.setDescription(description); datasetPb.setEtag(etag); datasetPb.setFriendlyName(friendlyName); - datasetPb.setId(id); + datasetPb.setId(generatedId); datasetPb.setLastModifiedTime(lastModified); datasetPb.setLocation(location); datasetPb.setSelfLink(selfLink); diff --git a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/Job.java b/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/Job.java index 1e63344a600d..7f8237473b15 100644 --- a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/Job.java +++ b/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/Job.java @@ -63,8 +63,8 @@ Builder etag(String etag) { } @Override - Builder id(String id) { - infoBuilder.id(id); + Builder generatedId(String generatedId) { + infoBuilder.generatedId(generatedId); return this; } @@ -128,22 +128,19 @@ public boolean exists() { /** * Checks if this job has completed its execution, either failing or succeeding. If the job does - * not exist this method returns {@code false}. To correctly wait for job's completion check that - * the job exists first, using {@link #exists()}: + * not exist this method returns {@code true}. You can wait for job completion with: *
 {@code
-   * if (job.exists()) {
-   *   while(!job.isDone()) {
-   *     Thread.sleep(1000L);
-   *   }
+   * while(!job.isDone()) {
+   *   Thread.sleep(1000L);
    * }}
* - * @return {@code true} if this job is in {@link JobStatus.State#DONE} state, {@code false} if the - * state is not {@link JobStatus.State#DONE} or the job does not exist + * @return {@code true} if this job is in {@link JobStatus.State#DONE} state or if it does not + * exist, {@code false} if the state is not {@link JobStatus.State#DONE} * @throws BigQueryException upon failure */ public boolean isDone() { Job job = bigquery.getJob(jobId(), BigQuery.JobOption.fields(BigQuery.JobField.STATUS)); - return job != null && job.status().state() == JobStatus.State.DONE; + return job == null || job.status().state() == JobStatus.State.DONE; } /** diff --git a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/JobInfo.java b/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/JobInfo.java index 1adf7fabafc1..b15ba38f8912 100644 --- a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/JobInfo.java +++ b/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/JobInfo.java @@ -42,10 +42,10 @@ public JobInfo apply(Job pb) { } }; - private static final long serialVersionUID = -3272941007234620265L; + private static final long serialVersionUID = 2740548743267670124L; private final String etag; - private final String id; + private final String generatedId; private final JobId jobId; private final String selfLink; private final JobStatus status; @@ -95,7 +95,7 @@ public abstract static class Builder { abstract Builder etag(String etag); - abstract Builder id(String id); + abstract Builder generatedId(String generatedId); /** * Sets the job identity. @@ -128,7 +128,7 @@ public abstract static class Builder { static final class BuilderImpl extends Builder { private String etag; - private String id; + private String generatedId; private JobId jobId; private String selfLink; private JobStatus status; @@ -140,7 +140,7 @@ static final class BuilderImpl extends Builder { BuilderImpl(JobInfo jobInfo) { this.etag = jobInfo.etag; - this.id = jobInfo.id; + this.generatedId = jobInfo.generatedId; this.jobId = jobInfo.jobId; this.selfLink = jobInfo.selfLink; this.status = jobInfo.status; @@ -151,7 +151,7 @@ static final class BuilderImpl extends Builder { BuilderImpl(Job jobPb) { this.etag = jobPb.getEtag(); - this.id = jobPb.getId(); + this.generatedId = jobPb.getId(); if (jobPb.getJobReference() != null) { this.jobId = JobId.fromPb(jobPb.getJobReference()); } @@ -173,8 +173,8 @@ Builder etag(String etag) { } @Override - Builder id(String id) { - this.id = id; + Builder generatedId(String generatedId) { + this.generatedId = generatedId; return this; } @@ -223,7 +223,7 @@ public JobInfo build() { JobInfo(BuilderImpl builder) { this.jobId = builder.jobId; this.etag = builder.etag; - this.id = builder.id; + this.generatedId = builder.generatedId; this.selfLink = builder.selfLink; this.status = builder.status; this.statistics = builder.statistics; @@ -239,10 +239,10 @@ public String etag() { } /** - * Returns an opaque id for the job. + * Returns the service-generated id for the job. */ - public String id() { - return id; + public String generatedId() { + return generatedId; } /** @@ -306,7 +306,7 @@ public String toString() { .add("statistics", statistics) .add("userEmail", userEmail) .add("etag", etag) - .add("id", id) + .add("generatedId", generatedId) .add("selfLink", selfLink) .add("configuration", configuration) .toString(); @@ -331,7 +331,7 @@ JobInfo setProjectId(String projectId) { Job toPb() { Job jobPb = new Job(); jobPb.setEtag(etag); - jobPb.setId(id); + jobPb.setId(generatedId); jobPb.setSelfLink(selfLink); jobPb.setUserEmail(userEmail); if (jobId != null) { diff --git a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/Option.java b/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/Option.java index 3fdc27ecab99..e7ac0d0a8cc4 100644 --- a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/Option.java +++ b/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/Option.java @@ -27,7 +27,7 @@ /** * Base class for BigQuery operation option. */ -class Option implements Serializable { +abstract class Option implements Serializable { private static final long serialVersionUID = -6647817677804099207L; @@ -53,8 +53,7 @@ public boolean equals(Object obj) { return false; } Option other = (Option) obj; - return Objects.equals(rpcOption, other.rpcOption) - && Objects.equals(value, other.value); + return Objects.equals(rpcOption, other.rpcOption) && Objects.equals(value, other.value); } @Override diff --git a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/QueryStage.java b/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/QueryStage.java index 8c9f91fd39f3..9404fbf5d9ad 100644 --- a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/QueryStage.java +++ b/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/QueryStage.java @@ -137,7 +137,7 @@ static QueryStep fromPb(com.google.api.services.bigquery.model.ExplainQueryStep private final double computeRatioAvg; private final double computeRatioMax; - private final long id; + private final long generatedId; private final String name; private final double readRatioAvg; private final double readRatioMax; @@ -153,7 +153,7 @@ static final class Builder { private double computeRatioAvg; private double computeRatioMax; - private long id; + private long generatedId; private String name; private double readRatioAvg; private double readRatioMax; @@ -177,8 +177,8 @@ Builder computeRatioMax(double computeRatioMax) { return this; } - Builder id(long id) { - this.id = id; + Builder generatedId(long generatedId) { + this.generatedId = generatedId; return this; } @@ -240,7 +240,7 @@ QueryStage build() { QueryStage(Builder builder) { computeRatioAvg = builder.computeRatioAvg; computeRatioMax = builder.computeRatioMax; - id = builder.id; + generatedId = builder.generatedId; name = builder.name; readRatioAvg = builder.readRatioAvg; readRatioMax = builder.readRatioMax; @@ -270,10 +270,10 @@ public double computeRatioMax() { } /** - * Returns a unique ID for the stage within its plan. + * Returns a unique, server-generated ID for the stage within its plan. */ - public long id() { - return id; + public long generatedId() { + return generatedId; } /** @@ -357,7 +357,7 @@ public String toString() { return MoreObjects.toStringHelper(this) .add("computeRatioAvg", computeRatioAvg) .add("computeRatioMax", computeRatioMax) - .add("id", id) + .add("generatedId", generatedId) .add("name", name) .add("readRatioAvg", readRatioAvg) .add("readRatioMax", readRatioMax) @@ -373,7 +373,7 @@ public String toString() { @Override public int hashCode() { - return Objects.hash(computeRatioAvg, computeRatioMax, id, name, readRatioAvg, readRatioMax, + return Objects.hash(computeRatioAvg, computeRatioMax, generatedId, name, readRatioAvg, readRatioMax, recordsRead, recordsWritten, steps, waitRatioAvg, waitRatioMax, writeRatioAvg); } @@ -383,7 +383,7 @@ public boolean equals(Object obj) { return false; } QueryStage other = (QueryStage) obj; - return id == other.id + return generatedId == other.generatedId && computeRatioAvg == other.computeRatioAvg && computeRatioMax == other.computeRatioMax && readRatioAvg == other.readRatioAvg @@ -406,7 +406,7 @@ ExplainQueryStage toPb() { ExplainQueryStage stagePb = new ExplainQueryStage() .setComputeRatioAvg(computeRatioAvg) .setComputeRatioMax(computeRatioMax) - .setId(id) + .setId(generatedId) .setName(name) .setReadRatioAvg(readRatioAvg) .setReadRatioMax(readRatioMax) @@ -426,7 +426,7 @@ static QueryStage fromPb(com.google.api.services.bigquery.model.ExplainQueryStag Builder builder = new QueryStage.Builder(); builder.computeRatioAvg(stagePb.getComputeRatioAvg()); builder.computeRatioMax(stagePb.getComputeRatioMax()); - builder.id(stagePb.getId()); + builder.generatedId(stagePb.getId()); builder.name(stagePb.getName()); builder.readRatioAvg(stagePb.getReadRatioAvg()); builder.readRatioMax(stagePb.getReadRatioMax()); diff --git a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/Table.java b/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/Table.java index 3f902d2ff242..b007771645df 100644 --- a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/Table.java +++ b/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/Table.java @@ -92,8 +92,8 @@ public Builder friendlyName(String friendlyName) { } @Override - Builder id(String id) { - infoBuilder.id(id); + Builder generatedId(String generatedId) { + infoBuilder.generatedId(generatedId); return this; } diff --git a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/TableInfo.java b/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/TableInfo.java index de331350e978..938907e245e7 100644 --- a/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/TableInfo.java +++ b/gcloud-java-bigquery/src/main/java/com/google/gcloud/bigquery/TableInfo.java @@ -52,10 +52,10 @@ public Table apply(TableInfo tableInfo) { } }; - private static final long serialVersionUID = -7679032506430816205L; + private static final long serialVersionUID = 609769795097719407L; private final String etag; - private final String id; + private final String generatedId; private final String selfLink; private final TableId tableId; private final String friendlyName; @@ -90,7 +90,7 @@ public abstract static class Builder { */ public abstract Builder friendlyName(String friendlyName); - abstract Builder id(String id); + abstract Builder generatedId(String generatedId); abstract Builder lastModifiedTime(Long lastModifiedTime); @@ -117,7 +117,7 @@ public abstract static class Builder { static class BuilderImpl extends Builder { private String etag; - private String id; + private String generatedId; private String selfLink; private TableId tableId; private String friendlyName; @@ -131,7 +131,7 @@ static class BuilderImpl extends Builder { BuilderImpl(TableInfo tableInfo) { this.etag = tableInfo.etag; - this.id = tableInfo.id; + this.generatedId = tableInfo.generatedId; this.selfLink = tableInfo.selfLink; this.tableId = tableInfo.tableId; this.friendlyName = tableInfo.friendlyName; @@ -152,7 +152,7 @@ static class BuilderImpl extends Builder { this.friendlyName = tablePb.getFriendlyName(); this.creationTime = tablePb.getCreationTime(); this.etag = tablePb.getEtag(); - this.id = tablePb.getId(); + this.generatedId = tablePb.getId(); this.selfLink = tablePb.getSelfLink(); this.definition = TableDefinition.fromPb(tablePb); } @@ -188,8 +188,8 @@ public Builder friendlyName(String friendlyName) { } @Override - Builder id(String id) { - this.id = id; + Builder generatedId(String generatedId) { + this.generatedId = generatedId; return this; } @@ -226,7 +226,7 @@ public TableInfo build() { TableInfo(BuilderImpl builder) { this.tableId = checkNotNull(builder.tableId); this.etag = builder.etag; - this.id = builder.id; + this.generatedId = builder.generatedId; this.selfLink = builder.selfLink; this.friendlyName = builder.friendlyName; this.description = builder.description; @@ -244,10 +244,10 @@ public String etag() { } /** - * Returns an opaque id for the table. + * Returns the service-generated id for the table. */ - public String id() { - return id; + public String generatedId() { + return generatedId; } /** @@ -321,7 +321,7 @@ public String toString() { return MoreObjects.toStringHelper(this) .add("tableId", tableId) .add("etag", etag) - .add("id", id) + .add("generatedId", generatedId) .add("selfLink", selfLink) .add("friendlyName", friendlyName) .add("description", description) @@ -379,7 +379,7 @@ Table toPb() { tablePb.setEtag(etag); tablePb.setExpirationTime(expirationTime); tablePb.setFriendlyName(friendlyName); - tablePb.setId(id); + tablePb.setId(generatedId); tablePb.setSelfLink(selfLink); return tablePb; } diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/BigQueryImplTest.java b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/BigQueryImplTest.java index a6f512800024..c7d7cf846ef2 100644 --- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/BigQueryImplTest.java +++ b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/BigQueryImplTest.java @@ -886,12 +886,14 @@ public com.google.api.services.bigquery.model.Job apply(Job job) { assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(jobList.toArray(), Iterables.toArray(page.values(), Job.class)); String selector = (String) capturedOptions.getValue().get(JOB_OPTION_FIELDS.rpcOption()); - assertTrue(selector.contains("etag,jobs(")); + assertTrue(selector.contains("nextPageToken,jobs(")); assertTrue(selector.contains("configuration")); assertTrue(selector.contains("jobReference")); assertTrue(selector.contains("statistics")); - assertTrue(selector.contains("state,errorResult),nextPageToken")); - assertEquals(80, selector.length()); + assertTrue(selector.contains("state")); + assertTrue(selector.contains("errorResult")); + assertTrue(selector.contains(")")); + assertEquals(75, selector.length()); } @Test diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/DatasetInfoTest.java b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/DatasetInfoTest.java index 20875c0fc853..474a31d44a20 100644 --- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/DatasetInfoTest.java +++ b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/DatasetInfoTest.java @@ -38,7 +38,7 @@ public class DatasetInfoTest { private static final String DESCRIPTION = "description"; private static final String ETAG = "0xFF00"; private static final String FRIENDLY_NAME = "friendlyDataset"; - private static final String ID = "P/D:1"; + private static final String GENERATED_ID = "P/D:1"; private static final Long LAST_MODIFIED = CREATION_TIME + 50; private static final String LOCATION = ""; private static final String SELF_LINK = "http://bigquery/p/d"; @@ -51,7 +51,7 @@ public class DatasetInfoTest { .description(DESCRIPTION) .etag(ETAG) .friendlyName(FRIENDLY_NAME) - .id(ID) + .generatedId(GENERATED_ID) .lastModified(LAST_MODIFIED) .location(LOCATION) .selfLink(SELF_LINK) @@ -90,7 +90,7 @@ public void testBuilder() { assertEquals(DESCRIPTION, DATASET_INFO.description()); assertEquals(ETAG, DATASET_INFO.etag()); assertEquals(FRIENDLY_NAME, DATASET_INFO.friendlyName()); - assertEquals(ID, DATASET_INFO.id()); + assertEquals(GENERATED_ID, DATASET_INFO.generatedId()); assertEquals(LAST_MODIFIED, DATASET_INFO.lastModified()); assertEquals(LOCATION, DATASET_INFO.location()); assertEquals(SELF_LINK, DATASET_INFO.selfLink()); @@ -101,7 +101,7 @@ public void testBuilder() { assertEquals(DESCRIPTION, DATASET_INFO_COMPLETE.description()); assertEquals(ETAG, DATASET_INFO_COMPLETE.etag()); assertEquals(FRIENDLY_NAME, DATASET_INFO_COMPLETE.friendlyName()); - assertEquals(ID, DATASET_INFO_COMPLETE.id()); + assertEquals(GENERATED_ID, DATASET_INFO_COMPLETE.generatedId()); assertEquals(LAST_MODIFIED, DATASET_INFO_COMPLETE.lastModified()); assertEquals(LOCATION, DATASET_INFO_COMPLETE.location()); assertEquals(SELF_LINK, DATASET_INFO_COMPLETE.selfLink()); @@ -125,7 +125,7 @@ private void compareDatasets(DatasetInfo expected, DatasetInfo value) { assertEquals(expected.description(), value.description()); assertEquals(expected.etag(), value.etag()); assertEquals(expected.friendlyName(), value.friendlyName()); - assertEquals(expected.id(), value.id()); + assertEquals(expected.generatedId(), value.generatedId()); assertEquals(expected.location(), value.location()); assertEquals(expected.selfLink(), value.selfLink()); assertEquals(expected.acl(), value.acl()); diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/DatasetTest.java b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/DatasetTest.java index dd03b7899ebc..43c550c59d11 100644 --- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/DatasetTest.java +++ b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/DatasetTest.java @@ -51,7 +51,7 @@ public class DatasetTest { private static final String DESCRIPTION = "description"; private static final String ETAG = "0xFF00"; private static final String FRIENDLY_NAME = "friendlyDataset"; - private static final String ID = "P/D:1"; + private static final String GENERATED_ID = "P/D:1"; private static final Long LAST_MODIFIED = CREATION_TIME + 50; private static final String LOCATION = ""; private static final String SELF_LINK = "http://bigquery/p/d"; @@ -102,7 +102,7 @@ public void testBuilder() { .description(DESCRIPTION) .etag(ETAG) .friendlyName(FRIENDLY_NAME) - .id(ID) + .generatedId(GENERATED_ID) .lastModified(LAST_MODIFIED) .location(LOCATION) .selfLink(SELF_LINK) @@ -114,7 +114,7 @@ public void testBuilder() { assertEquals(DESCRIPTION, builtDataset.description()); assertEquals(ETAG, builtDataset.etag()); assertEquals(FRIENDLY_NAME, builtDataset.friendlyName()); - assertEquals(ID, builtDataset.id()); + assertEquals(GENERATED_ID, builtDataset.generatedId()); assertEquals(LAST_MODIFIED, builtDataset.lastModified()); assertEquals(LOCATION, builtDataset.location()); assertEquals(SELF_LINK, builtDataset.selfLink()); @@ -362,7 +362,7 @@ private void compareDatasetInfo(DatasetInfo expected, DatasetInfo value) { assertEquals(expected.description(), value.description()); assertEquals(expected.etag(), value.etag()); assertEquals(expected.friendlyName(), value.friendlyName()); - assertEquals(expected.id(), value.id()); + assertEquals(expected.generatedId(), value.generatedId()); assertEquals(expected.location(), value.location()); assertEquals(expected.selfLink(), value.selfLink()); assertEquals(expected.acl(), value.acl()); diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobInfoTest.java b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobInfoTest.java index 260088470aff..9c90fbe7b05f 100644 --- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobInfoTest.java +++ b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobInfoTest.java @@ -37,7 +37,7 @@ public class JobInfoTest { private static final String ETAG = "etag"; - private static final String ID = "id"; + private static final String GENERATED_ID = "id"; private static final String SELF_LINK = "selfLink"; private static final String EMAIL = "email"; private static final JobId JOB_ID = JobId.of("job"); @@ -163,7 +163,7 @@ public class JobInfoTest { .statistics(COPY_JOB_STATISTICS) .jobId(JOB_ID) .etag(ETAG) - .id(ID) + .generatedId(GENERATED_ID) .selfLink(SELF_LINK) .userEmail(EMAIL) .status(JOB_STATUS) @@ -173,7 +173,7 @@ public class JobInfoTest { .statistics(EXTRACT_JOB_STATISTICS) .jobId(JOB_ID) .etag(ETAG) - .id(ID) + .generatedId(GENERATED_ID) .selfLink(SELF_LINK) .userEmail(EMAIL) .status(JOB_STATUS) @@ -183,7 +183,7 @@ public class JobInfoTest { .statistics(LOAD_JOB_STATISTICS) .jobId(JOB_ID) .etag(ETAG) - .id(ID) + .generatedId(GENERATED_ID) .selfLink(SELF_LINK) .userEmail(EMAIL) .status(JOB_STATUS) @@ -193,7 +193,7 @@ public class JobInfoTest { .statistics(QUERY_JOB_STATISTICS) .jobId(JOB_ID) .etag(ETAG) - .id(ID) + .generatedId(GENERATED_ID) .selfLink(SELF_LINK) .userEmail(EMAIL) .status(JOB_STATUS) @@ -266,7 +266,7 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { assertEquals(ETAG, COPY_JOB.etag()); - assertEquals(ID, COPY_JOB.id()); + assertEquals(GENERATED_ID, COPY_JOB.generatedId()); assertEquals(SELF_LINK, COPY_JOB.selfLink()); assertEquals(EMAIL, COPY_JOB.userEmail()); assertEquals(JOB_ID, COPY_JOB.jobId()); @@ -275,7 +275,7 @@ public void testBuilder() { assertEquals(COPY_JOB_STATISTICS, COPY_JOB.statistics()); assertEquals(ETAG, EXTRACT_JOB.etag()); - assertEquals(ID, EXTRACT_JOB.id()); + assertEquals(GENERATED_ID, EXTRACT_JOB.generatedId()); assertEquals(SELF_LINK, EXTRACT_JOB.selfLink()); assertEquals(EMAIL, EXTRACT_JOB.userEmail()); assertEquals(JOB_ID, EXTRACT_JOB.jobId()); @@ -284,7 +284,7 @@ public void testBuilder() { assertEquals(EXTRACT_JOB_STATISTICS, EXTRACT_JOB.statistics()); assertEquals(ETAG, LOAD_JOB.etag()); - assertEquals(ID, LOAD_JOB.id()); + assertEquals(GENERATED_ID, LOAD_JOB.generatedId()); assertEquals(SELF_LINK, LOAD_JOB.selfLink()); assertEquals(EMAIL, LOAD_JOB.userEmail()); assertEquals(JOB_ID, LOAD_JOB.jobId()); @@ -293,7 +293,7 @@ public void testBuilder() { assertEquals(LOAD_JOB_STATISTICS, LOAD_JOB.statistics()); assertEquals(ETAG, QUERY_JOB.etag()); - assertEquals(ID, QUERY_JOB.id()); + assertEquals(GENERATED_ID, QUERY_JOB.generatedId()); assertEquals(SELF_LINK, QUERY_JOB.selfLink()); assertEquals(EMAIL, QUERY_JOB.userEmail()); assertEquals(JOB_ID, QUERY_JOB.jobId()); @@ -359,7 +359,7 @@ private void compareJobInfo(JobInfo expected, JobInfo value) { assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); assertEquals(expected.etag(), value.etag()); - assertEquals(expected.id(), value.id()); + assertEquals(expected.generatedId(), value.generatedId()); assertEquals(expected.jobId(), value.jobId()); assertEquals(expected.selfLink(), value.selfLink()); assertEquals(expected.status(), value.status()); diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobStatisticsTest.java b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobStatisticsTest.java index 1ec67d034754..4a3940ba4543 100644 --- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobStatisticsTest.java +++ b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobStatisticsTest.java @@ -71,7 +71,7 @@ public class JobStatisticsTest { private static final QueryStage QUERY_STAGE = QueryStage.builder() .computeRatioAvg(1.1) .computeRatioMax(2.2) - .id(42L) + .generatedId(42L) .name("stage") .readRatioAvg(3.3) .readRatioMax(4.4) diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobTest.java b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobTest.java index db51706fff5a..61c9c521196a 100644 --- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobTest.java +++ b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/JobTest.java @@ -36,7 +36,7 @@ public class JobTest { private static final TableId TABLE_ID1 = TableId.of("dataset", "table1"); private static final TableId TABLE_ID2 = TableId.of("dataset", "table2"); private static final String ETAG = "etag"; - private static final String ID = "id"; + private static final String GENERATED_ID = "id"; private static final String SELF_LINK = "selfLink"; private static final String EMAIL = "email"; private static final JobStatus JOB_STATUS = new JobStatus(JobStatus.State.DONE); @@ -52,7 +52,7 @@ public class JobTest { .statistics(COPY_JOB_STATISTICS) .jobId(JOB_ID) .etag(ETAG) - .id(ID) + .generatedId(GENERATED_ID) .selfLink(SELF_LINK) .userEmail(EMAIL) .status(JOB_STATUS) @@ -89,13 +89,13 @@ public void testBuilder() { .statistics(COPY_JOB_STATISTICS) .jobId(JOB_ID) .etag(ETAG) - .id(ID) + .generatedId(GENERATED_ID) .selfLink(SELF_LINK) .userEmail(EMAIL) .status(JOB_STATUS) .build(); assertEquals(ETAG, builtJob.etag()); - assertEquals(ID, builtJob.id()); + assertEquals(GENERATED_ID, builtJob.generatedId()); assertEquals(SELF_LINK, builtJob.selfLink()); assertEquals(EMAIL, builtJob.userEmail()); assertEquals(JOB_ID, builtJob.jobId()); @@ -172,7 +172,7 @@ public void testIsDone_NotExists() throws Exception { expect(bigquery.getJob(JOB_INFO.jobId(), expectedOptions)).andReturn(null); replay(bigquery); initializeJob(); - assertFalse(job.isDone()); + assertTrue(job.isDone()); } @Test @@ -247,7 +247,7 @@ private void compareJobInfo(JobInfo expected, JobInfo value) { assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); assertEquals(expected.etag(), value.etag()); - assertEquals(expected.id(), value.id()); + assertEquals(expected.generatedId(), value.generatedId()); assertEquals(expected.jobId(), value.jobId()); assertEquals(expected.selfLink(), value.selfLink()); assertEquals(expected.status(), value.status()); diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/OptionTest.java b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/OptionTest.java index 2c89ececedb8..42f19830fb6c 100644 --- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/OptionTest.java +++ b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/OptionTest.java @@ -17,22 +17,49 @@ package com.google.gcloud.bigquery; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; import com.google.gcloud.bigquery.spi.BigQueryRpc; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; public class OptionTest { + private static final BigQueryRpc.Option RPC_OPTION = BigQueryRpc.Option.PAGE_TOKEN; + private static final BigQueryRpc.Option ANOTHER_RPC_OPTION = BigQueryRpc.Option.FIELDS; + private static final String VALUE = "some value"; + private static final String OTHER_VALUE = "another value"; + private static final Option OPTION = new Option(RPC_OPTION, VALUE) {}; + private static final Option OPTION_EQUALS = new Option(RPC_OPTION, VALUE) {}; + private static final Option OPTION_NOT_EQUALS1 = new Option(RPC_OPTION, OTHER_VALUE) {}; + private static final Option OPTION_NOT_EQUALS2 = new Option(ANOTHER_RPC_OPTION, VALUE) {}; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void testEquals() { + assertEquals(OPTION, OPTION_EQUALS); + assertNotEquals(OPTION, OPTION_NOT_EQUALS1); + assertNotEquals(OPTION, OPTION_NOT_EQUALS2); + } + @Test - public void testOption() { - Option option = new Option(BigQueryRpc.Option.PAGE_TOKEN, "token"); - assertEquals(BigQueryRpc.Option.PAGE_TOKEN, option.rpcOption()); - assertEquals("token", option.value()); + public void testHashCode() { + assertEquals(OPTION.hashCode(), OPTION_EQUALS.hashCode()); } - @Test(expected = NullPointerException.class) - public void testNullRpcOption() { - new Option(null, "token"); + @Test + public void testConstructor() { + assertEquals(RPC_OPTION, OPTION.rpcOption()); + assertEquals(VALUE, OPTION.value()); + Option option = new Option(RPC_OPTION, null) {}; + assertEquals(RPC_OPTION, option.rpcOption()); + assertNull(option.value()); + thrown.expect(NullPointerException.class); + new Option(null, VALUE) {}; } } diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/QueryStageTest.java b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/QueryStageTest.java index 99a7c8096454..ac60967a8bee 100644 --- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/QueryStageTest.java +++ b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/QueryStageTest.java @@ -48,7 +48,7 @@ public class QueryStageTest { private static final QueryStage QUERY_STAGE = QueryStage.builder() .computeRatioAvg(COMPUTE_RATIO_AVG) .computeRatioMax(COMPUTE_RATIO_MAX) - .id(ID) + .generatedId(ID) .name(NAME) .readRatioAvg(READ_RATIO_AVG) .readRatioMax(READ_RATIO_MAX) @@ -73,7 +73,7 @@ public void testQueryStepConstructor() { public void testBuilder() { assertEquals(COMPUTE_RATIO_AVG, QUERY_STAGE.computeRatioAvg(), 0); assertEquals(COMPUTE_RATIO_MAX, QUERY_STAGE.computeRatioMax(), 0); - assertEquals(ID, QUERY_STAGE.id()); + assertEquals(ID, QUERY_STAGE.generatedId()); assertEquals(NAME, QUERY_STAGE.name()); assertEquals(READ_RATIO_AVG, QUERY_STAGE.readRatioAvg(), 0); assertEquals(READ_RATIO_MAX, QUERY_STAGE.readRatioMax(), 0); @@ -108,7 +108,7 @@ private void compareQueryStage(QueryStage expected, QueryStage value) { assertEquals(expected, value); assertEquals(expected.computeRatioAvg(), value.computeRatioAvg(), 0); assertEquals(expected.computeRatioMax(), value.computeRatioMax(), 0); - assertEquals(expected.id(), value.id()); + assertEquals(expected.generatedId(), value.generatedId()); assertEquals(expected.name(), value.name()); assertEquals(expected.readRatioAvg(), value.readRatioAvg(), 0); assertEquals(expected.readRatioMax(), value.readRatioMax(), 0); diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/SerializationTest.java b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/SerializationTest.java index 111df074ffa2..61e763f9a539 100644 --- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/SerializationTest.java +++ b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/SerializationTest.java @@ -44,7 +44,7 @@ public class SerializationTest extends BaseSerializationTest { private static final String DESCRIPTION = "Description"; private static final String ETAG = "0xFF00"; private static final String FRIENDLY_NAME = "friendlyDataset"; - private static final String ID = "P/D:1"; + private static final String GENERATED_ID = "P/D:1"; private static final Long LAST_MODIFIED = CREATION_TIME + 50; private static final String LOCATION = ""; private static final String SELF_LINK = "http://bigquery/p/d"; @@ -56,7 +56,7 @@ public class SerializationTest extends BaseSerializationTest { .description(DESCRIPTION) .etag(ETAG) .friendlyName(FRIENDLY_NAME) - .id(ID) + .generatedId(GENERATED_ID) .lastModified(LAST_MODIFIED) .location(LOCATION) .selfLink(SELF_LINK) @@ -106,21 +106,21 @@ public class SerializationTest extends BaseSerializationTest { .creationTime(CREATION_TIME) .description(DESCRIPTION) .etag(ETAG) - .id(ID) + .generatedId(GENERATED_ID) .build(); private static final TableDefinition VIEW_DEFINITION = ViewDefinition.of("QUERY"); private static final TableInfo VIEW_INFO = TableInfo.builder(TABLE_ID, VIEW_DEFINITION) .creationTime(CREATION_TIME) .description(DESCRIPTION) .etag(ETAG) - .id(ID) + .generatedId(GENERATED_ID) .build(); private static final TableInfo EXTERNAL_TABLE_INFO = TableInfo.builder(TABLE_ID, EXTERNAL_TABLE_DEFINITION) .creationTime(CREATION_TIME) .description(DESCRIPTION) .etag(ETAG) - .id(ID) + .generatedId(GENERATED_ID) .build(); private static final JobStatistics JOB_STATISTICS = JobStatistics.builder() .creationTime(1L) diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableInfoTest.java b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableInfoTest.java index 18b8be10d71e..84d224f220cb 100644 --- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableInfoTest.java +++ b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableInfoTest.java @@ -27,7 +27,7 @@ public class TableInfoTest { private static final String ETAG = "etag"; - private static final String ID = "project:dataset:table"; + private static final String GENERATED_ID = "project:dataset:table"; private static final String SELF_LINK = "selfLink"; private static final TableId TABLE_ID = TableId.of("dataset", "table"); private static final String FRIENDLY_NAME = "friendlyName"; @@ -89,7 +89,7 @@ public class TableInfoTest { .etag(ETAG) .expirationTime(EXPIRATION_TIME) .friendlyName(FRIENDLY_NAME) - .id(ID) + .generatedId(GENERATED_ID) .lastModifiedTime(LAST_MODIFIED_TIME) .selfLink(SELF_LINK) .build(); @@ -99,7 +99,7 @@ public class TableInfoTest { .etag(ETAG) .expirationTime(EXPIRATION_TIME) .friendlyName(FRIENDLY_NAME) - .id(ID) + .generatedId(GENERATED_ID) .lastModifiedTime(LAST_MODIFIED_TIME) .selfLink(SELF_LINK) .build(); @@ -110,7 +110,7 @@ public class TableInfoTest { .etag(ETAG) .expirationTime(EXPIRATION_TIME) .friendlyName(FRIENDLY_NAME) - .id(ID) + .generatedId(GENERATED_ID) .lastModifiedTime(LAST_MODIFIED_TIME) .selfLink(SELF_LINK) .build(); @@ -148,7 +148,7 @@ public void testBuilder() { assertEquals(ETAG, TABLE_INFO.etag()); assertEquals(EXPIRATION_TIME, TABLE_INFO.expirationTime()); assertEquals(FRIENDLY_NAME, TABLE_INFO.friendlyName()); - assertEquals(ID, TABLE_INFO.id()); + assertEquals(GENERATED_ID, TABLE_INFO.generatedId()); assertEquals(LAST_MODIFIED_TIME, TABLE_INFO.lastModifiedTime()); assertEquals(TABLE_DEFINITION, TABLE_INFO.definition()); assertEquals(SELF_LINK, TABLE_INFO.selfLink()); @@ -159,7 +159,7 @@ public void testBuilder() { assertEquals(ETAG, VIEW_INFO.etag()); assertEquals(EXPIRATION_TIME, VIEW_INFO.expirationTime()); assertEquals(FRIENDLY_NAME, VIEW_INFO.friendlyName()); - assertEquals(ID, VIEW_INFO.id()); + assertEquals(GENERATED_ID, VIEW_INFO.generatedId()); assertEquals(LAST_MODIFIED_TIME, VIEW_INFO.lastModifiedTime()); assertEquals(VIEW_TYPE, VIEW_INFO.definition()); assertEquals(SELF_LINK, VIEW_INFO.selfLink()); @@ -169,7 +169,7 @@ public void testBuilder() { assertEquals(ETAG, EXTERNAL_TABLE_INFO.etag()); assertEquals(EXPIRATION_TIME, EXTERNAL_TABLE_INFO.expirationTime()); assertEquals(FRIENDLY_NAME, EXTERNAL_TABLE_INFO.friendlyName()); - assertEquals(ID, EXTERNAL_TABLE_INFO.id()); + assertEquals(GENERATED_ID, EXTERNAL_TABLE_INFO.generatedId()); assertEquals(LAST_MODIFIED_TIME, EXTERNAL_TABLE_INFO.lastModifiedTime()); assertEquals(EXTERNAL_TABLE_DEFINITION, EXTERNAL_TABLE_INFO.definition()); assertEquals(SELF_LINK, EXTERNAL_TABLE_INFO.selfLink()); @@ -198,7 +198,7 @@ private void compareTableInfo(TableInfo expected, TableInfo value) { assertEquals(expected.etag(), value.etag()); assertEquals(expected.expirationTime(), value.expirationTime()); assertEquals(expected.friendlyName(), value.friendlyName()); - assertEquals(expected.id(), value.id()); + assertEquals(expected.generatedId(), value.generatedId()); assertEquals(expected.lastModifiedTime(), value.lastModifiedTime()); assertEquals(expected.selfLink(), value.selfLink()); assertEquals(expected.definition(), value.definition()); diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableTest.java b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableTest.java index c7828ebeadf4..cab71d4705d5 100644 --- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableTest.java +++ b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/TableTest.java @@ -44,7 +44,7 @@ public class TableTest { private static final String ETAG = "etag"; - private static final String ID = "project:dataset:table1"; + private static final String GENERATED_ID = "project:dataset:table1"; private static final String SELF_LINK = "selfLink"; private static final String FRIENDLY_NAME = "friendlyName"; private static final String DESCRIPTION = "description"; @@ -115,7 +115,7 @@ public void testBuilder() { .etag(ETAG) .expirationTime(EXPIRATION_TIME) .friendlyName(FRIENDLY_NAME) - .id(ID) + .generatedId(GENERATED_ID) .lastModifiedTime(LAST_MODIFIED_TIME) .selfLink(SELF_LINK) .build(); @@ -125,7 +125,7 @@ public void testBuilder() { assertEquals(ETAG, builtTable.etag()); assertEquals(EXPIRATION_TIME, builtTable.expirationTime()); assertEquals(FRIENDLY_NAME, builtTable.friendlyName()); - assertEquals(ID, builtTable.id()); + assertEquals(GENERATED_ID, builtTable.generatedId()); assertEquals(LAST_MODIFIED_TIME, builtTable.lastModifiedTime()); assertEquals(TABLE_DEFINITION, builtTable.definition()); assertEquals(SELF_LINK, builtTable.selfLink()); @@ -398,7 +398,7 @@ private void compareTableInfo(TableInfo expected, TableInfo value) { assertEquals(expected.etag(), value.etag()); assertEquals(expected.expirationTime(), value.expirationTime()); assertEquals(expected.friendlyName(), value.friendlyName()); - assertEquals(expected.id(), value.id()); + assertEquals(expected.generatedId(), value.generatedId()); assertEquals(expected.lastModifiedTime(), value.lastModifiedTime()); assertEquals(expected.selfLink(), value.selfLink()); assertEquals(expected.definition(), value.definition()); diff --git a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/it/ITBigQueryTest.java b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/it/ITBigQueryTest.java index 50780b4fc9a9..cc7f06a251db 100644 --- a/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/it/ITBigQueryTest.java +++ b/gcloud-java-bigquery/src/test/java/com/google/gcloud/bigquery/it/ITBigQueryTest.java @@ -71,6 +71,7 @@ import org.junit.AfterClass; import org.junit.BeforeClass; +import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; @@ -214,7 +215,7 @@ public void testGetDataset() { assertEquals(DESCRIPTION, dataset.description()); assertNotNull(dataset.acl()); assertNotNull(dataset.etag()); - assertNotNull(dataset.id()); + assertNotNull(dataset.generatedId()); assertNotNull(dataset.lastModified()); assertNotNull(dataset.selfLink()); } @@ -231,7 +232,7 @@ public void testGetDatasetWithSelectedFields() { assertNull(dataset.acl()); assertNull(dataset.etag()); assertNull(dataset.friendlyName()); - assertNull(dataset.id()); + assertNull(dataset.generatedId()); assertNull(dataset.lastModified()); assertNull(dataset.location()); assertNull(dataset.selfLink()); @@ -270,7 +271,7 @@ public void testUpdateDatasetWithSelectedFields() { assertNull(updatedDataset.acl()); assertNull(updatedDataset.etag()); assertNull(updatedDataset.friendlyName()); - assertNull(updatedDataset.id()); + assertNull(updatedDataset.generatedId()); assertNull(updatedDataset.lastModified()); assertNull(updatedDataset.location()); assertNull(updatedDataset.selfLink()); @@ -623,6 +624,7 @@ public void testInsertAllWithErrors() { assertTrue(bigquery.delete(TableId.of(DATASET, tableName))); } + @Ignore("Flaky test; see issue #836") @Test public void testListAllTableData() { Page> rows = bigquery.listTableData(TABLE_ID); @@ -697,7 +699,7 @@ public void testListJobs() { assertNotNull(job.statistics()); assertNotNull(job.status()); assertNotNull(job.userEmail()); - assertNotNull(job.id()); + assertNotNull(job.generatedId()); } } @@ -709,7 +711,7 @@ public void testListJobsWithSelectedFields() { assertNotNull(job.status()); assertNotNull(job.userEmail()); assertNull(job.statistics()); - assertNull(job.id()); + assertNull(job.generatedId()); } } @@ -906,6 +908,7 @@ public void testCancelNonExistingJob() { assertFalse(bigquery.cancel("test_cancel_non_existing_job")); } + @Ignore("Flaky test; see #836") @Test public void testInsertFromFile() throws InterruptedException { String destinationTableName = "test_insert_from_file_table"; diff --git a/gcloud-java-contrib/README.md b/gcloud-java-contrib/README.md index 426417d54e87..f0ead8c79dea 100644 --- a/gcloud-java-contrib/README.md +++ b/gcloud-java-contrib/README.md @@ -16,16 +16,16 @@ If you are using Maven, add this to your pom.xml file com.google.gcloud gcloud-java-contrib - 0.1.5 + 0.1.7 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.gcloud:gcloud-java-contrib:0.1.5' +compile 'com.google.gcloud:gcloud-java-contrib:0.1.7' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.gcloud" % "gcloud-java-contrib" % "0.1.5" +libraryDependencies += "com.google.gcloud" % "gcloud-java-contrib" % "0.1.7" ``` Java Versions diff --git a/gcloud-java-contrib/pom.xml b/gcloud-java-contrib/pom.xml index bd4a6458dc38..1ef855a1ae5d 100644 --- a/gcloud-java-contrib/pom.xml +++ b/gcloud-java-contrib/pom.xml @@ -10,7 +10,7 @@ com.google.gcloud gcloud-java-pom - 0.1.6-SNAPSHOT + 0.1.8-SNAPSHOT gcloud-java-contrib diff --git a/gcloud-java-core/README.md b/gcloud-java-core/README.md index fc5f481f8ec3..067505179bc9 100644 --- a/gcloud-java-core/README.md +++ b/gcloud-java-core/README.md @@ -19,16 +19,16 @@ If you are using Maven, add this to your pom.xml file com.google.gcloud gcloud-java-core - 0.1.5 + 0.1.7 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.gcloud:gcloud-java-core:0.1.5' +compile 'com.google.gcloud:gcloud-java-core:0.1.7' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.gcloud" % "gcloud-java-core" % "0.1.5" +libraryDependencies += "com.google.gcloud" % "gcloud-java-core" % "0.1.7" ``` Troubleshooting diff --git a/gcloud-java-core/pom.xml b/gcloud-java-core/pom.xml index 6d0ed675b423..df116b0b1be4 100644 --- a/gcloud-java-core/pom.xml +++ b/gcloud-java-core/pom.xml @@ -10,7 +10,7 @@ com.google.gcloud gcloud-java-pom - 0.1.6-SNAPSHOT + 0.1.8-SNAPSHOT gcloud-java-core diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/FieldSelector.java b/gcloud-java-core/src/main/java/com/google/gcloud/FieldSelector.java new file mode 100644 index 000000000000..be6ab73d00bf --- /dev/null +++ b/gcloud-java-core/src/main/java/com/google/gcloud/FieldSelector.java @@ -0,0 +1,96 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.gcloud; + +import com.google.common.base.Function; +import com.google.common.base.Joiner; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +/** + * Interface for Google Cloud resource's fields. Implementations of this interface can be used to + * select only desired fields from a returned Google Cloud resource. + */ +public interface FieldSelector { + + /** + * Returns a string selector. This selector is passed to a Google Cloud service (possibly with + * other field selectors) to specify which resource fields should be returned by an API call. + */ + String selector(); + + /** + * A helper class used to build composite selectors given a number of fields. This class is not + * supposed to be used directly by users. + */ + class Helper { + + private Helper() {} + + private static final Function FIELD_TO_STRING_FUNCTION = + new Function() { + @Override + public String apply(FieldSelector fieldSelector) { + return fieldSelector.selector(); + } + }; + + private static String selector(List required, FieldSelector[] others, + String... extraResourceFields) { + Set fieldStrings = Sets.newHashSetWithExpectedSize(required.size() + others.length); + fieldStrings.addAll(Lists.transform(required, FIELD_TO_STRING_FUNCTION)); + fieldStrings.addAll(Lists.transform(Arrays.asList(others), FIELD_TO_STRING_FUNCTION)); + fieldStrings.addAll(Arrays.asList(extraResourceFields)); + return Joiner.on(',').join(fieldStrings); + } + + /** + * Returns a composite selector given a number of fields. The string selector returned by this + * method can be used for field selection in API calls that return a single resource. This + * method is not supposed to be used directly by users. + */ + public static String selector(List required, FieldSelector... others) { + return selector(required, others, new String[]{}); + } + + /** + * Returns a composite selector given a number of fields and a container name. The string + * selector returned by this method can be used for field selection in API calls that return a + * list of resources. This method is not supposed to be used directly by users. + */ + public static String listSelector(String containerName, List required, + FieldSelector... others) { + return "nextPageToken," + containerName + '(' + selector(required, others) + ')'; + } + + /** + * Returns a composite selector given a number of fields and a container name. This methods also + * takes an {@code extraResourceFields} parameter to specify some extra fields as strings. The + * string selector returned by this method can be used for field selection in API calls that + * return a list of resources. This method is not supposed to be used directly by users. + */ + public static String listSelector(String containerName, List required, + FieldSelector[] others, String... extraResourceFields) { + return "nextPageToken," + containerName + '(' + + selector(required, others, extraResourceFields) + ')'; + } + } +} diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/ServiceOptions.java b/gcloud-java-core/src/main/java/com/google/gcloud/ServiceOptions.java index d45069434a26..d53cfcdafe24 100644 --- a/gcloud-java-core/src/main/java/com/google/gcloud/ServiceOptions.java +++ b/gcloud-java-core/src/main/java/com/google/gcloud/ServiceOptions.java @@ -27,10 +27,16 @@ import com.google.api.client.http.javanet.NetHttpTransport; import com.google.auth.http.HttpCredentialsAdapter; import com.google.common.collect.Iterables; +import com.google.common.io.Files; import com.google.gcloud.spi.ServiceRpcFactory; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.JSONTokener; + import java.io.BufferedReader; import java.io.File; +import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; @@ -42,6 +48,7 @@ import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.URL; +import java.nio.charset.Charset; import java.util.Enumeration; import java.util.Locale; import java.util.Objects; @@ -376,11 +383,26 @@ protected String defaultHost() { protected String defaultProject() { String projectId = System.getProperty(PROJECT_ENV_NAME, System.getenv(PROJECT_ENV_NAME)); if (projectId == null) { - projectId = getAppEngineProjectId(); + projectId = appEngineProjectId(); + } + if (projectId == null) { + projectId = serviceAccountProjectId(); } return projectId != null ? projectId : googleCloudProjectId(); } + private static String activeGoogleCloudConfig(File configDir) { + String activeGoogleCloudConfig = null; + try { + activeGoogleCloudConfig = + Files.readFirstLine(new File(configDir, "active_config"), Charset.defaultCharset()); + } catch (IOException ex) { + // ignore + } + // if reading active_config failed or the file is empty we try default + return firstNonNull(activeGoogleCloudConfig, "default"); + } + protected static String googleCloudProjectId() { File configDir; if (System.getenv().containsKey("CLOUDSDK_CONFIG")) { @@ -390,9 +412,10 @@ protected static String googleCloudProjectId() { } else { configDir = new File(System.getProperty("user.home"), ".config/gcloud"); } + String activeConfig = activeGoogleCloudConfig(configDir); FileReader fileReader = null; try { - fileReader = new FileReader(new File(configDir, "configurations/config_default")); + fileReader = new FileReader(new File(configDir, "configurations/config_" + activeConfig)); } catch (FileNotFoundException newConfigFileNotFoundEx) { try { fileReader = new FileReader(new File(configDir, "properties")); @@ -446,7 +469,7 @@ private static boolean isWindows() { return System.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("windows"); } - protected static String getAppEngineProjectId() { + protected static String appEngineProjectId() { try { Class factoryClass = Class.forName("com.google.appengine.api.appidentity.AppIdentityServiceFactory"); @@ -464,6 +487,20 @@ protected static String getAppEngineProjectId() { } } + protected static String serviceAccountProjectId() { + String project = null; + String credentialsPath = System.getenv("GOOGLE_APPLICATION_CREDENTIALS"); + if(credentialsPath != null) { + try (InputStream credentialsStream = new FileInputStream(credentialsPath)) { + JSONObject json = new JSONObject(new JSONTokener(credentialsStream)); + project = json.getString("project_id"); + } catch (IOException | JSONException ex) { + // ignore + } + } + return project; + } + @SuppressWarnings("unchecked") public ServiceT service() { if (service == null) { diff --git a/gcloud-java-core/src/test/java/com/google/gcloud/FieldSelectorHelperTest.java b/gcloud-java-core/src/test/java/com/google/gcloud/FieldSelectorHelperTest.java new file mode 100644 index 000000000000..9871c942180e --- /dev/null +++ b/gcloud-java-core/src/test/java/com/google/gcloud/FieldSelectorHelperTest.java @@ -0,0 +1,84 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.gcloud; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.google.common.collect.ImmutableList; +import com.google.gcloud.FieldSelector.Helper; + +import org.junit.Test; + +import java.util.List; + +public class FieldSelectorHelperTest { + + private static final FieldSelector FIELD1 = new FieldSelector() { + @Override + public String selector() { + return "field1"; + } + }; + private static final FieldSelector FIELD2 = new FieldSelector() { + @Override + public String selector() { + return "field2"; + } + }; + private static final FieldSelector FIELD3 = new FieldSelector() { + @Override + public String selector() { + return "field3"; + } + }; + private static final List REQUIRED_FIELDS = ImmutableList.of(FIELD1, FIELD2); + private static final String CONTAINER = "container"; + + @Test + public void testSelector() { + String selector = Helper.selector(REQUIRED_FIELDS, FIELD3); + assertTrue(selector.contains("field1")); + assertTrue(selector.contains("field2")); + assertTrue(selector.contains("field3")); + assertEquals(20, selector.length()); + } + + @Test + public void testListSelector() { + String selector = Helper.listSelector(CONTAINER, REQUIRED_FIELDS, FIELD3); + assertTrue(selector.startsWith("nextPageToken,container(")); + assertTrue(selector.contains("field1")); + assertTrue(selector.contains("field2")); + assertTrue(selector.contains("field3")); + assertTrue(selector.endsWith(")")); + assertEquals(45, selector.length()); + } + + @Test + public void testListSelectorWithExtraFields() { + String selector = Helper.listSelector(CONTAINER, REQUIRED_FIELDS, + new FieldSelector[]{FIELD3}, "field4"); + assertTrue(selector.startsWith("nextPageToken,container(")); + assertTrue(selector.contains("field1")); + assertTrue(selector.contains("field2")); + assertTrue(selector.contains("field3")); + assertTrue(selector.contains("field4")); + assertTrue(selector.endsWith(")")); + assertEquals(52, selector.length()); + } +} diff --git a/gcloud-java-datastore/README.md b/gcloud-java-datastore/README.md index 0d89a0a07e3e..69cf039472a3 100644 --- a/gcloud-java-datastore/README.md +++ b/gcloud-java-datastore/README.md @@ -22,16 +22,16 @@ If you are using Maven, add this to your pom.xml file com.google.gcloud gcloud-java-datastore - 0.1.5 + 0.1.7 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.gcloud:gcloud-java-datastore:0.1.5' +compile 'com.google.gcloud:gcloud-java-datastore:0.1.7' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.gcloud" % "gcloud-java-datastore" % "0.1.5" +libraryDependencies += "com.google.gcloud" % "gcloud-java-datastore" % "0.1.7" ``` Example Application diff --git a/gcloud-java-datastore/pom.xml b/gcloud-java-datastore/pom.xml index f3b46e22b3c8..22498ab505f4 100644 --- a/gcloud-java-datastore/pom.xml +++ b/gcloud-java-datastore/pom.xml @@ -10,7 +10,7 @@ com.google.gcloud gcloud-java-pom - 0.1.6-SNAPSHOT + 0.1.8-SNAPSHOT gcloud-java-datastore @@ -22,16 +22,14 @@ ${project.version} - com.google.apis - google-api-services-datastore-protobuf - v1beta2-rev1-4.0.0 - compile - - - com.google.api-client - google-api-client - - + com.google.cloud.datastore + datastore-v1beta3-protos + 1.0.0-beta + + + com.google.cloud.datastore + datastore-v1beta3-proto-client + 1.0.0-beta ${project.groupId} diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BaseDatastoreBatchWriter.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BaseDatastoreBatchWriter.java index b42c07d62320..3aa0d38f45f1 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BaseDatastoreBatchWriter.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BaseDatastoreBatchWriter.java @@ -16,11 +16,11 @@ package com.google.gcloud.datastore; -import com.google.api.services.datastore.DatastoreV1; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; +import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; @@ -88,9 +88,7 @@ public final List add(FullEntity... entities) { for (FullEntity entity : entities) { IncompleteKey key = entity.key(); Preconditions.checkArgument(key != null, "Entity must have a key"); - if (key instanceof Key) { - addInternal((FullEntity) entity); - } else { + if (!(key instanceof Key)) { incompleteKeys.add(key); } } @@ -104,6 +102,7 @@ public final List add(FullEntity... entities) { List answer = Lists.newArrayListWithExpectedSize(entities.length); for (FullEntity entity : entities) { if (entity.key() instanceof Key) { + addInternal((FullEntity) entity); answer.add(Entity.convert((FullEntity) entity)); } else { Entity entityWithAllocatedId = Entity.builder(allocated.next(), entity).build(); @@ -199,24 +198,30 @@ protected DatastoreException newInvalidRequest(String msg, Object... params) { return DatastoreException.throwInvalidRequest(String.format(msg, params)); } - DatastoreV1.Mutation.Builder toMutationPb() { - DatastoreV1.Mutation.Builder mutationPb = DatastoreV1.Mutation.newBuilder(); + protected List toMutationPbList() { + List mutationsPb = + new ArrayList<>(); for (FullEntity entity : toAddAutoId()) { - mutationPb.addInsertAutoId(entity.toPb()); + mutationsPb.add( + com.google.datastore.v1beta3.Mutation.newBuilder().setInsert(entity.toPb()).build()); } for (FullEntity entity : toAdd().values()) { - mutationPb.addInsert(entity.toPb()); + mutationsPb.add( + com.google.datastore.v1beta3.Mutation.newBuilder().setInsert(entity.toPb()).build()); } for (FullEntity entity : toUpdate().values()) { - mutationPb.addUpdate(entity.toPb()); + mutationsPb.add( + com.google.datastore.v1beta3.Mutation.newBuilder().setUpdate(entity.toPb()).build()); } for (FullEntity entity : toPut().values()) { - mutationPb.addUpsert(entity.toPb()); + mutationsPb.add( + com.google.datastore.v1beta3.Mutation.newBuilder().setUpsert(entity.toPb()).build()); } for (Key key : toDelete()) { - mutationPb.addDelete(key.toPb()); + mutationsPb.add( + com.google.datastore.v1beta3.Mutation.newBuilder().setDelete(key.toPb()).build()); } - return mutationPb; + return mutationsPb; } protected abstract Datastore datastore(); diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BaseEntity.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BaseEntity.java index 20c0b13e5001..c7d7219abfb8 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BaseEntity.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BaseEntity.java @@ -22,12 +22,12 @@ import static com.google.gcloud.datastore.DoubleValue.of; import static com.google.gcloud.datastore.EntityValue.of; import static com.google.gcloud.datastore.KeyValue.of; +import static com.google.gcloud.datastore.LatLngValue.of; import static com.google.gcloud.datastore.ListValue.of; import static com.google.gcloud.datastore.LongValue.of; import static com.google.gcloud.datastore.NullValue.of; import static com.google.gcloud.datastore.StringValue.of; -import com.google.api.services.datastore.DatastoreV1; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Maps; import com.google.protobuf.InvalidProtocolBufferException; @@ -49,7 +49,8 @@ * @see Google Cloud Datastore * Entities, Properties, and Keys */ -public abstract class BaseEntity extends Serializable { +public abstract class BaseEntity + extends Serializable { private static final long serialVersionUID = 8175618724683792766L; @@ -91,10 +92,11 @@ private B self() { } @SuppressWarnings("unchecked") - B fill(DatastoreV1.Entity entityPb) { + B fill(com.google.datastore.v1beta3.Entity entityPb) { Map> copiedProperties = Maps.newHashMap(); - for (DatastoreV1.Property property : entityPb.getPropertyList()) { - copiedProperties.put(property.getName(), Value.fromPb(property.getValue())); + for (Map.Entry entry : + entityPb.getProperties().entrySet()) { + copiedProperties.put(entry.getKey(), Value.fromPb(entry.getValue())); } properties(copiedProperties); if (entityPb.hasKey()) { @@ -290,6 +292,36 @@ public B set(String name, DateTime first, DateTime second, DateTime... others) { return self(); } + /** + * Sets a property of type {@link LatLng}. + * + * @param name name of the property + * @param value value associated with the property + */ + public B set(String name, LatLng value) { + properties.put(name, of(value)); + return self(); + } + + /** + * Sets a list property containing elements of type {@link LatLng}. + * + * @param name name of the property + * @param first the first {@link LatLng} in the list + * @param second the second {@link LatLng} in the list + * @param others other {@link LatLng}s in the list + */ + public B set(String name, LatLng first, LatLng second, LatLng... others) { + List values = new LinkedList<>(); + values.add(of(first)); + values.add(of(second)); + for (LatLng other : others) { + values.add(of(other)); + } + properties.put(name, of(values)); + return self(); + } + /** * Sets a property of type {@link KeyValue}. * @@ -545,6 +577,17 @@ public DateTime getDateTime(String name) { return ((Value) getValue(name)).get(); } + /** + * Returns the property value as a LatLng. + * + * @throws DatastoreException if not such property. + * @throws ClassCastException if value is not a LatLng. + */ + @SuppressWarnings("unchecked") + public LatLng getLatLng(String name) { + return ((Value) getValue(name)).get(); + } + /** * Returns the property value as a Key. * @@ -603,20 +646,19 @@ ImmutableSortedMap> properties() { @Override Object fromPb(byte[] bytesPb) throws InvalidProtocolBufferException { Builder builder = emptyBuilder(); - builder.fill(DatastoreV1.Entity.parseFrom(bytesPb)); + builder.fill(com.google.datastore.v1beta3.Entity.parseFrom(bytesPb)); return builder.build(); } protected abstract Builder emptyBuilder(); @Override - final DatastoreV1.Entity toPb() { - DatastoreV1.Entity.Builder entityPb = DatastoreV1.Entity.newBuilder(); + final com.google.datastore.v1beta3.Entity toPb() { + com.google.datastore.v1beta3.Entity.Builder entityPb = + com.google.datastore.v1beta3.Entity.newBuilder(); + Map propertiesPb = entityPb.getMutableProperties(); for (Map.Entry> entry : properties.entrySet()) { - DatastoreV1.Property.Builder propertyPb = DatastoreV1.Property.newBuilder(); - propertyPb.setName(entry.getKey()); - propertyPb.setValue(entry.getValue().toPb()); - entityPb.addProperty(propertyPb.build()); + propertiesPb.put(entry.getKey(), entry.getValue().toPb()); } if (key != null) { entityPb.setKey(key.toPb()); diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BaseKey.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BaseKey.java index 4ab6f51b6767..f2bb87e740d0 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BaseKey.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BaseKey.java @@ -20,7 +20,6 @@ import static com.google.gcloud.datastore.Validator.validateKind; import static com.google.gcloud.datastore.Validator.validateNamespace; -import com.google.api.services.datastore.DatastoreV1; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; @@ -31,7 +30,7 @@ /** * Base class for keys. */ -public abstract class BaseKey extends Serializable { +public abstract class BaseKey extends Serializable { private static final long serialVersionUID = -4671243265877410635L; @@ -46,8 +45,8 @@ public abstract class BaseKey extends Serializable { */ protected abstract static class Builder> { - String projectId; - String namespace; + String projectId = ""; + String namespace = ""; String kind; final List ancestors; @@ -179,20 +178,15 @@ public boolean equals(Object obj) { } @Override - DatastoreV1.Key toPb() { - DatastoreV1.Key.Builder keyPb = DatastoreV1.Key.newBuilder(); - DatastoreV1.PartitionId.Builder partitionIdPb = DatastoreV1.PartitionId.newBuilder(); - if (projectId != null) { - partitionIdPb.setDatasetId(projectId); - } - if (namespace != null) { - partitionIdPb.setNamespace(namespace); - } - if (partitionIdPb.hasDatasetId() || partitionIdPb.hasNamespace()) { - keyPb.setPartitionId(partitionIdPb.build()); - } + com.google.datastore.v1beta3.Key toPb() { + com.google.datastore.v1beta3.Key.Builder keyPb = com.google.datastore.v1beta3.Key.newBuilder(); + com.google.datastore.v1beta3.PartitionId.Builder partitionIdPb = + com.google.datastore.v1beta3.PartitionId.newBuilder(); + partitionIdPb.setProjectId(projectId); + partitionIdPb.setNamespaceId(namespace); + keyPb.setPartitionId(partitionIdPb.build()); for (PathElement pathEntry : path) { - keyPb.addPathElement(pathEntry.toPb()); + keyPb.addPath(pathEntry.toPb()); } return keyPb.build(); } diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BatchImpl.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BatchImpl.java index 8cb41304500b..303e9703f4cc 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BatchImpl.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BatchImpl.java @@ -16,63 +16,53 @@ package com.google.gcloud.datastore; -import com.google.api.services.datastore.DatastoreV1; -import com.google.common.base.Function; -import com.google.common.collect.Lists; -import com.google.gcloud.datastore.BatchOption.ForceWrites; - +import java.util.ArrayList; +import java.util.Iterator; import java.util.List; -import java.util.Map; class BatchImpl extends BaseDatastoreBatchWriter implements Batch { private final DatastoreImpl datastore; - private final boolean force; static class ResponseImpl implements Batch.Response { - private final DatastoreV1.CommitResponse response; + private final com.google.datastore.v1beta3.CommitResponse response; + private final int numAutoAllocatedIds; - ResponseImpl(DatastoreV1.CommitResponse response) { + ResponseImpl(com.google.datastore.v1beta3.CommitResponse response, int numAutoAllocatedIds) { this.response = response; + this.numAutoAllocatedIds = numAutoAllocatedIds; } @Override public List generatedKeys() { - return Lists.transform(response.getMutationResult().getInsertAutoIdKeyList(), - new Function() { - @Override public Key apply(DatastoreV1.Key keyPb) { - return Key.fromPb(keyPb); - } - }); + Iterator results = + response.getMutationResultsList().iterator(); + List generated = new ArrayList<>(numAutoAllocatedIds); + for (int i = 0; i < numAutoAllocatedIds; i++) { + generated.add(Key.fromPb(results.next().getKey())); + } + return generated; } } - BatchImpl(DatastoreImpl datastore, BatchOption... options) { + BatchImpl(DatastoreImpl datastore) { super("batch"); this.datastore = datastore; - Map, BatchOption> optionsMap = BatchOption.asImmutableMap(options); - if (optionsMap.containsKey(ForceWrites.class)) { - force = ((ForceWrites) optionsMap.get(ForceWrites.class)).force(); - } else { - force = datastore.options().force(); - } } @Override public Batch.Response submit() { validateActive(); - DatastoreV1.Mutation.Builder mutationPb = toMutationPb(); - if (force) { - mutationPb.setForce(force); - } - DatastoreV1.CommitRequest.Builder requestPb = DatastoreV1.CommitRequest.newBuilder(); - requestPb.setMode(DatastoreV1.CommitRequest.Mode.NON_TRANSACTIONAL); - requestPb.setMutation(mutationPb); - DatastoreV1.CommitResponse responsePb = datastore.commit(requestPb.build()); + List mutationsPb = toMutationPbList(); + com.google.datastore.v1beta3.CommitRequest.Builder requestPb = + com.google.datastore.v1beta3.CommitRequest.newBuilder(); + requestPb.setMode(com.google.datastore.v1beta3.CommitRequest.Mode.NON_TRANSACTIONAL); + requestPb.addAllMutations(mutationsPb); + com.google.datastore.v1beta3.CommitResponse responsePb = datastore.commit(requestPb.build()); deactivate(); - return new ResponseImpl(responsePb); + return new ResponseImpl(responsePb, toAddAutoId().size()); } @Override diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BatchOption.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BatchOption.java deleted file mode 100644 index 362a74e96c79..000000000000 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BatchOption.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2015 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.gcloud.datastore; - -import com.google.common.collect.ImmutableMap; - -import java.util.Map; - -public abstract class BatchOption implements java.io.Serializable { - - private static final long serialVersionUID = -3932758377282659839L; - - public static final class ForceWrites extends BatchOption { - - private static final long serialVersionUID = 2555054296046232799L; - - private final boolean force; - - public ForceWrites(boolean force) { - this.force = force; - } - - public boolean force() { - return force; - } - } - - BatchOption() { - // package protected - } - - public static ForceWrites forceWrites() { - return new ForceWrites(true); - } - - static Map, BatchOption> asImmutableMap(BatchOption... options) { - ImmutableMap.Builder, BatchOption> builder = - ImmutableMap.builder(); - for (BatchOption option : options) { - builder.put(option.getClass(), option); - } - return builder.build(); - } -} diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Blob.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Blob.java index 42a98e60b5e6..b86c4ccb963e 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Blob.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Blob.java @@ -18,8 +18,6 @@ import static com.google.common.base.Preconditions.checkNotNull; -import com.google.api.services.datastore.DatastoreV1; -import com.google.api.services.datastore.DatastoreV1.Value; import com.google.common.base.MoreObjects; import com.google.common.base.MoreObjects.ToStringHelper; import com.google.protobuf.ByteString; @@ -38,7 +36,7 @@ * @see * Google Cloud Datastore Entities, Properties, and Keys */ -public final class Blob extends Serializable { +public final class Blob extends Serializable { private static final long serialVersionUID = 3835421019618247721L; @@ -147,12 +145,12 @@ public static Blob copyFrom(InputStream input) throws IOException { } @Override - Value toPb() { - return DatastoreV1.Value.newBuilder().setBlobValue(byteString).build(); + com.google.datastore.v1beta3.Value toPb() { + return com.google.datastore.v1beta3.Value.newBuilder().setBlobValue(byteString).build(); } @Override Object fromPb(byte[] bytesPb) throws InvalidProtocolBufferException { - return new Blob(DatastoreV1.Value.parseFrom(bytesPb).getBlobValue()); + return new Blob(com.google.datastore.v1beta3.Value.parseFrom(bytesPb).getBlobValue()); } } diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BlobValue.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BlobValue.java index fb61c0b9ad34..19d545e1790c 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BlobValue.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BlobValue.java @@ -16,9 +16,7 @@ package com.google.gcloud.datastore; -import static com.google.api.services.datastore.DatastoreV1.Value.BLOB_VALUE_FIELD_NUMBER; - -import com.google.api.services.datastore.DatastoreV1; +import static com.google.datastore.v1beta3.Value.BLOB_VALUE_FIELD_NUMBER; public final class BlobValue extends Value { @@ -40,12 +38,12 @@ public Builder newBuilder(Blob value) { } @Override - protected Blob getValue(DatastoreV1.Value from) { + protected Blob getValue(com.google.datastore.v1beta3.Value from) { return new Blob(from.getBlobValue()); } @Override - protected void setValue(BlobValue from, DatastoreV1.Value.Builder to) { + protected void setValue(BlobValue from, com.google.datastore.v1beta3.Value.Builder to) { to.setBlobValue(from.get().byteString()); } }; diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BooleanValue.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BooleanValue.java index 2dd98a5013ac..3e1bdc14e822 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BooleanValue.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/BooleanValue.java @@ -16,9 +16,7 @@ package com.google.gcloud.datastore; -import static com.google.api.services.datastore.DatastoreV1.Value.BOOLEAN_VALUE_FIELD_NUMBER; - -import com.google.api.services.datastore.DatastoreV1; +import static com.google.datastore.v1beta3.Value.BOOLEAN_VALUE_FIELD_NUMBER; public final class BooleanValue extends Value { @@ -40,12 +38,12 @@ public Builder newBuilder(Boolean value) { } @Override - protected Boolean getValue(DatastoreV1.Value from) { + protected Boolean getValue(com.google.datastore.v1beta3.Value from) { return from.getBooleanValue(); } @Override - protected void setValue(BooleanValue from, DatastoreV1.Value.Builder to) { + protected void setValue(BooleanValue from, com.google.datastore.v1beta3.Value.Builder to) { to.setBooleanValue(from.get()); } }; diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Cursor.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Cursor.java index 5e577f7feb6c..c4d2b37672da 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Cursor.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Cursor.java @@ -18,8 +18,6 @@ import static com.google.common.base.Preconditions.checkNotNull; -import com.google.api.services.datastore.DatastoreV1; -import com.google.api.services.datastore.DatastoreV1.Value; import com.google.common.base.MoreObjects; import com.google.common.base.MoreObjects.ToStringHelper; import com.google.common.io.BaseEncoding; @@ -30,7 +28,7 @@ * A Google Cloud Datastore cursor. * The cursor can be used to as a starting point or an ending point for a {@link Query} */ -public final class Cursor extends Serializable { +public final class Cursor extends Serializable { private static final long serialVersionUID = -1423744878777486541L; @@ -87,16 +85,16 @@ public static Cursor copyFrom(byte[] bytes) { } @Override - Value toPb() { - return DatastoreV1.Value.newBuilder().setBlobValue(byteString).build(); + com.google.datastore.v1beta3.Value toPb() { + return com.google.datastore.v1beta3.Value.newBuilder().setBlobValue(byteString).build(); } @Override Object fromPb(byte[] bytesPb) throws InvalidProtocolBufferException { - return fromPb(DatastoreV1.Value.parseFrom(bytesPb)); + return fromPb(com.google.datastore.v1beta3.Value.parseFrom(bytesPb)); } - static Cursor fromPb(DatastoreV1.Value valuePb) { + static Cursor fromPb(com.google.datastore.v1beta3.Value valuePb) { return new Cursor(valuePb.getBlobValue()); } } diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Datastore.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Datastore.java index 870ed8d9474f..c0efaa52b4e8 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Datastore.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Datastore.java @@ -18,6 +18,7 @@ import com.google.gcloud.Service; +import java.util.Iterator; import java.util.List; /** @@ -30,8 +31,7 @@ public interface Datastore extends Service, DatastoreReaderWri * * @throws DatastoreException upon failure */ - Transaction newTransaction(TransactionOption... options); - + Transaction newTransaction(); /** * A callback for running with a transactional @@ -45,7 +45,6 @@ interface TransactionCallable { T run(DatastoreReaderWriter readerWriter) throws Exception; } - /** * Invokes the callback's {@link Datastore.TransactionCallable#run} method with a * {@link DatastoreReaderWriter} that is associated with a new transaction. @@ -54,15 +53,14 @@ interface TransactionCallable { * as a {@link DatastoreException} with the original exception as its root cause. * * @param callable the callback to call with a newly created transactional readerWriter - * @param options the options for the created transaction * @throws DatastoreException upon failure */ - T runInTransaction(TransactionCallable callable, TransactionOption... options); + T runInTransaction(TransactionCallable callable); /** * Returns a new Batch for processing multiple write operations in one request. */ - Batch newBatch(BatchOption... options); + Batch newBatch(); /** * Allocate a unique id for the given key. @@ -106,4 +104,39 @@ interface TransactionCallable { * Returns a new KeyFactory for this service */ KeyFactory newKeyFactory(); + + /** + * Returns an {@link Entity} for the given {@link Key} or {@code null} if it doesn't exist. + * {@link ReadOption}s can be specified if desired. + * + * @throws DatastoreException upon failure + */ + Entity get(Key key, ReadOption... options); + + /** + * Returns an {@link Entity} for each given {@link Key} that exists in the Datastore. The order of + * the result is unspecified. Results are loaded lazily, so it is possible to get a + * {@code DatastoreException} from the returned {@code Iterator}'s + * {@link Iterator#hasNext hasNext} or {@link Iterator#next next} methods. {@link ReadOption}s can + * be specified if desired. + * + * @throws DatastoreException upon failure + * @see #get(Key) + */ + Iterator get(Iterable keys, ReadOption... options); + + /** + * Returns a list with a value for each given key (ordered by input). {@code null} values are + * returned for nonexistent keys. When possible prefer using {@link #get(Key...)} to avoid eagerly + * loading the results. {@link ReadOption}s can be specified if desired. + */ + List fetch(Iterable keys, ReadOption... options); + + /** + * Submits a {@link Query} and returns its result. {@link ReadOption}s can be specified if + * desired. + * + * @throws DatastoreException upon failure + */ + QueryResults run(Query query, ReadOption... options); } diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreException.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreException.java index ecad69ac635b..a940fe573f93 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreException.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreException.java @@ -34,9 +34,7 @@ public class DatastoreException extends BaseServiceException { // see https://cloud.google.com/datastore/docs/concepts/errors#Error_Codes" private static final Set RETRYABLE_ERRORS = ImmutableSet.of( - new Error(409, "ABORTED"), - new Error(403, "DEADLINE_EXCEEDED"), - new Error(503, "UNAVAILABLE")); + new Error(10, "ABORTED"), new Error(4, "DEADLINE_EXCEEDED"), new Error(14, "UNAVAILABLE")); private static final long serialVersionUID = 2663750991205874435L; public DatastoreException(int code, String message, String reason, Throwable cause) { diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreHelper.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreHelper.java index a74d06642740..e3cf9c055576 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreHelper.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreHelper.java @@ -20,6 +20,8 @@ import com.google.common.collect.Maps; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -33,13 +35,16 @@ class DatastoreHelper { private DatastoreHelper() { } - static Key allocateId(Datastore service, IncompleteKey key) { return service.allocateId(new IncompleteKey[]{key}).get(0); } - static Entity get(DatastoreReader reader, Key key) { - return Iterators.getNext(reader.get(new Key[]{key}), null); + static Entity get(Transaction reader, Key key) { + return Iterators.getNext(reader.get(new Key[] {key}), null); + } + + static Entity get(Datastore reader, Key key, ReadOption... options) { + return Iterators.getNext(reader.get(Collections.singletonList(key), options), null); } static Entity add(DatastoreWriter writer, FullEntity entity) { @@ -51,11 +56,22 @@ static KeyFactory newKeyFactory(DatastoreOptions options) { } /** - * Returns a list with a value for each given key (ordered by input). - * A {@code null} would be returned for non-existing keys. + * Returns a list with a value for each given key (ordered by input). {@code null} values are + * returned for nonexistent keys. */ - static List fetch(DatastoreReader reader, Key... keys) { - Iterator entities = reader.get(keys); + static List fetch(Transaction reader, Key... keys) { + return compileEntities(keys, reader.get(keys)); + } + + /** + * Returns a list with a value for each given key (ordered by input). {@code null} values are + * returned for nonexistent keys. + */ + static List fetch(Datastore reader, Key[] keys, ReadOption... options) { + return compileEntities(keys, reader.get(Arrays.asList(keys), options)); + } + + private static List compileEntities(Key[] keys, Iterator entities) { Map map = Maps.newHashMapWithExpectedSize(keys.length); while (entities.hasNext()) { Entity entity = entities.next(); @@ -63,15 +79,14 @@ static List fetch(DatastoreReader reader, Key... keys) { } List list = new ArrayList<>(keys.length); for (Key key : keys) { - // this will include nulls for non-existing keys + // this will include nulls for nonexistent keys list.add(map.get(key)); } return list; } - static T runInTransaction(Datastore datastore, - Datastore.TransactionCallable callable, TransactionOption... options) { - Transaction transaction = datastore.newTransaction(options); + static T runInTransaction(Datastore datastore, Datastore.TransactionCallable callable) { + Transaction transaction = datastore.newTransaction(); try { T value = callable.run(transaction); transaction.commit(); diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreImpl.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreImpl.java index 49a5728a4da9..4193931ab990 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreImpl.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreImpl.java @@ -16,19 +16,22 @@ package com.google.gcloud.datastore; -import com.google.api.services.datastore.DatastoreV1; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; import com.google.common.collect.AbstractIterator; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; import com.google.common.collect.Sets; +import com.google.datastore.v1beta3.ReadOptions.ReadConsistency; import com.google.gcloud.BaseService; import com.google.gcloud.RetryHelper; import com.google.gcloud.RetryHelper.RetryHelperException; import com.google.gcloud.RetryParams; +import com.google.gcloud.datastore.ReadOption.EventualConsistency; import com.google.gcloud.datastore.spi.DatastoreRpc; import com.google.protobuf.ByteString; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; @@ -51,18 +54,18 @@ final class DatastoreImpl extends BaseService implements Datas } @Override - public Batch newBatch(BatchOption... options) { - return new BatchImpl(this, options); + public Batch newBatch() { + return new BatchImpl(this); } @Override - public Transaction newTransaction(TransactionOption... options) { - return new TransactionImpl(this, options); + public Transaction newTransaction() { + return new TransactionImpl(this); } @Override - public T runInTransaction(TransactionCallable callable, TransactionOption... options) { - return DatastoreHelper.runInTransaction(this, callable, options); + public T runInTransaction(TransactionCallable callable) { + return DatastoreHelper.runInTransaction(this, callable); } @Override @@ -70,14 +73,22 @@ public QueryResults run(Query query) { return run(null, query); } - QueryResults run(DatastoreV1.ReadOptions readOptionsPb, Query query) { + @Override + public QueryResults run(Query query, ReadOption... options) { + return run(toReadOptionsPb(options), query); + } + + QueryResults run(com.google.datastore.v1beta3.ReadOptions readOptionsPb, Query query) { return new QueryResultsImpl<>(this, readOptionsPb, query); } - DatastoreV1.RunQueryResponse runQuery(final DatastoreV1.RunQueryRequest requestPb) { + com.google.datastore.v1beta3.RunQueryResponse runQuery( + final com.google.datastore.v1beta3.RunQueryRequest requestPb) { try { - return RetryHelper.runWithRetries(new Callable() { - @Override public DatastoreV1.RunQueryResponse call() throws DatastoreException { + return RetryHelper.runWithRetries( + new Callable() { + @Override public com.google.datastore.v1beta3.RunQueryResponse call() + throws DatastoreException { return datastoreRpc.runQuery(requestPb); } }, retryParams, EXCEPTION_HANDLER); @@ -96,22 +107,26 @@ public List allocateId(IncompleteKey... keys) { if (keys.length == 0) { return Collections.emptyList(); } - DatastoreV1.AllocateIdsRequest.Builder requestPb = DatastoreV1.AllocateIdsRequest.newBuilder(); + com.google.datastore.v1beta3.AllocateIdsRequest.Builder requestPb = + com.google.datastore.v1beta3.AllocateIdsRequest.newBuilder(); for (IncompleteKey key : keys) { - requestPb.addKey(trimNameOrId(key).toPb()); + requestPb.addKeys(trimNameOrId(key).toPb()); } - DatastoreV1.AllocateIdsResponse responsePb = allocateIds(requestPb.build()); + com.google.datastore.v1beta3.AllocateIdsResponse responsePb = allocateIds(requestPb.build()); ImmutableList.Builder keyList = ImmutableList.builder(); - for (DatastoreV1.Key keyPb : responsePb.getKeyList()) { + for (com.google.datastore.v1beta3.Key keyPb : responsePb.getKeysList()) { keyList.add(Key.fromPb(keyPb)); } return keyList.build(); } - DatastoreV1.AllocateIdsResponse allocateIds(final DatastoreV1.AllocateIdsRequest requestPb) { + com.google.datastore.v1beta3.AllocateIdsResponse allocateIds( + final com.google.datastore.v1beta3.AllocateIdsRequest requestPb) { try { - return RetryHelper.runWithRetries(new Callable() { - @Override public DatastoreV1.AllocateIdsResponse call() throws DatastoreException { + return RetryHelper.runWithRetries( + new Callable() { + @Override public com.google.datastore.v1beta3.AllocateIdsResponse call() + throws DatastoreException { return datastoreRpc.allocateIds(requestPb); } }, retryParams, EXCEPTION_HANDLER); @@ -138,7 +153,7 @@ public List add(FullEntity... entities) { if (entities.length == 0) { return Collections.emptyList(); } - DatastoreV1.Mutation.Builder mutationPb = DatastoreV1.Mutation.newBuilder(); + List mutationsPb = new ArrayList<>(); Map completeEntities = new LinkedHashMap<>(); for (FullEntity entity : entities) { Entity completeEntity = null; @@ -150,22 +165,24 @@ public List add(FullEntity... entities) { throw DatastoreException.throwInvalidRequest( "Duplicate entity with the key %s", entity.key()); } - mutationPb.addInsert(completeEntity.toPb()); } else { Preconditions.checkArgument(entity.hasKey(), "entity %s is missing a key", entity); - mutationPb.addInsertAutoId(entity.toPb()); } + mutationsPb.add(com.google.datastore.v1beta3.Mutation.newBuilder() + .setInsert(entity.toPb()).build()); } - DatastoreV1.CommitResponse commitResponse = commitMutation(mutationPb); - Iterator allocatedKeys = - commitResponse.getMutationResult().getInsertAutoIdKeyList().iterator(); + com.google.datastore.v1beta3.CommitResponse commitResponse = commitMutation(mutationsPb); + Iterator mutationResults = + commitResponse.getMutationResultsList().iterator(); ImmutableList.Builder responseBuilder = ImmutableList.builder(); for (FullEntity entity : entities) { Entity completeEntity = completeEntities.get(entity.key()); if (completeEntity != null) { responseBuilder.add(completeEntity); + mutationResults.next(); } else { - responseBuilder.add(Entity.builder(Key.fromPb(allocatedKeys.next()), entity).build()); + responseBuilder.add( + Entity.builder(Key.fromPb(mutationResults.next().getKey()), entity).build()); } } return responseBuilder.build(); @@ -176,46 +193,73 @@ public Entity get(Key key) { return DatastoreHelper.get(this, key); } + @Override + public Entity get(Key key, ReadOption... options) { + return DatastoreHelper.get(this, key, options); + } + @Override public Iterator get(Key... keys) { return get(null, keys); } + @Override + public Iterator get(Iterable keys, ReadOption... options) { + return get(toReadOptionsPb(options), Iterables.toArray(keys, Key.class)); + } + + private static com.google.datastore.v1beta3.ReadOptions toReadOptionsPb(ReadOption... options) { + com.google.datastore.v1beta3.ReadOptions readOptionsPb = null; + if (options != null + && ReadOption.asImmutableMap(options).containsKey(EventualConsistency.class)) { + readOptionsPb = com.google.datastore.v1beta3.ReadOptions.newBuilder() + .setReadConsistency(ReadConsistency.EVENTUAL) + .build(); + } + return readOptionsPb; + } + @Override public List fetch(Key... keys) { return DatastoreHelper.fetch(this, keys); } - Iterator get(DatastoreV1.ReadOptions readOptionsPb, final Key... keys) { + @Override + public List fetch(Iterable keys, ReadOption... options) { + return DatastoreHelper.fetch(this, Iterables.toArray(keys, Key.class), options); + } + + Iterator get(com.google.datastore.v1beta3.ReadOptions readOptionsPb, final Key... keys) { if (keys.length == 0) { return Collections.emptyIterator(); } - DatastoreV1.LookupRequest.Builder requestPb = DatastoreV1.LookupRequest.newBuilder(); + com.google.datastore.v1beta3.LookupRequest.Builder requestPb = + com.google.datastore.v1beta3.LookupRequest.newBuilder(); if (readOptionsPb != null) { requestPb.setReadOptions(readOptionsPb); } for (Key k : Sets.newLinkedHashSet(Arrays.asList(keys))) { - requestPb.addKey(k.toPb()); + requestPb.addKeys(k.toPb()); } return new ResultsIterator(requestPb); } final class ResultsIterator extends AbstractIterator { - private final DatastoreV1.LookupRequest.Builder requestPb; - Iterator iter; + private final com.google.datastore.v1beta3.LookupRequest.Builder requestPb; + Iterator iter; - ResultsIterator(DatastoreV1.LookupRequest.Builder requestPb) { + ResultsIterator(com.google.datastore.v1beta3.LookupRequest.Builder requestPb) { this.requestPb = requestPb; loadResults(); } private void loadResults() { - DatastoreV1.LookupResponse responsePb = lookup(requestPb.build()); + com.google.datastore.v1beta3.LookupResponse responsePb = lookup(requestPb.build()); iter = responsePb.getFoundList().iterator(); - requestPb.clearKey(); + requestPb.clearKeys(); if (responsePb.getDeferredCount() > 0) { - requestPb.addAllKey(responsePb.getDeferredList()); + requestPb.addAllKeys(responsePb.getDeferredList()); } } @@ -223,7 +267,7 @@ private void loadResults() { @Override protected Entity computeNext() { while (!iter.hasNext()) { - if (requestPb.getKeyCount() == 0) { + if (requestPb.getKeysCount() == 0) { return endOfData(); } loadResults(); @@ -232,10 +276,13 @@ protected Entity computeNext() { } } - DatastoreV1.LookupResponse lookup(final DatastoreV1.LookupRequest requestPb) { + com.google.datastore.v1beta3.LookupResponse lookup( + final com.google.datastore.v1beta3.LookupRequest requestPb) { try { - return RetryHelper.runWithRetries(new Callable() { - @Override public DatastoreV1.LookupResponse call() throws DatastoreException { + return RetryHelper.runWithRetries( + new Callable() { + @Override public com.google.datastore.v1beta3.LookupResponse call() + throws DatastoreException { return datastoreRpc.lookup(requestPb); } }, retryParams, EXCEPTION_HANDLER); @@ -248,15 +295,17 @@ DatastoreV1.LookupResponse lookup(final DatastoreV1.LookupRequest requestPb) { @Override public final void update(Entity... entities) { if (entities.length > 0) { - DatastoreV1.Mutation.Builder mutationPb = DatastoreV1.Mutation.newBuilder(); + List mutationsPb = + new ArrayList<>(); Map dedupEntities = new LinkedHashMap<>(); for (Entity entity : entities) { dedupEntities.put(entity.key(), entity); } for (Entity entity : dedupEntities.values()) { - mutationPb.addUpdate(entity.toPb()); + mutationsPb.add( + com.google.datastore.v1beta3.Mutation.newBuilder().setUpdate(entity.toPb()).build()); } - commitMutation(mutationPb); + commitMutation(mutationsPb); } } @@ -264,27 +313,30 @@ public final void update(Entity... entities) { @Override public final void put(Entity... entities) { if (entities.length > 0) { - DatastoreV1.Mutation.Builder mutationPb = DatastoreV1.Mutation.newBuilder(); + List mutationsPb = + new ArrayList<>(); Map dedupEntities = new LinkedHashMap<>(); for (Entity entity : entities) { dedupEntities.put(entity.key(), entity); } for (Entity e : dedupEntities.values()) { - mutationPb.addUpsert(e.toPb()); + mutationsPb.add( + com.google.datastore.v1beta3.Mutation.newBuilder().setUpsert(e.toPb()).build()); } - commitMutation(mutationPb); + commitMutation(mutationsPb); } } @Override public void delete(Key... keys) { if (keys.length > 0) { - DatastoreV1.Mutation.Builder mutationPb = DatastoreV1.Mutation.newBuilder(); + List mutationsPb = new ArrayList<>(); Set dedupKeys = new LinkedHashSet<>(Arrays.asList(keys)); for (Key key : dedupKeys) { - mutationPb.addDelete(key.toPb()); + mutationsPb.add( + com.google.datastore.v1beta3.Mutation.newBuilder().setDelete(key.toPb()).build()); } - commitMutation(mutationPb); + commitMutation(mutationsPb); } } @@ -293,53 +345,63 @@ public KeyFactory newKeyFactory() { return DatastoreHelper.newKeyFactory(options()); } - private DatastoreV1.CommitResponse commitMutation(DatastoreV1.Mutation.Builder mutationPb) { - if (options().force()) { - mutationPb.setForce(true); - } - DatastoreV1.CommitRequest.Builder requestPb = DatastoreV1.CommitRequest.newBuilder(); - requestPb.setMode(DatastoreV1.CommitRequest.Mode.NON_TRANSACTIONAL); - requestPb.setMutation(mutationPb); + private com.google.datastore.v1beta3.CommitResponse commitMutation( + List mutationsPb) { + com.google.datastore.v1beta3.CommitRequest.Builder requestPb = + com.google.datastore.v1beta3.CommitRequest.newBuilder(); + requestPb.setMode(com.google.datastore.v1beta3.CommitRequest.Mode.NON_TRANSACTIONAL); + requestPb.addAllMutations(mutationsPb); return commit(requestPb.build()); } - DatastoreV1.CommitResponse commit(final DatastoreV1.CommitRequest requestPb) { + com.google.datastore.v1beta3.CommitResponse commit( + final com.google.datastore.v1beta3.CommitRequest requestPb) { try { - return RetryHelper.runWithRetries(new Callable() { - @Override public DatastoreV1.CommitResponse call() throws DatastoreException { - return datastoreRpc.commit(requestPb); - } - }, retryParams, EXCEPTION_HANDLER); + return RetryHelper.runWithRetries( + new Callable() { + @Override + public com.google.datastore.v1beta3.CommitResponse call() throws DatastoreException { + return datastoreRpc.commit(requestPb); + } + }, + retryParams, + EXCEPTION_HANDLER); } catch (RetryHelperException e) { throw DatastoreException.translateAndThrow(e); } } - ByteString requestTransactionId(DatastoreV1.BeginTransactionRequest.Builder requestPb) { + ByteString requestTransactionId( + com.google.datastore.v1beta3.BeginTransactionRequest.Builder requestPb) { return beginTransaction(requestPb.build()).getTransaction(); } - DatastoreV1.BeginTransactionResponse beginTransaction( - final DatastoreV1.BeginTransactionRequest requestPb) { + com.google.datastore.v1beta3.BeginTransactionResponse beginTransaction( + final com.google.datastore.v1beta3.BeginTransactionRequest requestPb) { try { - return RetryHelper.runWithRetries(new Callable() { - @Override - public DatastoreV1.BeginTransactionResponse call() throws DatastoreException { - return datastoreRpc.beginTransaction(requestPb); - } - }, retryParams, EXCEPTION_HANDLER); + return RetryHelper.runWithRetries( + new Callable() { + @Override + public com.google.datastore.v1beta3.BeginTransactionResponse call() + throws DatastoreException { + return datastoreRpc.beginTransaction(requestPb); + } + }, + retryParams, + EXCEPTION_HANDLER); } catch (RetryHelperException e) { throw DatastoreException.translateAndThrow(e); } } void rollbackTransaction(ByteString transaction) { - DatastoreV1.RollbackRequest.Builder requestPb = DatastoreV1.RollbackRequest.newBuilder(); + com.google.datastore.v1beta3.RollbackRequest.Builder requestPb = + com.google.datastore.v1beta3.RollbackRequest.newBuilder(); requestPb.setTransaction(transaction); rollback(requestPb.build()); } - void rollback(final DatastoreV1.RollbackRequest requestPb) { + void rollback(final com.google.datastore.v1beta3.RollbackRequest requestPb) { try { RetryHelper.runWithRetries(new Callable() { @Override public Void call() throws DatastoreException { diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreOptions.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreOptions.java index db1a5f800ce8..bc0efd837755 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreOptions.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreOptions.java @@ -18,9 +18,7 @@ import static com.google.gcloud.datastore.Validator.validateNamespace; -import com.google.api.services.datastore.DatastoreV1; -import com.google.api.services.datastore.DatastoreV1.EntityResult; -import com.google.api.services.datastore.DatastoreV1.LookupResponse; +import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.gcloud.ServiceOptions; @@ -36,14 +34,10 @@ public class DatastoreOptions extends ServiceOptions { private static final long serialVersionUID = 5056049000758143852L; - private static final String DATASET_ENV_NAME = "DATASTORE_DATASET"; - private static final String HOST_ENV_NAME = "DATASTORE_HOST"; private static final String DATASTORE_SCOPE = "https://www.googleapis.com/auth/datastore"; - private static final String USERINFO_SCOPE = "https://www.googleapis.com/auth/userinfo.email"; - private static final Set SCOPES = ImmutableSet.of(DATASTORE_SCOPE, USERINFO_SCOPE); + private static final Set SCOPES = ImmutableSet.of(DATASTORE_SCOPE); private final String namespace; - private final boolean force; private final boolean normalizeDataset; public static class DefaultDatastoreFactory implements DatastoreFactory { @@ -70,7 +64,6 @@ public static class Builder extends ServiceOptions.Builder { private String namespace; - private boolean force; private boolean normalizeDataset = true; private Builder() { @@ -78,7 +71,6 @@ private Builder() { private Builder(DatastoreOptions options) { super(options); - force = options.force; namespace = options.namespace; normalizeDataset = options.normalizeDataset; } @@ -94,11 +86,6 @@ public Builder namespace(String namespace) { return this; } - public Builder force(boolean force) { - this.force = force; - return this; - } - Builder normalizeDataset(boolean normalizeDataset) { this.normalizeDataset = normalizeDataset; return this; @@ -109,7 +96,6 @@ private DatastoreOptions(Builder builder) { super(DatastoreFactory.class, DatastoreRpcFactory.class, builder); normalizeDataset = builder.normalizeDataset; namespace = builder.namespace != null ? builder.namespace : defaultNamespace(); - force = builder.force; } private DatastoreOptions normalize() { @@ -120,32 +106,38 @@ private DatastoreOptions normalize() { Builder builder = toBuilder(); builder.normalizeDataset(false); // Replace provided project-id with full project-id (s~xxx, e~xxx,...) - DatastoreV1.LookupRequest.Builder requestPb = DatastoreV1.LookupRequest.newBuilder(); - DatastoreV1.Key key = DatastoreV1.Key.newBuilder() - .addPathElement(DatastoreV1.Key.PathElement.newBuilder().setKind("__foo__").setName("bar")) + com.google.datastore.v1beta3.LookupRequest.Builder requestPb = + com.google.datastore.v1beta3.LookupRequest.newBuilder(); + com.google.datastore.v1beta3.Key key = com.google.datastore.v1beta3.Key.newBuilder() + .addPath(com.google.datastore.v1beta3.Key.PathElement.newBuilder() + .setKind("__foo__").setName("bar")) .build(); - requestPb.addKey(key); - LookupResponse responsePb = rpc().lookup(requestPb.build()); + requestPb.addKeys(key); + com.google.datastore.v1beta3.LookupResponse responsePb = rpc().lookup(requestPb.build()); if (responsePb.getDeferredCount() > 0) { key = responsePb.getDeferred(0); } else { - Iterator combinedIter = + Iterator combinedIter = Iterables.concat(responsePb.getMissingList(), responsePb.getFoundList()).iterator(); key = combinedIter.next().getEntity().getKey(); } - builder.projectId(key.getPartitionId().getDatasetId()); + builder.projectId(key.getPartitionId().getProjectId()); return new DatastoreOptions(builder); } @Override protected String defaultHost() { - String host = System.getProperty(HOST_ENV_NAME, System.getenv(HOST_ENV_NAME)); - return host != null ? host : super.defaultHost(); + String host = System.getProperty( + com.google.datastore.v1beta3.client.DatastoreHelper.LOCAL_HOST_ENV_VAR, + System.getenv(com.google.datastore.v1beta3.client.DatastoreHelper.LOCAL_HOST_ENV_VAR)); + return host != null ? host : com.google.datastore.v1beta3.client.DatastoreFactory.DEFAULT_HOST; } @Override protected String defaultProject() { - String projectId = System.getProperty(DATASET_ENV_NAME, System.getenv(DATASET_ENV_NAME)); + String projectId = System.getProperty( + com.google.datastore.v1beta3.client.DatastoreHelper.PROJECT_ID_ENV_VAR, + System.getenv(com.google.datastore.v1beta3.client.DatastoreHelper.PROJECT_ID_ENV_VAR)); if (projectId == null) { projectId = appEngineAppId(); } @@ -180,17 +172,13 @@ private static String defaultNamespace() { Class clazz = Class.forName("com.google.appengine.api.NamespaceManager"); Method method = clazz.getMethod("get"); String namespace = (String) method.invoke(null); - return namespace == null || namespace.isEmpty() ? null : namespace; + return MoreObjects.firstNonNull(namespace, ""); } catch (Exception ignore) { - // return null (Datastore default namespace) if could not automatically determine - return null; + // return empty string (Datastore default namespace) if could not automatically determine + return ""; } } - public boolean force() { - return force; - } - @Override protected Set scopes() { return SCOPES; @@ -204,7 +192,7 @@ public Builder toBuilder() { @Override public int hashCode() { - return baseHashCode() ^ Objects.hash(namespace, force, normalizeDataset); + return baseHashCode() ^ Objects.hash(namespace, normalizeDataset); } @Override @@ -214,7 +202,6 @@ public boolean equals(Object obj) { } DatastoreOptions other = (DatastoreOptions) obj; return baseEquals(other) && Objects.equals(namespace, other.namespace) - && Objects.equals(force, other.force) && Objects.equals(normalizeDataset, other.normalizeDataset); } diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreReader.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreReader.java index 4852dd53e16c..3d6e5ec73243 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreReader.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DatastoreReader.java @@ -25,18 +25,17 @@ public interface DatastoreReader { /** - * Returns an {@link Entity} for the given {@link Key} or {@code null} if does not exists. + * Returns an {@link Entity} for the given {@link Key} or {@code null} if it doesn't exist. * * @throws DatastoreException upon failure */ Entity get(Key key); /** - * Returns an {@link Entity} for each given {@link Key} that exists in the Datastore. - * The order of the result is unspecified. - * Results are loaded lazily therefore it is possible to get a {@code DatastoreException} - * from the returned {@code Iterator}'s {@link Iterator#hasNext hasNext} or - * {@link Iterator#next next} methods. + * Returns an {@link Entity} for each given {@link Key} that exists in the Datastore. The order of + * the result is unspecified. Results are loaded lazily, so it is possible to get a + * {@code DatastoreException} from the returned {@code Iterator}'s + * {@link Iterator#hasNext hasNext} or {@link Iterator#next next} methods. * * @throws DatastoreException upon failure * @see #get(Key) @@ -44,14 +43,14 @@ public interface DatastoreReader { Iterator get(Key... key); /** - * Returns a list with a value for each given key (ordered by input). - * A {@code null} would be returned for non-existing keys. - * When possible prefer using {@link #get(Key...)} which does not eagerly loads the results. + * Returns a list with a value for each given key (ordered by input). {@code null} values are + * returned for nonexistent keys. When possible prefer using {@link #get(Key...)} to avoid eagerly + * loading the results. */ List fetch(Key... keys); /** - * Submit a {@link Query} and returns its result. + * Submits a {@link Query} and returns its result. * * @throws DatastoreException upon failure */ diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DateTime.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DateTime.java index d22edd9697e4..5e8664395802 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DateTime.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DateTime.java @@ -18,8 +18,6 @@ import static com.google.common.base.Preconditions.checkNotNull; -import com.google.api.services.datastore.DatastoreV1; -import com.google.api.services.datastore.DatastoreV1.Value; import com.google.protobuf.InvalidProtocolBufferException; import org.joda.time.format.ISODateTimeFormat; @@ -34,7 +32,7 @@ * @see Google Cloud Datastore * Entities, Properties, and Keys */ -public final class DateTime extends Serializable +public final class DateTime extends Serializable implements Comparable { private static final long serialVersionUID = 7343324797621228378L; @@ -98,12 +96,23 @@ public static DateTime copyFrom(Calendar calendar) { } @Override - Value toPb() { - return DatastoreV1.Value.newBuilder().setIntegerValue(timestampMicroseconds).build(); + com.google.protobuf.Timestamp toPb() { + return microsecondsToTimestampPb(timestampMicroseconds); } @Override Object fromPb(byte[] bytesPb) throws InvalidProtocolBufferException { - return new DateTime(DatastoreV1.Value.parseFrom(bytesPb).getIntegerValue()); + return new DateTime(timestampPbToMicroseconds( + com.google.protobuf.Timestamp.parseFrom(bytesPb))); + } + + static long timestampPbToMicroseconds(com.google.protobuf.Timestamp timestampPb) { + return timestampPb.getSeconds() * 1000000 + timestampPb.getNanos() / 1000; + } + + static com.google.protobuf.Timestamp microsecondsToTimestampPb(long microseconds) { + long seconds = microseconds / 1000000; + int nanos = (int) (microseconds % 1000000) * 1000; + return com.google.protobuf.Timestamp.newBuilder().setSeconds(seconds).setNanos(nanos).build(); } } diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DateTimeValue.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DateTimeValue.java index 7aec5c7d3c47..e9c42ffabf4c 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DateTimeValue.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DateTimeValue.java @@ -16,9 +16,7 @@ package com.google.gcloud.datastore; -import static com.google.api.services.datastore.DatastoreV1.Value.TIMESTAMP_MICROSECONDS_VALUE_FIELD_NUMBER; - -import com.google.api.services.datastore.DatastoreV1; +import static com.google.datastore.v1beta3.Value.TIMESTAMP_VALUE_FIELD_NUMBER; public final class DateTimeValue extends Value { @@ -31,7 +29,7 @@ public final class DateTimeValue extends Value { @Override public int getProtoFieldId() { - return TIMESTAMP_MICROSECONDS_VALUE_FIELD_NUMBER; + return TIMESTAMP_VALUE_FIELD_NUMBER; } @Override @@ -40,13 +38,14 @@ public Builder newBuilder(DateTime value) { } @Override - protected DateTime getValue(DatastoreV1.Value from) { - return new DateTime(from.getTimestampMicrosecondsValue()); + protected DateTime getValue(com.google.datastore.v1beta3.Value from) { + return new DateTime(DateTime.timestampPbToMicroseconds(from.getTimestampValue())); } @Override - protected void setValue(DateTimeValue from, DatastoreV1.Value.Builder to) { - to.setTimestampMicrosecondsValue(from.get().timestampMicroseconds()); + protected void setValue(DateTimeValue from, com.google.datastore.v1beta3.Value.Builder to) { + to.setTimestampValue(DateTime.microsecondsToTimestampPb(from.get() + .timestampMicroseconds())); } }; diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DoubleValue.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DoubleValue.java index d12bbe317aef..d7409d08fe63 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DoubleValue.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/DoubleValue.java @@ -16,9 +16,7 @@ package com.google.gcloud.datastore; -import static com.google.api.services.datastore.DatastoreV1.Value.DOUBLE_VALUE_FIELD_NUMBER; - -import com.google.api.services.datastore.DatastoreV1; +import static com.google.datastore.v1beta3.Value.DOUBLE_VALUE_FIELD_NUMBER; public final class DoubleValue extends Value { @@ -40,12 +38,12 @@ public Builder newBuilder(Double value) { } @Override - protected Double getValue(DatastoreV1.Value from) { + protected Double getValue(com.google.datastore.v1beta3.Value from) { return from.getDoubleValue(); } @Override - protected void setValue(DoubleValue from, DatastoreV1.Value.Builder to) { + protected void setValue(DoubleValue from, com.google.datastore.v1beta3.Value.Builder to) { to.setDoubleValue(from.get()); } }; diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Entity.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Entity.java index dc1af5b8a2d9..d012eff14422 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Entity.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Entity.java @@ -18,7 +18,6 @@ import static com.google.common.base.Preconditions.checkNotNull; -import com.google.api.services.datastore.DatastoreV1; import com.google.common.base.Preconditions; /** @@ -93,7 +92,7 @@ public static Builder builder(Key key, FullEntity copyFrom) { return new Builder(key, copyFrom); } - static Entity fromPb(DatastoreV1.Entity entityPb) { + static Entity fromPb(com.google.datastore.v1beta3.Entity entityPb) { return new Builder().fill(entityPb).build(); } } diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/EntityQuery.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/EntityQuery.java index 902168f20f48..3eda20eed3dc 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/EntityQuery.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/EntityQuery.java @@ -16,8 +16,6 @@ package com.google.gcloud.datastore; -import com.google.api.services.datastore.DatastoreV1; - /** * An implementation of a Google Cloud Datastore entity query that can be constructed by providing * all the specific query elements. @@ -43,10 +41,10 @@ public static final class Builder extends StructuredQuery.BuilderImpl> { @@ -41,12 +38,12 @@ public Builder newBuilder(FullEntity value) { } @Override - protected FullEntity getValue(DatastoreV1.Value from) { + protected FullEntity getValue(com.google.datastore.v1beta3.Value from) { return FullEntity.fromPb(from.getEntityValue()); } @Override - protected void setValue(EntityValue from, DatastoreV1.Value.Builder to) { + protected void setValue(EntityValue from, com.google.datastore.v1beta3.Value.Builder to) { to.setEntityValue(from.get().toPb()); } }; @@ -57,13 +54,6 @@ private Builder() { super(ValueType.ENTITY); } - @Override - public Builder indexed(boolean indexed) { - // see issue #25 - Preconditions.checkArgument(!indexed, "EntityValue can't be indexed"); - return super.indexed(indexed); - } - @Override public EntityValue build() { return new EntityValue(this); @@ -88,6 +78,6 @@ public static EntityValue of(FullEntity entity) { } public static Builder builder(FullEntity entity) { - return new Builder().set(entity).indexed(false); + return new Builder().set(entity); } } diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/FullEntity.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/FullEntity.java index 55c573b9a636..25225b853556 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/FullEntity.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/FullEntity.java @@ -16,8 +16,6 @@ package com.google.gcloud.datastore; -import com.google.api.services.datastore.DatastoreV1; - /** * A full entity is a {@link BaseEntity} that holds all the properties associated with a * Datastore entity (as opposed to {@link ProjectionEntity}). @@ -71,7 +69,7 @@ public static Builder builder(FullEntity copyFro } - static FullEntity fromPb(DatastoreV1.Entity entityPb) { + static FullEntity fromPb(com.google.datastore.v1beta3.Entity entityPb) { return new Builder<>().fill(entityPb).build(); } } diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/GqlQuery.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/GqlQuery.java index 7c03b69d9f39..342eaf7bd8eb 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/GqlQuery.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/GqlQuery.java @@ -19,7 +19,6 @@ import static com.google.common.base.Preconditions.checkNotNull; import static com.google.gcloud.datastore.Validator.validateNamespace; -import com.google.api.services.datastore.DatastoreV1; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -75,25 +74,22 @@ public final class GqlQuery extends Query { private final transient String queryString; private final transient boolean allowLiteral; - private final transient ImmutableList namedBindings; + private final transient ImmutableMap namedBindings; private final transient ImmutableList positionalBindings; - static final class Binding extends Serializable { + static final class Binding extends Serializable { private static final long serialVersionUID = 1976895435257636275L; - private final transient String name; private final transient Cursor cursor; private final transient Value value; - Binding(String name, Cursor cursor) { - this.name = name; + Binding(Cursor cursor) { this.cursor = checkNotNull(cursor); value = null; } - Binding(String name, Value value) { - this.name = name; + Binding(Value value) { this.value = checkNotNull(value); cursor = null; } @@ -102,13 +98,9 @@ Object cursorOrValue() { return MoreObjects.firstNonNull(cursor, value); } - String name() { - return name; - } - @Override public int hashCode() { - return Objects.hash(name, cursor, value); + return Objects.hash(cursor, value); } @Override @@ -120,17 +112,13 @@ public boolean equals(Object obj) { return false; } Binding other = (Binding) obj; - return Objects.equals(name, other.name) - && Objects.equals(cursor, other.cursor) - && Objects.equals(value, other.value); + return Objects.equals(cursor, other.cursor) && Objects.equals(value, other.value); } @Override - DatastoreV1.GqlQueryArg toPb() { - DatastoreV1.GqlQueryArg.Builder argPb = DatastoreV1.GqlQueryArg.newBuilder(); - if (name != null) { - argPb.setName(name); - } + com.google.datastore.v1beta3.GqlQueryParameter toPb() { + com.google.datastore.v1beta3.GqlQueryParameter.Builder argPb = + com.google.datastore.v1beta3.GqlQueryParameter.newBuilder(); if (cursor != null) { argPb.setCursor(cursor.byteString()); } @@ -142,15 +130,18 @@ DatastoreV1.GqlQueryArg toPb() { @Override Object fromPb(byte[] bytesPb) throws InvalidProtocolBufferException { - return fromPb(DatastoreV1.GqlQueryArg.parseFrom(bytesPb)); + return fromPb(com.google.datastore.v1beta3.GqlQueryParameter.parseFrom(bytesPb)); } - static Binding fromPb(DatastoreV1.GqlQueryArg argPb) { - String name = argPb.hasName() ? argPb.getName() : null; - if (argPb.hasCursor()) { - return new Binding(name, new Cursor(argPb.getCursor())); + static Binding fromPb(com.google.datastore.v1beta3.GqlQueryParameter argPb) { + switch (argPb.getParameterTypeCase()) { + case CURSOR: + return new Binding(new Cursor(argPb.getCursor())); + case VALUE: + return new Binding(Value.fromPb(argPb.getValue())); + default: + throw new AssertionError("Unexpected enum value " + argPb.getParameterTypeCase()); } - return new Binding(name, Value.fromPb(argPb.getValue())); } } @@ -193,52 +184,52 @@ public Builder clearBindings() { } public Builder setBinding(String name, Cursor cursor) { - namedBindings.put(name, new Binding(name, cursor)); + namedBindings.put(name, new Binding(cursor)); return this; } public Builder setBinding(String name, String... value) { - namedBindings.put(name, toBinding(name, StringValue.MARSHALLER, Arrays.asList(value))); + namedBindings.put(name, toBinding(StringValue.MARSHALLER, Arrays.asList(value))); return this; } public Builder setBinding(String name, long... value) { - namedBindings.put(name, toBinding(name, LongValue.MARSHALLER, Longs.asList(value))); + namedBindings.put(name, toBinding(LongValue.MARSHALLER, Longs.asList(value))); return this; } public Builder setBinding(String name, double... value) { - namedBindings.put(name, toBinding(name, DoubleValue.MARSHALLER, Doubles.asList(value))); + namedBindings.put(name, toBinding(DoubleValue.MARSHALLER, Doubles.asList(value))); return this; } public Builder setBinding(String name, boolean... value) { - namedBindings.put(name, toBinding(name, BooleanValue.MARSHALLER, Booleans.asList(value))); + namedBindings.put(name, toBinding(BooleanValue.MARSHALLER, Booleans.asList(value))); return this; } public Builder setBinding(String name, DateTime... value) { - namedBindings.put(name, toBinding(name, DateTimeValue.MARSHALLER, Arrays.asList(value))); + namedBindings.put(name, toBinding(DateTimeValue.MARSHALLER, Arrays.asList(value))); return this; } public Builder setBinding(String name, Key... value) { - namedBindings.put(name, toBinding(name, KeyValue.MARSHALLER, Arrays.asList(value))); + namedBindings.put(name, toBinding(KeyValue.MARSHALLER, Arrays.asList(value))); return this; } public Builder setBinding(String name, FullEntity... value) { - namedBindings.put(name, toBinding(name, EntityValue.MARSHALLER, Arrays.asList(value))); + namedBindings.put(name, toBinding(EntityValue.MARSHALLER, Arrays.asList(value))); return this; } public Builder setBinding(String name, Blob... value) { - namedBindings.put(name, toBinding(name, BlobValue.MARSHALLER, Arrays.asList(value))); + namedBindings.put(name, toBinding(BlobValue.MARSHALLER, Arrays.asList(value))); return this; } public Builder addBinding(Cursor cursor) { - positionalBindings.add(new Binding(null, cursor)); + positionalBindings.add(new Binding(cursor)); return this; } @@ -286,11 +277,7 @@ public GqlQuery build() { return new GqlQuery<>(this); } - private static Binding toBinding(Value.BuilderFactory builderFactory, List values) { - return toBinding(null, builderFactory, values); - } - - private static Binding toBinding(String name, Value.BuilderFactory builderFactory, + private static Binding toBinding(Value.BuilderFactory builderFactory, List values) { List> list = new ArrayList<>(values.size()); for (Object object : values) { @@ -306,7 +293,7 @@ private static Binding toBinding(String name, Value.BuilderFactory } else { value = new ListValue(list); } - return new Binding(name, value); + return new Binding(value); } } @@ -314,7 +301,7 @@ private GqlQuery(Builder builder) { super(builder.resultType, builder.namespace); queryString = builder.queryString; allowLiteral = builder.allowLiteral; - namedBindings = ImmutableList.copyOf(builder.namedBindings.values()); + namedBindings = ImmutableMap.copyOf(builder.namedBindings); positionalBindings = ImmutableList.copyOf(builder.positionalBindings); } @@ -331,8 +318,8 @@ public boolean allowLiteral() { */ public Map namedBindings() { ImmutableMap.Builder builder = ImmutableSortedMap.naturalOrder(); - for (Binding binding : namedBindings) { - builder.put(binding.name(), binding.cursorOrValue()); + for (Map.Entry binding : namedBindings.entrySet()) { + builder.put(binding.getKey(), binding.getValue().cursorOrValue()); } return builder.build(); } @@ -370,50 +357,53 @@ public boolean equals(Object obj) { } @Override - DatastoreV1.GqlQuery toPb() { - DatastoreV1.GqlQuery.Builder queryPb = DatastoreV1.GqlQuery.newBuilder(); + com.google.datastore.v1beta3.GqlQuery toPb() { + com.google.datastore.v1beta3.GqlQuery.Builder queryPb = + com.google.datastore.v1beta3.GqlQuery.newBuilder(); queryPb.setQueryString(queryString); - queryPb.setAllowLiteral(allowLiteral); - for (Binding argument : namedBindings) { - queryPb.addNameArg(argument.toPb()); + queryPb.setAllowLiterals(allowLiteral); + Map namedBindingsPb = + queryPb.getMutableNamedBindings(); + for (Map.Entry entry : namedBindings.entrySet()) { + namedBindingsPb.put(entry.getKey(), entry.getValue().toPb()); } for (Binding argument : positionalBindings) { - queryPb.addNumberArg(argument.toPb()); + queryPb.addPositionalBindings(argument.toPb()); } return queryPb.build(); } @Override - void populatePb(DatastoreV1.RunQueryRequest.Builder requestPb) { + void populatePb(com.google.datastore.v1beta3.RunQueryRequest.Builder requestPb) { requestPb.setGqlQuery(toPb()); } @Override - GqlQuery nextQuery(DatastoreV1.QueryResultBatch responsePb) { - // See issue #17 - throw new UnsupportedOperationException("paging for this query is not implemented yet"); + Query nextQuery(com.google.datastore.v1beta3.RunQueryResponse responsePb) { + return StructuredQuery.fromPb(type(), namespace(), responsePb.getQuery()) + .nextQuery(responsePb); } @Override Object fromPb(ResultType resultType, String namespace, byte[] bytesPb) throws InvalidProtocolBufferException { - return fromPb(resultType, namespace, DatastoreV1.GqlQuery.parseFrom(bytesPb)); + return fromPb(resultType, namespace, com.google.datastore.v1beta3.GqlQuery.parseFrom(bytesPb)); } private static GqlQuery fromPb( - ResultType resultType, String ns, DatastoreV1.GqlQuery queryPb) { + ResultType resultType, String ns, com.google.datastore.v1beta3.GqlQuery queryPb) { Builder builder = new Builder<>(resultType, queryPb.getQueryString()); builder.namespace(ns); - if (queryPb.hasAllowLiteral()) { - builder.allowLiteral = queryPb.getAllowLiteral(); - } - for (DatastoreV1.GqlQueryArg nameArg : queryPb.getNameArgList()) { - Binding argument = Binding.fromPb(nameArg); - builder.namedBindings.put(argument.name(), argument); - } - for (DatastoreV1.GqlQueryArg numberArg : queryPb.getNumberArgList()) { - Binding argument = Binding.fromPb(numberArg); - builder.positionalBindings.add(argument); + builder.allowLiteral = queryPb.getAllowLiterals(); + for (Map.Entry nameArg + : queryPb.getNamedBindings().entrySet()) { + Binding currBinding = Binding.fromPb(nameArg.getValue()); + builder.namedBindings.put(nameArg.getKey(), currBinding); + } + for (com.google.datastore.v1beta3.GqlQueryParameter numberArg + : queryPb.getPositionalBindingsList()) { + Binding currBinding = Binding.fromPb(numberArg); + builder.positionalBindings.add(currBinding); } return builder.build(); } diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/IncompleteKey.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/IncompleteKey.java index 2192384ef70b..31039b6826f7 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/IncompleteKey.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/IncompleteKey.java @@ -16,7 +16,6 @@ package com.google.gcloud.datastore; -import com.google.api.services.datastore.DatastoreV1; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.protobuf.InvalidProtocolBufferException; @@ -55,25 +54,21 @@ public IncompleteKey build() { @Override Object fromPb(byte[] bytesPb) throws InvalidProtocolBufferException { - return fromPb(DatastoreV1.Key.parseFrom(bytesPb)); + return fromPb(com.google.datastore.v1beta3.Key.parseFrom(bytesPb)); } - static IncompleteKey fromPb(DatastoreV1.Key keyPb) { - String projectId = null; - String namespace = null; + static IncompleteKey fromPb(com.google.datastore.v1beta3.Key keyPb) { + String projectId = ""; + String namespace = ""; if (keyPb.hasPartitionId()) { - DatastoreV1.PartitionId partitionIdPb = keyPb.getPartitionId(); - if (partitionIdPb.hasDatasetId()) { - projectId = partitionIdPb.getDatasetId(); - } - if (partitionIdPb.hasNamespace()) { - namespace = partitionIdPb.getNamespace(); - } + com.google.datastore.v1beta3.PartitionId partitionIdPb = keyPb.getPartitionId(); + projectId = partitionIdPb.getProjectId(); + namespace = partitionIdPb.getNamespaceId(); } - List pathElementsPb = keyPb.getPathElementList(); + List pathElementsPb = keyPb.getPathList(); Preconditions.checkArgument(!pathElementsPb.isEmpty(), "Path must not be empty"); ImmutableList.Builder pathBuilder = ImmutableList.builder(); - for (DatastoreV1.Key.PathElement pathElementPb : pathElementsPb) { + for (com.google.datastore.v1beta3.Key.PathElement pathElementPb : pathElementsPb) { pathBuilder.add(PathElement.fromPb(pathElementPb)); } ImmutableList path = pathBuilder.build(); diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Key.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Key.java index c6cdc0fa6142..ccc36ef1f533 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Key.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Key.java @@ -18,7 +18,6 @@ import static java.nio.charset.StandardCharsets.UTF_8; -import com.google.api.services.datastore.DatastoreV1; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.protobuf.InvalidProtocolBufferException; @@ -153,7 +152,8 @@ public String toUrlSafe() { public static Key fromUrlSafe(String urlSafe) { try { String utf8Str = URLDecoder.decode(urlSafe, UTF_8.name()); - DatastoreV1.Key.Builder builder = DatastoreV1.Key.newBuilder(); + com.google.datastore.v1beta3.Key.Builder builder = + com.google.datastore.v1beta3.Key.newBuilder(); TextFormat.merge(utf8Str, builder); return fromPb(builder.build()); } catch (UnsupportedEncodingException e) { @@ -165,10 +165,10 @@ public static Key fromUrlSafe(String urlSafe) { @Override Object fromPb(byte[] bytesPb) throws InvalidProtocolBufferException { - return fromPb(DatastoreV1.Key.parseFrom(bytesPb)); + return fromPb(com.google.datastore.v1beta3.Key.parseFrom(bytesPb)); } - static Key fromPb(DatastoreV1.Key keyPb) { + static Key fromPb(com.google.datastore.v1beta3.Key keyPb) { IncompleteKey key = IncompleteKey.fromPb(keyPb); Preconditions.checkState(key instanceof Key, "Key is not complete"); return (Key) key; diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/KeyFactory.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/KeyFactory.java index a440992870df..947880111ea4 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/KeyFactory.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/KeyFactory.java @@ -28,7 +28,7 @@ public final class KeyFactory extends BaseKey.Builder { private final String ns; public KeyFactory(String projectId) { - this(projectId, null); + this(projectId, ""); } public KeyFactory(String projectId, String namespace) { diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/KeyQuery.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/KeyQuery.java index 7afa0f5099d6..4224f2d07ce5 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/KeyQuery.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/KeyQuery.java @@ -16,8 +16,6 @@ package com.google.gcloud.datastore; -import com.google.api.services.datastore.DatastoreV1; - /** * An implementation of a Google Cloud Datastore key-only query that can be constructed by providing * all the specific query elements. @@ -40,14 +38,14 @@ public static final class Builder extends StructuredQuery.BuilderImpl { @@ -40,12 +38,12 @@ public Builder newBuilder(Key key) { } @Override - protected Key getValue(DatastoreV1.Value from) { + protected Key getValue(com.google.datastore.v1beta3.Value from) { return Key.fromPb(from.getKeyValue()); } @Override - protected void setValue(KeyValue from, DatastoreV1.Value.Builder to) { + protected void setValue(KeyValue from, com.google.datastore.v1beta3.Value.Builder to) { to.setKeyValue(from.get().toPb()); } }; diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/LatLng.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/LatLng.java new file mode 100644 index 000000000000..7e2b42fac4d3 --- /dev/null +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/LatLng.java @@ -0,0 +1,90 @@ +/* + * Copyright 2015 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.gcloud.datastore; + +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.protobuf.InvalidProtocolBufferException; + +import java.util.Objects; + +/** + * A Google Cloud Datastore LatLng (represented by latitude and longitude in degrees). + * This class is immutable. + * + * @see Google Cloud Datastore + * Entities, Properties, and Keys + */ +public final class LatLng extends Serializable { + + private static final long serialVersionUID = 9077060962655752073L; + + private final transient double latitude; + private final transient double longitude; + + LatLng(double latitude, double longitude) { + checkArgument( + latitude >= -90.0 && latitude <= 90.0, "latitude must be in the range [-90, 90] degrees"); + checkArgument( + longitude >= -180.0 && longitude <= 180.0, + "latitude must be in the range [-180, 180] degrees"); + this.latitude = latitude; + this.longitude = longitude; + } + + public double latitude() { + return latitude; + } + + public double longitude() { + return longitude; + } + + @Override + public String toString() { + return Double.toString(latitude) + ", " + Double.toString(longitude); + } + + @Override + public int hashCode() { + return Objects.hash(latitude, longitude); + } + + @Override + public boolean equals(Object obj) { + return obj == this || (obj instanceof LatLng && this.latitude == ((LatLng) obj).latitude + && this.longitude == ((LatLng) obj).longitude); + } + + public static LatLng of(double latitude, double longitude) { + return new LatLng(latitude, longitude); + } + + @Override + protected com.google.type.LatLng toPb() { + return com.google.type.LatLng.newBuilder() + .setLatitude(latitude) + .setLongitude(longitude) + .build(); + } + + @Override + protected Object fromPb(byte[] bytesPb) throws InvalidProtocolBufferException { + com.google.type.LatLng parsedLatLng = com.google.type.LatLng.parseFrom(bytesPb); + return new LatLng(parsedLatLng.getLatitude(), parsedLatLng.getLongitude()); + } +} diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/LatLngValue.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/LatLngValue.java new file mode 100644 index 000000000000..91723f710816 --- /dev/null +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/LatLngValue.java @@ -0,0 +1,84 @@ +/* + * Copyright 2015 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.gcloud.datastore; + +import static com.google.datastore.v1beta3.Value.GEO_POINT_VALUE_FIELD_NUMBER; + +public final class LatLngValue extends Value { + + private static final long serialVersionUID = -5810614280642405898L; + + static final BaseMarshaller MARSHALLER = + new BaseMarshaller() { + + private static final long serialVersionUID = -3550567536035178649L; + + @Override + public int getProtoFieldId() { + return GEO_POINT_VALUE_FIELD_NUMBER; + } + + @Override + public Builder newBuilder(LatLng value) { + return builder(value); + } + + @Override + protected LatLng getValue(com.google.datastore.v1beta3.Value from) { + return new LatLng( + from.getGeoPointValue().getLatitude(), from.getGeoPointValue().getLongitude()); + } + + @Override + protected void setValue(LatLngValue from, com.google.datastore.v1beta3.Value.Builder to) { + to.setGeoPointValue(from.get().toPb()); + } + }; + + public static final class Builder extends Value.BaseBuilder { + + private Builder() { + super(ValueType.LAT_LNG); + } + + @Override + public LatLngValue build() { + return new LatLngValue(this); + } + } + + public LatLngValue(LatLng value) { + this(builder(value)); + } + + private LatLngValue(Builder builder) { + super(builder); + } + + @Override + public Builder toBuilder() { + return new Builder().mergeFrom(this); + } + + public static LatLngValue of(LatLng value) { + return new LatLngValue(value); + } + + public static Builder builder(LatLng value) { + return new Builder().set(value); + } +} diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ListValue.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ListValue.java index 06282a2c79d1..9d4fe9c186d5 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ListValue.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ListValue.java @@ -16,9 +16,8 @@ package com.google.gcloud.datastore; -import static com.google.api.services.datastore.DatastoreV1.Value.LIST_VALUE_FIELD_NUMBER; +import static com.google.datastore.v1beta3.Value.ARRAY_VALUE_FIELD_NUMBER; -import com.google.api.services.datastore.DatastoreV1; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; @@ -36,7 +35,7 @@ public final class ListValue extends Value>> { @Override public int getProtoFieldId() { - return LIST_VALUE_FIELD_NUMBER; + return ARRAY_VALUE_FIELD_NUMBER; } @Override @@ -45,19 +44,23 @@ public Builder newBuilder(List> values) { } @Override - protected List> getValue(DatastoreV1.Value from) { - List> properties = new ArrayList<>(from.getListValueCount()); - for (DatastoreV1.Value valuePb : from.getListValueList()) { + protected List> getValue(com.google.datastore.v1beta3.Value from) { + List> properties = new ArrayList<>(from.getArrayValue().getValuesCount()); + for (com.google.datastore.v1beta3.Value valuePb : from.getArrayValue().getValuesList()) { properties.add(Value.fromPb(valuePb)); } return properties; } @Override - protected void setValue(ListValue from, DatastoreV1.Value.Builder to) { + protected void setValue(ListValue from, com.google.datastore.v1beta3.Value.Builder to) { + List propertiesPb = + new ArrayList(); for (Value property : from.get()) { - to.addListValue(property.toPb()); + propertiesPb.add(property.toPb()); } + to.setArrayValue(com.google.datastore.v1beta3.ArrayValue.newBuilder() + .addAllValues(propertiesPb)); } }; @@ -71,7 +74,7 @@ private Builder() { } private void addValueHelper(Value value) { - // see datastore_v1.proto definition for list_value + // see datastore.proto definition for list_value Preconditions.checkArgument(value.type() != ValueType.LIST, "Cannot contain another list"); listBuilder.add(value); } @@ -84,12 +87,6 @@ public Builder addValue(Value first, Value... other) { return this; } - @Override - public Builder indexed(boolean indexed) { - // see issue #26 - throw DatastoreException.throwInvalidRequest("ListValue can't specify index"); - } - /** * Copy the list of values. * diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/LongValue.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/LongValue.java index 43d139e90249..18cdead6280a 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/LongValue.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/LongValue.java @@ -16,9 +16,7 @@ package com.google.gcloud.datastore; -import static com.google.api.services.datastore.DatastoreV1.Value.INTEGER_VALUE_FIELD_NUMBER; - -import com.google.api.services.datastore.DatastoreV1; +import static com.google.datastore.v1beta3.Value.INTEGER_VALUE_FIELD_NUMBER; public final class LongValue extends Value { @@ -40,12 +38,12 @@ public Builder newBuilder(Long value) { } @Override - protected Long getValue(DatastoreV1.Value from) { + protected Long getValue(com.google.datastore.v1beta3.Value from) { return from.getIntegerValue(); } @Override - protected void setValue(LongValue from, DatastoreV1.Value.Builder to) { + protected void setValue(LongValue from, com.google.datastore.v1beta3.Value.Builder to) { to.setIntegerValue(from.get()); } }; diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/NullValue.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/NullValue.java index 58fed152ffd5..ed314200b8bb 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/NullValue.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/NullValue.java @@ -18,7 +18,7 @@ import static com.google.common.base.Preconditions.checkArgument; -import com.google.api.services.datastore.DatastoreV1; +import static com.google.datastore.v1beta3.Value.NULL_VALUE_FIELD_NUMBER; public final class NullValue extends Value { @@ -36,21 +36,22 @@ public Builder newBuilder(Void value) { @Override public int getProtoFieldId() { - return 0; + return NULL_VALUE_FIELD_NUMBER; } @Override - protected Void getValue(DatastoreV1.Value from) { + protected Void getValue(com.google.datastore.v1beta3.Value from) { return null; } @Override - protected void setValue(NullValue from, DatastoreV1.Value.Builder to) { - // nothing to set + protected void setValue(NullValue from, com.google.datastore.v1beta3.Value.Builder to) { + to.setNullValue(com.google.protobuf.NullValue.NULL_VALUE); } }; - public static final class Builder extends Value.BaseBuilder { + public static final class Builder + extends Value.BaseBuilder { private Builder() { super(ValueType.NULL); diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/PathElement.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/PathElement.java index 6b76eb70ea5b..1759cc82bcea 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/PathElement.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/PathElement.java @@ -19,7 +19,6 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -import com.google.api.services.datastore.DatastoreV1; import com.google.common.base.Strings; import com.google.protobuf.InvalidProtocolBufferException; @@ -28,7 +27,7 @@ /** * Represents a single element in a key's path. */ -public final class PathElement extends Serializable { +public final class PathElement extends Serializable { private static final long serialVersionUID = -7968078857690784595L; @@ -86,8 +85,9 @@ public boolean equals(Object obj) { } @Override - DatastoreV1.Key.PathElement toPb() { - DatastoreV1.Key.PathElement.Builder pathElementPb = DatastoreV1.Key.PathElement.newBuilder(); + com.google.datastore.v1beta3.Key.PathElement toPb() { + com.google.datastore.v1beta3.Key.PathElement.Builder pathElementPb = + com.google.datastore.v1beta3.Key.PathElement.newBuilder(); pathElementPb.setKind(kind); if (id != null) { pathElementPb.setId(id); @@ -99,18 +99,19 @@ DatastoreV1.Key.PathElement toPb() { @Override Object fromPb(byte[] bytesPb) throws InvalidProtocolBufferException { - return fromPb(DatastoreV1.Key.PathElement.parseFrom(bytesPb)); + return fromPb(com.google.datastore.v1beta3.Key.PathElement.parseFrom(bytesPb)); } - static PathElement fromPb(DatastoreV1.Key.PathElement pathElementPb) { + static PathElement fromPb(com.google.datastore.v1beta3.Key.PathElement pathElementPb) { String kind = pathElementPb.getKind(); - if (pathElementPb.hasId()) { - return of(kind, pathElementPb.getId()); + switch (pathElementPb.getIdTypeCase()) { + case ID: + return of(kind, pathElementPb.getId()); + case NAME: + return of(kind, pathElementPb.getName()); + default: + return of(kind); } - if (pathElementPb.hasName()) { - return of(kind, pathElementPb.getName()); - } - return of(kind); } static PathElement of(String kind) { diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ProjectionEntity.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ProjectionEntity.java index 1ba054b68161..f8af814245ab 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ProjectionEntity.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ProjectionEntity.java @@ -16,7 +16,6 @@ package com.google.gcloud.datastore; -import com.google.api.services.datastore.DatastoreV1; import com.google.protobuf.ByteString; /** @@ -56,7 +55,7 @@ public ProjectionEntity build() { @Override public DateTime getDateTime(String name) { Value value = getValue(name); - if (value.hasMeaning() && value.meaning() == 18 && value instanceof LongValue) { + if (value.meaning() == 18 && value instanceof LongValue) { return new DateTime(getLong(name)); } return ((Value) value).get(); @@ -66,13 +65,13 @@ public DateTime getDateTime(String name) { @Override public Blob getBlob(String name) { Value value = getValue(name); - if (value.hasMeaning() && value.meaning() == 18 && value instanceof StringValue) { + if (value.meaning() == 18 && value instanceof StringValue) { return new Blob(ByteString.copyFromUtf8(getString(name))); } return ((Value) value).get(); } - static ProjectionEntity fromPb(DatastoreV1.Entity entityPb) { + static ProjectionEntity fromPb(com.google.datastore.v1beta3.Entity entityPb) { return new Builder().fill(entityPb).build(); } diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ProjectionEntityQuery.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ProjectionEntityQuery.java index bad9fc5af2d0..d0e9920f3a61 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ProjectionEntityQuery.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ProjectionEntityQuery.java @@ -54,7 +54,7 @@ public Builder clearProjection() { * Sets the query's projection clause (clearing any previously specified Projection settings). */ @Override - public Builder projection(Projection projection, Projection... others) { + public Builder projection(String projection, String... others) { super.projection(projection, others); return this; } @@ -63,7 +63,7 @@ public Builder projection(Projection projection, Projection... others) { * Adds one or more projections to the existing projection clause. */ @Override - public Builder addProjection(Projection projection, Projection... others) { + public Builder addProjection(String projection, String... others) { super.addProjection(projection, others); return this; } @@ -72,8 +72,8 @@ public Builder addProjection(Projection projection, Projection... others) { * Clears the group by clause. */ @Override - public Builder clearGroupBy() { - super.clearGroupBy(); + public Builder clearDistinctOn() { + super.clearDistinctOn(); return this; } @@ -81,8 +81,8 @@ public Builder clearGroupBy() { * Sets the query's group by clause (clearing any previously specified GroupBy settings). */ @Override - public Builder groupBy(String property, String... others) { - super.groupBy(property, others); + public Builder distinctOn(String property, String... others) { + super.distinctOn(property, others); return this; } @@ -90,8 +90,8 @@ public Builder groupBy(String property, String... others) { * Adds one or more properties to the existing group by clause. */ @Override - public Builder addGroupBy(String property, String... others) { - super.addGroupBy(property, others); + public Builder addDistinctOn(String property, String... others) { + super.addDistinctOn(property, others); return this; } diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Query.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Query.java index 50591a87a6a4..dd0ea9f1b798 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Query.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Query.java @@ -18,7 +18,6 @@ import static com.google.common.base.Preconditions.checkNotNull; -import com.google.api.services.datastore.DatastoreV1; import com.google.common.base.MoreObjects; import com.google.common.base.MoreObjects.ToStringHelper; import com.google.common.collect.Maps; @@ -55,63 +54,69 @@ public abstract class Query extends Serializable { public abstract static class ResultType implements java.io.Serializable { private static final long serialVersionUID = 2104157695425806623L; - private static final Map> - PB_TO_INSTANCE = Maps.newEnumMap(DatastoreV1.EntityResult.ResultType.class); + private static final Map> + PB_TO_INSTANCE = Maps.newEnumMap( + com.google.datastore.v1beta3.EntityResult.ResultType.class); - static final ResultType UNKNOWN = new ResultType(null, Object.class) { + static final ResultType UNKNOWN = + new ResultType(null, Object.class) { - private static final long serialVersionUID = 1602329532153860907L; + private static final long serialVersionUID = 1602329532153860907L; - @Override - Object convert(DatastoreV1.Entity entityPb) { - if (entityPb.getPropertyCount() == 0) { - if (!entityPb.hasKey()) { - return null; + @Override + Object convert(com.google.datastore.v1beta3.Entity entityPb) { + if (entityPb.getProperties().isEmpty()) { + if (!entityPb.hasKey()) { + return null; + } + return Key.fromPb(entityPb.getKey()); + } + return ProjectionEntity.fromPb(entityPb); } - return Key.fromPb(entityPb.getKey()); - } - return ProjectionEntity.fromPb(entityPb); - } - }; + }; public static final ResultType ENTITY = - new ResultType(DatastoreV1.EntityResult.ResultType.FULL, Entity.class) { + new ResultType( + com.google.datastore.v1beta3.EntityResult.ResultType.FULL, Entity.class) { - private static final long serialVersionUID = 7712959777507168274L; + private static final long serialVersionUID = 7712959777507168274L; - @Override - Entity convert(DatastoreV1.Entity entityPb) { - return Entity.fromPb(entityPb); - } - }; + @Override + Entity convert(com.google.datastore.v1beta3.Entity entityPb) { + return Entity.fromPb(entityPb); + } + }; public static final ResultType KEY = - new ResultType(DatastoreV1.EntityResult.ResultType.KEY_ONLY, Key.class) { + new ResultType( + com.google.datastore.v1beta3.EntityResult.ResultType.KEY_ONLY, Key.class) { - private static final long serialVersionUID = -8514289244104446252L; + private static final long serialVersionUID = -8514289244104446252L; - @Override - Key convert(DatastoreV1.Entity entityPb) { - return Key.fromPb(entityPb.getKey()); - } - }; + @Override + Key convert(com.google.datastore.v1beta3.Entity entityPb) { + return Key.fromPb(entityPb.getKey()); + } + }; public static final ResultType PROJECTION_ENTITY = - new ResultType(DatastoreV1.EntityResult.ResultType.PROJECTION, + new ResultType( + com.google.datastore.v1beta3.EntityResult.ResultType.PROJECTION, ProjectionEntity.class) { private static final long serialVersionUID = -7591409419690650246L; @Override - ProjectionEntity convert(DatastoreV1.Entity entityPb) { + ProjectionEntity convert(com.google.datastore.v1beta3.Entity entityPb) { return ProjectionEntity.fromPb(entityPb); } - }; + }; private final Class resultClass; - private final DatastoreV1.EntityResult.ResultType queryType; + private final com.google.datastore.v1beta3.EntityResult.ResultType queryType; - private ResultType(DatastoreV1.EntityResult.ResultType queryType, Class resultClass) { + private ResultType(com.google.datastore.v1beta3.EntityResult.ResultType queryType, + Class resultClass) { this.queryType = queryType; this.resultClass = resultClass; if (queryType != null) { @@ -152,9 +157,9 @@ boolean isAssignableFrom(ResultType otherResultType) { return resultClass.isAssignableFrom(otherResultType.resultClass); } - abstract V convert(DatastoreV1.Entity entityPb); + abstract V convert(com.google.datastore.v1beta3.Entity entityPb); - static ResultType fromPb(DatastoreV1.EntityResult.ResultType typePb) { + static ResultType fromPb(com.google.datastore.v1beta3.EntityResult.ResultType typePb) { return MoreObjects.firstNonNull(PB_TO_INSTANCE.get(typePb), UNKNOWN); } } @@ -189,9 +194,9 @@ Object fromPb(byte[] bytesPb) throws InvalidProtocolBufferException { abstract Object fromPb(ResultType resultType, String namespace, byte[] bytesPb) throws InvalidProtocolBufferException; - abstract void populatePb(DatastoreV1.RunQueryRequest.Builder requestPb); + abstract void populatePb(com.google.datastore.v1beta3.RunQueryRequest.Builder requestPb); - abstract Query nextQuery(DatastoreV1.QueryResultBatch responsePb); + abstract Query nextQuery(com.google.datastore.v1beta3.RunQueryResponse responsePb); /** * Returns a new {@link GqlQuery} builder. diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/QueryResults.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/QueryResults.java index b882131ba939..a6e5971936dd 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/QueryResults.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/QueryResults.java @@ -36,8 +36,21 @@ public interface QueryResults extends Iterator { Class resultClass(); /** - * Returns the Cursor for the point after the value returned in the last {@link #next} call. - * Currently, {@code cursorAfter} returns null in all cases but the last result. + * Returns the Cursor for the point after the value returned in the last {@link #next} call. This + * cursor can be used to issue subsequent queries (with the same constraints) that may return + * additional results. + * + *

A simple use case: + *

 {@code
+   * Query query = Query.entityQueryBuilder()
+   *     .kind("Person")
+   *     .filter(PropertyFilter.eq("favoriteFood", "pizza"))
+   *     .build();
+   * QueryResults results = datastore.run(query);
+   * // Consume some results (using results.next()) and do any other actions as necessary.
+   * query = query.toBuilder().startCursor(results.cursorAfter()).build();
+   * results = datastore.run(query); // now we will iterate over all entities not yet consumed
+   * }
*/ Cursor cursorAfter(); } diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/QueryResultsImpl.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/QueryResultsImpl.java index 3c2e0d177f80..ec3a652c6131 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/QueryResultsImpl.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/QueryResultsImpl.java @@ -16,10 +16,9 @@ package com.google.gcloud.datastore; -import com.google.api.services.datastore.DatastoreV1; -import com.google.api.services.datastore.DatastoreV1.QueryResultBatch.MoreResultsType; import com.google.common.base.Preconditions; import com.google.common.collect.AbstractIterator; +import com.google.datastore.v1beta3.QueryResultBatch.MoreResultsType; import com.google.gcloud.datastore.Query.ResultType; import com.google.protobuf.ByteString; @@ -29,46 +28,56 @@ class QueryResultsImpl extends AbstractIterator implements QueryResults { private final DatastoreImpl datastore; - private final DatastoreV1.ReadOptions readOptionsPb; - private final DatastoreV1.PartitionId partitionIdPb; + private final com.google.datastore.v1beta3.ReadOptions readOptionsPb; + private final com.google.datastore.v1beta3.PartitionId partitionIdPb; private final ResultType queryResultType; private Query query; private ResultType actualResultType; - private DatastoreV1.QueryResultBatch queryResultBatchPb; + private com.google.datastore.v1beta3.RunQueryResponse runQueryResponsePb; + private com.google.datastore.v1beta3.Query mostRecentQueryPb; private boolean lastBatch; - private Iterator entityResultPbIter; - private ByteString cursor; // only available in v1beta3 + private Iterator entityResultPbIter; + private ByteString cursor; - - QueryResultsImpl(DatastoreImpl datastore, DatastoreV1.ReadOptions readOptionsPb, + QueryResultsImpl(DatastoreImpl datastore, com.google.datastore.v1beta3.ReadOptions readOptionsPb, Query query) { this.datastore = datastore; this.readOptionsPb = readOptionsPb; this.query = query; queryResultType = query.type(); - DatastoreV1.PartitionId.Builder pbBuilder = DatastoreV1.PartitionId.newBuilder(); - pbBuilder.setDatasetId(datastore.options().projectId()); + com.google.datastore.v1beta3.PartitionId.Builder pbBuilder = + com.google.datastore.v1beta3.PartitionId.newBuilder(); + pbBuilder.setProjectId(datastore.options().projectId()); if (query.namespace() != null) { - pbBuilder.setNamespace(query.namespace()); + pbBuilder.setNamespaceId(query.namespace()); } else if (datastore.options().namespace() != null) { - pbBuilder.setNamespace(datastore.options().namespace()); + pbBuilder.setNamespaceId(datastore.options().namespace()); } partitionIdPb = pbBuilder.build(); sendRequest(); + if (runQueryResponsePb.getBatch().getSkippedResults() > 0) { + cursor = runQueryResponsePb.getBatch().getSkippedCursor(); + } else { + cursor = mostRecentQueryPb.getStartCursor(); + } } private void sendRequest() { - DatastoreV1.RunQueryRequest.Builder requestPb = DatastoreV1.RunQueryRequest.newBuilder(); + com.google.datastore.v1beta3.RunQueryRequest.Builder requestPb = + com.google.datastore.v1beta3.RunQueryRequest.newBuilder(); if (readOptionsPb != null) { requestPb.setReadOptions(readOptionsPb); } requestPb.setPartitionId(partitionIdPb); query.populatePb(requestPb); - queryResultBatchPb = datastore.runQuery(requestPb.build()).getBatch(); - lastBatch = queryResultBatchPb.getMoreResults() != MoreResultsType.NOT_FINISHED; - entityResultPbIter = queryResultBatchPb.getEntityResultList().iterator(); - // cursor = resultPb.getSkippedCursor(); // available in v1beta3, use startCursor if not skipped - actualResultType = ResultType.fromPb(queryResultBatchPb.getEntityResultType()); + runQueryResponsePb = datastore.runQuery(requestPb.build()); + mostRecentQueryPb = runQueryResponsePb.getQuery(); + if (mostRecentQueryPb == null) { + mostRecentQueryPb = requestPb.getQuery(); + } + lastBatch = runQueryResponsePb.getBatch().getMoreResults() != MoreResultsType.NOT_FINISHED; + entityResultPbIter = runQueryResponsePb.getBatch().getEntityResultsList().iterator(); + actualResultType = ResultType.fromPb(runQueryResponsePb.getBatch().getEntityResultType()); if (Objects.equals(queryResultType, ResultType.PROJECTION_ENTITY)) { // projection entity can represent all type of results actualResultType = ResultType.PROJECTION_ENTITY; @@ -80,15 +89,15 @@ private void sendRequest() { @Override protected T computeNext() { while (!entityResultPbIter.hasNext() && !lastBatch) { - query = query.nextQuery(queryResultBatchPb); + query = query.nextQuery(runQueryResponsePb); sendRequest(); } if (!entityResultPbIter.hasNext()) { - cursor = queryResultBatchPb.getEndCursor(); + cursor = runQueryResponsePb.getBatch().getEndCursor(); return endOfData(); } - DatastoreV1.EntityResult entityResultPb = entityResultPbIter.next(); - //cursor = entityResultPb.getCursor(); // only available in v1beta3 + com.google.datastore.v1beta3.EntityResult entityResultPb = entityResultPbIter.next(); + cursor = entityResultPb.getCursor(); @SuppressWarnings("unchecked") T result = (T) actualResultType.convert(entityResultPb.getEntity()); return result; @@ -101,7 +110,6 @@ public Class resultClass() { @Override public Cursor cursorAfter() { - return cursor == null ? null : new Cursor(cursor); - //return new Cursor(cursor); // only available in v1beta3 + return new Cursor(cursor); } } diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/RawValue.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/RawValue.java index 9d447cf4289b..cd64bcdeff05 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/RawValue.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/RawValue.java @@ -16,19 +16,17 @@ package com.google.gcloud.datastore; -import com.google.api.services.datastore.DatastoreV1; - -public final class RawValue extends Value { +public final class RawValue extends Value { private static final long serialVersionUID = -3359604598651897941L; - static final BaseMarshaller MARSHALLER = - new BaseMarshaller() { + static final BaseMarshaller MARSHALLER = + new BaseMarshaller() { private static final long serialVersionUID = 5320642719486106244L; @Override - public Builder newBuilder(DatastoreV1.Value value) { + public Builder newBuilder(com.google.datastore.v1beta3.Value value) { return builder(value); } @@ -38,18 +36,19 @@ public int getProtoFieldId() { } @Override - protected DatastoreV1.Value getValue(DatastoreV1.Value from) { + protected com.google.datastore.v1beta3.Value getValue( + com.google.datastore.v1beta3.Value from) { return from; } @Override - protected void setValue(RawValue from, DatastoreV1.Value.Builder to) { + protected void setValue(RawValue from, com.google.datastore.v1beta3.Value.Builder to) { to.mergeFrom(from.get()); } }; public static final class Builder - extends Value.BaseBuilder { + extends Value.BaseBuilder { private Builder() { super(ValueType.RAW_VALUE); @@ -65,7 +64,7 @@ private RawValue(Builder builder) { super(builder); } - RawValue(DatastoreV1.Value valuePb) { + RawValue(com.google.datastore.v1beta3.Value valuePb) { this(builder(valuePb)); } @@ -74,18 +73,14 @@ public Builder toBuilder() { return new Builder().mergeFrom(this); } - static RawValue of(DatastoreV1.Value valuePb) { + static RawValue of(com.google.datastore.v1beta3.Value valuePb) { return new RawValue(valuePb); } - static Builder builder(DatastoreV1.Value valuePb) { + static Builder builder(com.google.datastore.v1beta3.Value valuePb) { Builder builder = new Builder(); - if (valuePb.hasIndexed()) { - builder.indexed(valuePb.getIndexed()); - } - if (valuePb.hasMeaning()) { - builder.meaning(valuePb.getMeaning()); - } + builder.excludeFromIndexes(valuePb.getExcludeFromIndexes()); + builder.meaning(valuePb.getMeaning()); builder.set(valuePb); return builder; } diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ReadOption.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ReadOption.java new file mode 100644 index 000000000000..f0de06d1651d --- /dev/null +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ReadOption.java @@ -0,0 +1,68 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.gcloud.datastore; + +import com.google.common.collect.ImmutableMap; + +import java.io.Serializable; +import java.util.Map; + +/** + * Specifies options for read operations in Datastore, namely getting/fetching entities and running + * queries. + */ +public abstract class ReadOption implements Serializable { + + private static final long serialVersionUID = -4406964829189800528L; + + /** + * Specifies eventual consistency for reads from Datastore. Lookups and ancestor queries using + * this option permit Datastore to return stale results. + */ + public static final class EventualConsistency extends ReadOption { + + private static final long serialVersionUID = -6959530217724666172L; + + private final boolean eventualConsistency; + + private EventualConsistency(boolean eventualConsistency) { + this.eventualConsistency = eventualConsistency; + } + + public boolean isEventual() { + return eventualConsistency; + } + } + + private ReadOption() {} + + /** + * Returns a {@code ReadOption} that specifies eventual consistency, allowing Datastore to return + * stale results from gets, fetches, and ancestor queries. + */ + public static EventualConsistency eventualConsistency() { + return new EventualConsistency(true); + } + + static Map, ReadOption> asImmutableMap(ReadOption... options) { + ImmutableMap.Builder, ReadOption> builder = ImmutableMap.builder(); + for (ReadOption option : options) { + builder.put(option.getClass(), option); + } + return builder.build(); + } +} diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/StringValue.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/StringValue.java index 95a31e714876..4b2c8e123be7 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/StringValue.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/StringValue.java @@ -16,9 +16,7 @@ package com.google.gcloud.datastore; -import static com.google.api.services.datastore.DatastoreV1.Value.STRING_VALUE_FIELD_NUMBER; - -import com.google.api.services.datastore.DatastoreV1; +import static com.google.datastore.v1beta3.Value.STRING_VALUE_FIELD_NUMBER; public final class StringValue extends Value { @@ -40,12 +38,12 @@ public Builder newBuilder(String value) { } @Override - protected String getValue(DatastoreV1.Value from) { + protected String getValue(com.google.datastore.v1beta3.Value from) { return from.getStringValue(); } @Override - protected void setValue(StringValue from, DatastoreV1.Value.Builder to) { + protected void setValue(StringValue from, com.google.datastore.v1beta3.Value.Builder to) { to.setStringValue(from.get()); } }; diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/StructuredQuery.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/StructuredQuery.java index 5892268f859c..d91956d6c1db 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/StructuredQuery.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/StructuredQuery.java @@ -25,7 +25,6 @@ import static com.google.gcloud.datastore.LongValue.of; import static com.google.gcloud.datastore.StringValue.of; -import com.google.api.services.datastore.DatastoreV1; import com.google.common.base.MoreObjects; import com.google.common.base.MoreObjects.ToStringHelper; import com.google.common.base.Preconditions; @@ -53,14 +52,14 @@ * Entity entity = results.next(); * ... * } - * } + * } * *

A simple key-only query of all entities for a specific kind *

 {@code
  * Query keyOnlyQuery =  Query.keyQueryBuilder().kind(KIND1).build();
  * QueryResults results = datastore.run(keyOnlyQuery);
  * ...
- * } 
+ * } * *

A less trivial example of a projection query that returns the first 10 results * of "age" and "name" properties (sorted and grouped by "age") with an age greater than 18 @@ -75,7 +74,7 @@ * .build(); * QueryResults results = datastore.run(query); * ... - * } + * } * * @param the type of the result values this query will produce * @see Datastore @@ -87,9 +86,9 @@ public abstract class StructuredQuery extends Query { static final String KEY_PROPERTY_NAME = "__key__"; private final transient String kind; - private final ImmutableList projection; + private final ImmutableList projection; private final transient Filter filter; - private final ImmutableList groupBy; + private final ImmutableList distinctOn; private final transient ImmutableList orderBy; private final transient Cursor startCursor; private final transient Cursor endCursor; @@ -103,13 +102,17 @@ public abstract static class Filter implements Serializable { Filter() { } - abstract DatastoreV1.Filter toPb(); + abstract com.google.datastore.v1beta3.Filter toPb(); - static Filter fromPb(DatastoreV1.Filter filterPb) { - if (filterPb.hasCompositeFilter()) { - return CompositeFilter.fromPb(filterPb.getCompositeFilter()); + static Filter fromPb(com.google.datastore.v1beta3.Filter filterPb) { + switch (filterPb.getFilterTypeCase()) { + case COMPOSITE_FILTER: + return CompositeFilter.fromPb(filterPb.getCompositeFilter()); + case PROPERTY_FILTER: + return PropertyFilter.fromPb(filterPb.getPropertyFilter()); + default: + throw new AssertionError("Unexpected enum value " + filterPb.getFilterTypeCase()); } - return PropertyFilter.fromPb(filterPb.getPropertyFilter()); } } @@ -125,11 +128,11 @@ public static final class CompositeFilter extends Filter { enum Operator { AND; - DatastoreV1.CompositeFilter.Operator toPb() { - return DatastoreV1.CompositeFilter.Operator.valueOf(name()); + com.google.datastore.v1beta3.CompositeFilter.Operator toPb() { + return com.google.datastore.v1beta3.CompositeFilter.Operator.valueOf(name()); } - static Operator fromPb(DatastoreV1.CompositeFilter.Operator operatorPb) { + static Operator fromPb(com.google.datastore.v1beta3.CompositeFilter.Operator operatorPb) { return valueOf(operatorPb.name()); } } @@ -172,11 +175,14 @@ public boolean equals(Object obj) { && filters.equals(other.filters); } - static CompositeFilter fromPb(DatastoreV1.CompositeFilter compositeFilterPb) { - Operator operator = Operator.fromPb(compositeFilterPb.getOperator()); + static CompositeFilter fromPb(com.google.datastore.v1beta3.CompositeFilter compositeFilterPb) { + Operator operator = Operator.fromPb(compositeFilterPb.getOp()); ImmutableList.Builder filters = ImmutableList.builder(); - for (DatastoreV1.Filter filterPb : compositeFilterPb.getFilterList()) { - filters.add(Filter.fromPb(filterPb)); + for (com.google.datastore.v1beta3.Filter filterPb : compositeFilterPb.getFiltersList()) { + Filter currFilter = Filter.fromPb(filterPb); + if (currFilter != null) { + filters.add(currFilter); + } } return new CompositeFilter(operator, filters.build()); } @@ -186,12 +192,14 @@ public static CompositeFilter and(Filter first, Filter... other) { } @Override - DatastoreV1.Filter toPb() { - DatastoreV1.Filter.Builder filterPb = DatastoreV1.Filter.newBuilder(); - DatastoreV1.CompositeFilter.Builder compositeFilterPb = filterPb.getCompositeFilterBuilder(); - compositeFilterPb.setOperator(operator.toPb()); + com.google.datastore.v1beta3.Filter toPb() { + com.google.datastore.v1beta3.Filter.Builder filterPb = + com.google.datastore.v1beta3.Filter.newBuilder(); + com.google.datastore.v1beta3.CompositeFilter.Builder compositeFilterPb = + filterPb.getCompositeFilterBuilder(); + compositeFilterPb.setOp(operator.toPb()); for (Filter filter : filters) { - compositeFilterPb.addFilter(filter.toPb()); + compositeFilterPb.addFilters(filter.toPb()); } return filterPb.build(); } @@ -216,11 +224,11 @@ enum Operator { EQUAL, HAS_ANCESTOR; - DatastoreV1.PropertyFilter.Operator toPb() { - return DatastoreV1.PropertyFilter.Operator.valueOf(name()); + com.google.datastore.v1beta3.PropertyFilter.Operator toPb() { + return com.google.datastore.v1beta3.PropertyFilter.Operator.valueOf(name()); } - static Operator fromPb(DatastoreV1.PropertyFilter.Operator operatorPb) { + static Operator fromPb(com.google.datastore.v1beta3.PropertyFilter.Operator operatorPb) { return valueOf(operatorPb.name()); } } @@ -231,9 +239,9 @@ private PropertyFilter(String property, Operator operator, Value value) { this.value = checkNotNull(value); } - static PropertyFilter fromPb(DatastoreV1.PropertyFilter propertyFilterPb) { + static PropertyFilter fromPb(com.google.datastore.v1beta3.PropertyFilter propertyFilterPb) { String property = propertyFilterPb.getProperty().getName(); - Operator operator = Operator.fromPb(propertyFilterPb.getOperator()); + Operator operator = Operator.fromPb(propertyFilterPb.getOp()); Value value = Value.fromPb(propertyFilterPb.getValue()); return new PropertyFilter(property, operator, value); } @@ -435,11 +443,13 @@ public static PropertyFilter isNull(String property) { } @Override - DatastoreV1.Filter toPb() { - DatastoreV1.Filter.Builder filterPb = DatastoreV1.Filter.newBuilder(); - DatastoreV1.PropertyFilter.Builder propertyFilterPb = filterPb.getPropertyFilterBuilder(); + com.google.datastore.v1beta3.Filter toPb() { + com.google.datastore.v1beta3.Filter.Builder filterPb = + com.google.datastore.v1beta3.Filter.newBuilder(); + com.google.datastore.v1beta3.PropertyFilter.Builder propertyFilterPb = + filterPb.getPropertyFilterBuilder(); propertyFilterPb.getPropertyBuilder().setName(property); - propertyFilterPb.setOperator(operator.toPb()); + propertyFilterPb.setOp(operator.toPb()); if (value != null) { propertyFilterPb.setValue(value.toPb()); } @@ -458,11 +468,11 @@ public enum Direction { ASCENDING, DESCENDING; - DatastoreV1.PropertyOrder.Direction toPb() { - return DatastoreV1.PropertyOrder.Direction.valueOf(name()); + com.google.datastore.v1beta3.PropertyOrder.Direction toPb() { + return com.google.datastore.v1beta3.PropertyOrder.Direction.valueOf(name()); } - static Direction fromPb(DatastoreV1.PropertyOrder.Direction directionPb) { + static Direction fromPb(com.google.datastore.v1beta3.PropertyOrder.Direction directionPb) { return valueOf(directionPb.name()); } } @@ -498,10 +508,11 @@ public Direction direction() { return direction; } - DatastoreV1.PropertyOrder toPb() { - return DatastoreV1.PropertyOrder.newBuilder() + com.google.datastore.v1beta3.PropertyOrder toPb() { + return com.google.datastore.v1beta3.PropertyOrder.newBuilder() .setDirection(direction.toPb()) - .setProperty(DatastoreV1.PropertyReference.newBuilder().setName(property).build()) + .setProperty(com.google.datastore.v1beta3.PropertyReference.newBuilder() + .setName(property).build()) .build(); } @@ -513,102 +524,13 @@ public static OrderBy desc(String property) { return new OrderBy(property, OrderBy.Direction.DESCENDING); } - static OrderBy fromPb(DatastoreV1.PropertyOrder propertyOrderPb) { + static OrderBy fromPb(com.google.datastore.v1beta3.PropertyOrder propertyOrderPb) { String property = propertyOrderPb.getProperty().getName(); Direction direction = Direction.fromPb(propertyOrderPb.getDirection()); return new OrderBy(property, direction); } } - /** - * A class representing a projection based on a property. - */ - public static final class Projection implements Serializable { - - private static final long serialVersionUID = 3083707957256279470L; - - private final Aggregate aggregate; - private final String property; - - public enum Aggregate { - - FIRST; - - DatastoreV1.PropertyExpression.AggregationFunction toPb() { - return DatastoreV1.PropertyExpression.AggregationFunction.valueOf(name()); - } - - static Aggregate fromPb(DatastoreV1.PropertyExpression.AggregationFunction aggregatePb) { - return valueOf(aggregatePb.name()); - } - } - - private Projection(Aggregate aggregate, String property) { - this.aggregate = aggregate; - this.property = property; - } - - @Override - public int hashCode() { - return Objects.hash(property, aggregate); - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof Projection)) { - return false; - } - Projection other = (Projection) obj; - return Objects.equals(property, other.property) - && Objects.equals(aggregate, other.aggregate); - } - - @Override - public String toString() { - ToStringHelper toStringHelper = MoreObjects.toStringHelper(this); - toStringHelper.add("property", property); - if (aggregate != null) { - toStringHelper.add("aggregate", aggregate); - } - return toStringHelper.toString(); - } - - DatastoreV1.PropertyExpression toPb() { - DatastoreV1.PropertyExpression.Builder expressionPb = - DatastoreV1.PropertyExpression.newBuilder(); - if (aggregate != null) { - expressionPb.setAggregationFunction(aggregate.toPb()); - } - expressionPb.setProperty( - DatastoreV1.PropertyReference.newBuilder().setName(property).build()); - return expressionPb.build(); - } - - static Projection fromPb(DatastoreV1.PropertyExpression propertyExpressionPb) { - String property = propertyExpressionPb.getProperty().getName(); - Aggregate aggregate = null; - if (propertyExpressionPb.hasAggregationFunction()) { - aggregate = Aggregate.fromPb(propertyExpressionPb.getAggregationFunction()); - } - return new Projection(aggregate, property); - } - - public static Projection property(String property) { - return new Projection(null, property); - } - - public static Projection aggregate(Aggregate aggregate, String property) { - return new Projection(aggregate, property); - } - - public static Projection first(String property) { - return new Projection(Aggregate.FIRST, property); - } - } - /** * Interface for StructuredQuery builders. * @@ -655,9 +577,9 @@ abstract static class BuilderImpl> implements Bui private final ResultType resultType; private String namespace; private String kind; - private final List projection = new LinkedList<>(); + private final List projection = new LinkedList<>(); private Filter filter; - private final List groupBy = new LinkedList<>(); + private final List distinctOn = new LinkedList<>(); private final List orderBy = new LinkedList<>(); private Cursor startCursor; private Cursor endCursor; @@ -674,7 +596,7 @@ abstract static class BuilderImpl> implements Bui kind = query.kind; projection.addAll(query.projection); filter = query.filter; - groupBy.addAll(query.groupBy); + distinctOn.addAll(query.distinctOn); orderBy.addAll(query.orderBy); startCursor = query.startCursor; endCursor = query.endCursor; @@ -756,62 +678,65 @@ B clearProjection() { return self(); } - B projection(Projection projection, Projection... others) { + B projection(String projection, String... others) { clearProjection(); addProjection(projection, others); return self(); } - B addProjection(Projection projection, Projection... others) { + B addProjection(String projection, String... others) { this.projection.add(projection); Collections.addAll(this.projection, others); return self(); } - B clearGroupBy() { - groupBy.clear(); + B clearDistinctOn() { + distinctOn.clear(); return self(); } - B groupBy(String property, String... others) { - clearGroupBy(); - addGroupBy(property, others); + B distinctOn(String property, String... others) { + clearDistinctOn(); + addDistinctOn(property, others); return self(); } - B addGroupBy(String property, String... others) { - this.groupBy.add(property); - Collections.addAll(this.groupBy, others); + B addDistinctOn(String property, String... others) { + this.distinctOn.add(property); + Collections.addAll(this.distinctOn, others); return self(); } - B mergeFrom(DatastoreV1.Query queryPb) { + B mergeFrom(com.google.datastore.v1beta3.Query queryPb) { if (queryPb.getKindCount() > 0) { kind(queryPb.getKind(0).getName()); } - if (queryPb.hasStartCursor()) { + if (!queryPb.getStartCursor().isEmpty()) { startCursor(new Cursor(queryPb.getStartCursor())); } - if (queryPb.hasEndCursor()) { + if (!queryPb.getEndCursor().isEmpty()) { endCursor(new Cursor(queryPb.getEndCursor())); } - if (queryPb.hasOffset()) { - offset(queryPb.getOffset()); - } + offset(queryPb.getOffset()); if (queryPb.hasLimit()) { - limit(queryPb.getLimit()); + limit(queryPb.getLimit().getValue()); } if (queryPb.hasFilter()) { - filter(Filter.fromPb(queryPb.getFilter())); + Filter currFilter = Filter.fromPb(queryPb.getFilter()); + if (currFilter != null) { + filter(currFilter); + } } - for (DatastoreV1.PropertyOrder orderByPb : queryPb.getOrderList()) { + for (com.google.datastore.v1beta3.PropertyOrder orderByPb : queryPb.getOrderList()) { addOrderBy(OrderBy.fromPb(orderByPb)); } - for (DatastoreV1.PropertyExpression projectionPb : queryPb.getProjectionList()) { - addProjection(Projection.fromPb(projectionPb)); + for (com.google.datastore.v1beta3.Projection projectionPb + : queryPb.getProjectionList()) { + addProjection(projectionPb.getProperty().getName()); } - for (DatastoreV1.PropertyReference groupByPb : queryPb.getGroupByList()) { - addGroupBy(groupByPb.getName()); + for (com.google.datastore.v1beta3.PropertyReference distinctOnPb : + queryPb.getDistinctOnList()) { + addDistinctOn(distinctOnPb.getName()); } return self(); } @@ -822,7 +747,7 @@ B mergeFrom(DatastoreV1.Query queryPb) { kind = builder.kind; projection = ImmutableList.copyOf(builder.projection); filter = builder.filter; - groupBy = ImmutableList.copyOf(builder.groupBy); + distinctOn = ImmutableList.copyOf(builder.distinctOn); orderBy = ImmutableList.copyOf(builder.orderBy); startCursor = builder.startCursor; endCursor = builder.endCursor; @@ -833,7 +758,7 @@ B mergeFrom(DatastoreV1.Query queryPb) { @Override public int hashCode() { return Objects.hash(namespace(), kind, startCursor, endCursor, offset, limit, filter, orderBy, - projection(), groupBy()); +distinctOn()); } @Override @@ -854,7 +779,7 @@ public boolean equals(Object obj) { && Objects.equals(filter, other.filter) && Objects.equals(orderBy, other.orderBy) && Objects.equals(projection, other.projection) - && Objects.equals(groupBy, other.groupBy); + && Objects.equals(distinctOn, other.distinctOn); } @@ -863,10 +788,10 @@ public String kind() { } boolean keyOnly() { - return projection.size() == 1 && KEY_PROPERTY_NAME.equals(projection.get(0).property); + return projection.size() == 1 && KEY_PROPERTY_NAME.equals(projection.get(0)); } - public List projection() { + public List projection() { return projection; } @@ -874,8 +799,8 @@ public Filter filter() { return filter; } - public List groupBy() { - return groupBy; + public List distinctOn() { + return distinctOn; } public ImmutableList orderBy() { @@ -901,28 +826,29 @@ public Integer limit() { public abstract Builder toBuilder(); @Override - void populatePb(DatastoreV1.RunQueryRequest.Builder requestPb) { + void populatePb(com.google.datastore.v1beta3.RunQueryRequest.Builder requestPb) { requestPb.setQuery(toPb()); } @Override - StructuredQuery nextQuery(DatastoreV1.QueryResultBatch responsePb) { + StructuredQuery nextQuery(com.google.datastore.v1beta3.RunQueryResponse responsePb) { Builder builder = toBuilder(); - builder.startCursor(new Cursor(responsePb.getEndCursor())); - if (offset > 0 && responsePb.getSkippedResults() < offset) { - builder.offset(offset - responsePb.getSkippedResults()); + builder.startCursor(new Cursor(responsePb.getBatch().getEndCursor())); + if (offset > 0 && responsePb.getBatch().getSkippedResults() < offset) { + builder.offset(offset - responsePb.getBatch().getSkippedResults()); } else { builder.offset(0); if (limit != null) { - builder.limit(limit - responsePb.getEntityResultCount()); + builder.limit(limit - responsePb.getBatch().getEntityResultsCount()); } } return builder.build(); } @Override - DatastoreV1.Query toPb() { - DatastoreV1.Query.Builder queryPb = DatastoreV1.Query.newBuilder(); + com.google.datastore.v1beta3.Query toPb() { + com.google.datastore.v1beta3.Query.Builder queryPb = + com.google.datastore.v1beta3.Query.newBuilder(); if (kind != null) { queryPb.addKindBuilder().setName(kind); } @@ -936,7 +862,7 @@ DatastoreV1.Query toPb() { queryPb.setOffset(offset); } if (limit != null) { - queryPb.setLimit(limit); + queryPb.setLimit(com.google.protobuf.Int32Value.newBuilder().setValue(limit.intValue())); } if (filter != null) { queryPb.setFilter(filter.toPb()); @@ -944,11 +870,16 @@ DatastoreV1.Query toPb() { for (OrderBy value : orderBy) { queryPb.addOrder(value.toPb()); } - for (String value : groupBy) { - queryPb.addGroupBy(DatastoreV1.PropertyReference.newBuilder().setName(value).build()); + for (String value : distinctOn) { + queryPb.addDistinctOn(com.google.datastore.v1beta3.PropertyReference.newBuilder() + .setName(value).build()); } - for (Projection value : projection) { - queryPb.addProjection(value.toPb()); + for (String value : projection) { + com.google.datastore.v1beta3.Projection.Builder expressionPb = + com.google.datastore.v1beta3.Projection.newBuilder(); + expressionPb.setProperty( + com.google.datastore.v1beta3.PropertyReference.newBuilder().setName(value).build()); + queryPb.addProjection(expressionPb.build()); } return queryPb.build(); } @@ -956,11 +887,12 @@ DatastoreV1.Query toPb() { @Override Object fromPb(ResultType resultType, String namespace, byte[] bytesPb) throws InvalidProtocolBufferException { - return fromPb(resultType, namespace, DatastoreV1.Query.parseFrom(bytesPb)); + return fromPb(resultType, namespace, com.google.datastore.v1beta3.Query.parseFrom(bytesPb)); } - static StructuredQuery fromPb(ResultType resultType, String namespace, - DatastoreV1.Query queryPb) { + @SuppressWarnings("unchecked") + static StructuredQuery fromPb(ResultType resultType, String namespace, + com.google.datastore.v1beta3.Query queryPb) { BuilderImpl builder; if (resultType.equals(ResultType.ENTITY)) { builder = new EntityQuery.Builder(); @@ -969,6 +901,6 @@ static StructuredQuery fromPb(ResultType resultType, String namespace, } else { builder = new ProjectionEntityQuery.Builder(); } - return builder.namespace(namespace).mergeFrom(queryPb).build(); + return (StructuredQuery) builder.namespace(namespace).mergeFrom(queryPb).build(); } } diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/TransactionImpl.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/TransactionImpl.java index ae677aa005d6..469c14e1c78a 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/TransactionImpl.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/TransactionImpl.java @@ -16,56 +16,45 @@ package com.google.gcloud.datastore; -import com.google.api.services.datastore.DatastoreV1; -import com.google.common.base.Function; -import com.google.common.collect.Lists; -import com.google.gcloud.datastore.TransactionOption.ForceWrites; -import com.google.gcloud.datastore.TransactionOption.IsolationLevel; import com.google.protobuf.ByteString; +import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import java.util.Map; final class TransactionImpl extends BaseDatastoreBatchWriter implements Transaction { private final DatastoreImpl datastore; private final ByteString transaction; - private final boolean force; private boolean rolledback; static class ResponseImpl implements Transaction.Response { - private final DatastoreV1.CommitResponse response; + private final com.google.datastore.v1beta3.CommitResponse response; + private final int numAutoAllocatedIds; - ResponseImpl(DatastoreV1.CommitResponse response) { + ResponseImpl(com.google.datastore.v1beta3.CommitResponse response, int numAutoAllocatedIds) { this.response = response; + this.numAutoAllocatedIds = numAutoAllocatedIds; } @Override public List generatedKeys() { - return Lists.transform(response.getMutationResult().getInsertAutoIdKeyList(), - new Function() { - @Override public Key apply(DatastoreV1.Key keyPb) { - return Key.fromPb(keyPb); - } - }); + Iterator results = + response.getMutationResultsList().iterator(); + List generated = new ArrayList<>(numAutoAllocatedIds); + for (int i = 0; i < numAutoAllocatedIds; i++) { + generated.add(Key.fromPb(results.next().getKey())); + } + return generated; } } - TransactionImpl(DatastoreImpl datastore, TransactionOption... options) { + TransactionImpl(DatastoreImpl datastore) { super("transaction"); this.datastore = datastore; - DatastoreV1.BeginTransactionRequest.Builder requestPb = - DatastoreV1.BeginTransactionRequest.newBuilder(); - Map, TransactionOption> optionsMap = - TransactionOption.asImmutableMap(options); - IsolationLevel isolationLevel = (IsolationLevel) optionsMap.get(IsolationLevel.class); - if (isolationLevel != null) { - requestPb.setIsolationLevel(isolationLevel.level().toPb()); - } - ForceWrites forceWrites = (ForceWrites) optionsMap.get(TransactionOption.ForceWrites.class); - force = forceWrites != null && forceWrites.force(); + com.google.datastore.v1beta3.BeginTransactionRequest.Builder requestPb = + com.google.datastore.v1beta3.BeginTransactionRequest.newBuilder(); transaction = datastore.requestTransactionId(requestPb); } @@ -77,7 +66,8 @@ public Entity get(Key key) { @Override public Iterator get(Key... keys) { validateActive(); - DatastoreV1.ReadOptions.Builder readOptionsPb = DatastoreV1.ReadOptions.newBuilder(); + com.google.datastore.v1beta3.ReadOptions.Builder readOptionsPb = + com.google.datastore.v1beta3.ReadOptions.newBuilder(); readOptionsPb.setTransaction(transaction); return datastore.get(readOptionsPb.build(), keys); } @@ -91,7 +81,8 @@ public List fetch(Key... keys) { @Override public QueryResults run(Query query) { validateActive(); - DatastoreV1.ReadOptions.Builder readOptionsPb = DatastoreV1.ReadOptions.newBuilder(); + com.google.datastore.v1beta3.ReadOptions.Builder readOptionsPb = + com.google.datastore.v1beta3.ReadOptions.newBuilder(); readOptionsPb.setTransaction(transaction); return datastore.run(readOptionsPb.build(), query); } @@ -99,17 +90,15 @@ public QueryResults run(Query query) { @Override public Transaction.Response commit() { validateActive(); - DatastoreV1.Mutation.Builder mutationPb = toMutationPb(); - if (force) { - mutationPb.setForce(force); - } - DatastoreV1.CommitRequest.Builder requestPb = DatastoreV1.CommitRequest.newBuilder(); - requestPb.setMode(DatastoreV1.CommitRequest.Mode.TRANSACTIONAL); + List mutationsPb = toMutationPbList(); + com.google.datastore.v1beta3.CommitRequest.Builder requestPb = + com.google.datastore.v1beta3.CommitRequest.newBuilder(); + requestPb.setMode(com.google.datastore.v1beta3.CommitRequest.Mode.TRANSACTIONAL); requestPb.setTransaction(transaction); - requestPb.setMutation(mutationPb); - DatastoreV1.CommitResponse responsePb = datastore.commit(requestPb.build()); + requestPb.addAllMutations(mutationsPb); + com.google.datastore.v1beta3.CommitResponse responsePb = datastore.commit(requestPb.build()); deactivate(); - return new ResponseImpl(responsePb); + return new ResponseImpl(responsePb, toAddAutoId().size()); } @Override diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/TransactionOption.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/TransactionOption.java deleted file mode 100644 index c1c8368213dc..000000000000 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/TransactionOption.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2015 Google Inc. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.gcloud.datastore; - -import com.google.api.services.datastore.DatastoreV1; -import com.google.common.collect.ImmutableMap; - -import java.io.Serializable; -import java.util.Map; - - -public abstract class TransactionOption implements Serializable { - - private static final long serialVersionUID = -1862234444015690375L; - - public static final class ForceWrites extends TransactionOption { - - private static final long serialVersionUID = -6873967516988380886L; - - private final boolean force; - - public ForceWrites(boolean force) { - this.force = force; - } - - public boolean force() { - return force; - } - - @Override - BatchOption toBatchWriteOption() { - return new BatchOption.ForceWrites(force); - } - } - - public static final class IsolationLevel extends TransactionOption { - - private static final long serialVersionUID = -5592165378565409515L; - - private final Level level; - - public enum Level { - - SERIALIZABLE(DatastoreV1.BeginTransactionRequest.IsolationLevel.SERIALIZABLE), - SNAPSHOT(DatastoreV1.BeginTransactionRequest.IsolationLevel.SNAPSHOT); - - private final DatastoreV1.BeginTransactionRequest.IsolationLevel levelPb; - - Level(DatastoreV1.BeginTransactionRequest.IsolationLevel levelPb) { - this.levelPb = levelPb; - } - - DatastoreV1.BeginTransactionRequest.IsolationLevel toPb() { - return levelPb; - } - } - - public IsolationLevel(Level level) { - this.level = level; - } - - - public Level level() { - return level; - } - - @Override - BatchOption toBatchWriteOption() { - return null; - } - } - - TransactionOption() { - // package protected - } - - public static ForceWrites forceWrites() { - return new ForceWrites(true); - } - - public static IsolationLevel serializable() { - return new IsolationLevel(IsolationLevel.Level.SERIALIZABLE); - } - - public static IsolationLevel snapshot() { - return new IsolationLevel(IsolationLevel.Level.SNAPSHOT); - } - - static Map, TransactionOption> asImmutableMap( - TransactionOption... options) { - ImmutableMap.Builder, TransactionOption> builder = - ImmutableMap.builder(); - for (TransactionOption option : options) { - builder.put(option.getClass(), option); - } - return builder.build(); - } - - abstract BatchOption toBatchWriteOption(); -} diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Validator.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Validator.java index 09a3fa7defcc..dc7069cebf62 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Validator.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Validator.java @@ -45,13 +45,11 @@ static String validateDatabase(String projectId) { } static String validateNamespace(String namespace) { - if (namespace != null) { - checkArgument(!namespace.isEmpty(), "namespace must not be an empty string"); - checkArgument(namespace.length() <= MAX_NAMESPACE_LENGTH, - "namespace must not contain more than 100 characters"); - checkArgument(NAMESPACE_PATTERN.matcher(namespace).matches(), - "namespace must the following pattern: " + NAMESPACE_PATTERN.pattern()); - } + checkArgument(namespace != null, "Namespace cannot be null. Leave unset for default."); + checkArgument(namespace.length() <= MAX_NAMESPACE_LENGTH, + "namespace must not contain more than 100 characters"); + checkArgument(NAMESPACE_PATTERN.matcher(namespace).matches(), + "namespace must the following pattern: " + NAMESPACE_PATTERN.pattern()); return namespace; } diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Value.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Value.java index 4d8aaec086f1..4f3d39f1dae1 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Value.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/Value.java @@ -18,11 +18,9 @@ import static com.google.common.base.Preconditions.checkNotNull; -import com.google.api.services.datastore.DatastoreV1; -import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.datastore.v1beta3.Value.ValueTypeCase; import com.google.protobuf.InvalidProtocolBufferException; -import java.util.Map.Entry; import java.util.Objects; /** @@ -33,14 +31,14 @@ * * @param the type of the content for this value */ -public abstract class Value extends Serializable { +public abstract class Value extends Serializable { private static final long serialVersionUID = -1899638277588872742L; private final transient ValueType valueType; - private final transient Boolean indexed; - private final transient Integer meaning; + private final transient boolean excludeFromIndexes; + private final transient int meaning; private final transient V value; interface BuilderFactory, B extends ValueBuilder> @@ -55,34 +53,27 @@ abstract static class BaseMarshaller, B extends ValueBuild @SuppressWarnings("deprecation") @Override - public final B fromProto(DatastoreV1.Value proto) { + public final B fromProto(com.google.datastore.v1beta3.Value proto) { B builder = newBuilder(getValue(proto)); - if (proto.hasIndexed()) { - builder.indexed(proto.getIndexed()); - } - if (proto.hasMeaning()) { - builder.meaning(proto.getMeaning()); - } + builder.excludeFromIndexes(proto.getExcludeFromIndexes()); + builder.meaning(proto.getMeaning()); return builder; } @SuppressWarnings("deprecation") @Override - public final DatastoreV1.Value toProto(P value) { - DatastoreV1.Value.Builder builder = DatastoreV1.Value.newBuilder(); - if (value.hasIndexed()) { - builder.setIndexed(value.indexed()); - } - if (value.hasMeaning()) { - builder.setMeaning(value.meaning()); - } + public final com.google.datastore.v1beta3.Value toProto(P value) { + com.google.datastore.v1beta3.Value.Builder builder = + com.google.datastore.v1beta3.Value.newBuilder(); + builder.setExcludeFromIndexes(value.excludeFromIndexes()); + builder.setMeaning(value.meaning()); setValue(value, builder); return builder.build(); } - protected abstract V getValue(DatastoreV1.Value from); + protected abstract V getValue(com.google.datastore.v1beta3.Value from); - protected abstract void setValue(P from, DatastoreV1.Value.Builder to); + protected abstract void setValue(P from, com.google.datastore.v1beta3.Value.Builder to); } @SuppressWarnings("deprecation") @@ -90,8 +81,8 @@ abstract static class BaseBuilder, B extends BaseBuilder { private final ValueType valueType; - private Boolean indexed; - private Integer meaning; + private boolean excludeFromIndexes; + private int meaning; private V value; BaseBuilder(ValueType valueType) { @@ -105,30 +96,30 @@ public ValueType getValueType() { @Override public B mergeFrom(P other) { - indexed = other.indexed(); + excludeFromIndexes = other.excludeFromIndexes(); meaning = other.meaning(); set(other.get()); return self(); } @Override - public Boolean getIndexed() { - return indexed; + public boolean getExcludeFromIndexes() { + return excludeFromIndexes; } @Override - public B indexed(boolean indexed) { - this.indexed = indexed; + public B excludeFromIndexes(boolean excludeFromIndexes) { + this.excludeFromIndexes = excludeFromIndexes; return self(); } @Override - public Integer getMeaning() { + public int getMeaning() { return meaning; } @Override - public B meaning(Integer meaning) { + public B meaning(int meaning) { this.meaning = meaning; return self(); } @@ -155,7 +146,7 @@ private B self() {

, B extends BaseBuilder> Value(ValueBuilder builder) { valueType = builder.getValueType(); - indexed = builder.getIndexed(); + excludeFromIndexes = builder.getExcludeFromIndexes(); meaning = builder.getMeaning(); value = builder.get(); } @@ -164,21 +155,12 @@ public final ValueType type() { return valueType; } - public final boolean hasIndexed() { - return indexed != null; - } - - public final Boolean indexed() { - return indexed; - } - - @Deprecated - public final boolean hasMeaning() { - return meaning != null; + public final boolean excludeFromIndexes() { + return excludeFromIndexes; } @Deprecated - public final Integer meaning() { + final int meaning() { return meaning; } @@ -190,7 +172,7 @@ public final V get() { @Override public int hashCode() { - return Objects.hash(valueType, indexed, meaning, value); + return Objects.hash(valueType, excludeFromIndexes, meaning, value); } @Override @@ -204,34 +186,26 @@ public boolean equals(Object obj) { } Value other = (Value) obj; return Objects.equals(valueType, other.valueType) - && Objects.equals(indexed, other.indexed) + && Objects.equals(excludeFromIndexes, other.excludeFromIndexes) && Objects.equals(meaning, other.meaning) && Objects.equals(value, other.value); } @Override @SuppressWarnings("unchecked") - DatastoreV1.Value toPb() { + com.google.datastore.v1beta3.Value toPb() { return type().getMarshaller().toProto(this); } - static Value fromPb(DatastoreV1.Value proto) { - for (Entry entry : proto.getAllFields().entrySet()) { - FieldDescriptor descriptor = entry.getKey(); - if (descriptor.getName().endsWith("_value")) { - ValueType valueType = ValueType.getByDescriptorId(descriptor.getNumber()); - if (valueType == null) { - // unsupported type - return RawValue.MARSHALLER.fromProto(proto).build(); - } - return valueType.getMarshaller().fromProto(proto).build(); - } - } - return NullValue.MARSHALLER.fromProto(proto).build(); + static Value fromPb(com.google.datastore.v1beta3.Value proto) { + ValueTypeCase descriptorId = proto.getValueTypeCase(); + ValueType valueType = ValueType.getByDescriptorId(descriptorId.getNumber()); + return valueType == null ? RawValue.MARSHALLER.fromProto(proto).build() + : valueType.getMarshaller().fromProto(proto).build(); } @Override Object fromPb(byte[] bytesPb) throws InvalidProtocolBufferException { - return fromPb(DatastoreV1.Value.parseFrom(bytesPb)); + return fromPb(com.google.datastore.v1beta3.Value.parseFrom(bytesPb)); } } diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ValueBuilder.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ValueBuilder.java index a867ef25b321..236118a18620 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ValueBuilder.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ValueBuilder.java @@ -29,14 +29,14 @@ public interface ValueBuilder, B extends ValueBuilder, B extends ValueBuilder> extends java.io.Serializable { - B fromProto(DatastoreV1.Value proto); + B fromProto(com.google.datastore.v1beta3.Value proto); - DatastoreV1.Value toProto(P value); + com.google.datastore.v1beta3.Value toProto(P value); int getProtoFieldId(); } diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ValueType.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ValueType.java index b09583103a59..ab16126336f5 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ValueType.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/ValueType.java @@ -78,8 +78,12 @@ public enum ValueType { /** * Represents a raw/unparsed value. */ - RAW_VALUE(RawValue.MARSHALLER); + RAW_VALUE(RawValue.MARSHALLER), + /** + * Represents a {@link LatLng} value + */ + LAT_LNG(LatLngValue.MARSHALLER); private static final ImmutableMap DESCRIPTOR_TO_TYPE_MAP; diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/package-info.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/package-info.java index fbf468d6458d..f1ec9b925e7c 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/package-info.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/package-info.java @@ -54,6 +54,7 @@ * project ID and * provide * credentials. + * * @see Google Cloud Datastore */ package com.google.gcloud.datastore; diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/spi/DatastoreRpc.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/spi/DatastoreRpc.java index 002078550d1f..0aff146835e0 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/spi/DatastoreRpc.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/spi/DatastoreRpc.java @@ -16,18 +16,18 @@ package com.google.gcloud.datastore.spi; -import com.google.api.services.datastore.DatastoreV1.AllocateIdsRequest; -import com.google.api.services.datastore.DatastoreV1.AllocateIdsResponse; -import com.google.api.services.datastore.DatastoreV1.BeginTransactionRequest; -import com.google.api.services.datastore.DatastoreV1.BeginTransactionResponse; -import com.google.api.services.datastore.DatastoreV1.CommitRequest; -import com.google.api.services.datastore.DatastoreV1.CommitResponse; -import com.google.api.services.datastore.DatastoreV1.LookupRequest; -import com.google.api.services.datastore.DatastoreV1.LookupResponse; -import com.google.api.services.datastore.DatastoreV1.RollbackRequest; -import com.google.api.services.datastore.DatastoreV1.RollbackResponse; -import com.google.api.services.datastore.DatastoreV1.RunQueryRequest; -import com.google.api.services.datastore.DatastoreV1.RunQueryResponse; +import com.google.datastore.v1beta3.AllocateIdsRequest; +import com.google.datastore.v1beta3.AllocateIdsResponse; +import com.google.datastore.v1beta3.BeginTransactionRequest; +import com.google.datastore.v1beta3.BeginTransactionResponse; +import com.google.datastore.v1beta3.CommitRequest; +import com.google.datastore.v1beta3.CommitResponse; +import com.google.datastore.v1beta3.LookupRequest; +import com.google.datastore.v1beta3.LookupResponse; +import com.google.datastore.v1beta3.RollbackRequest; +import com.google.datastore.v1beta3.RollbackResponse; +import com.google.datastore.v1beta3.RunQueryRequest; +import com.google.datastore.v1beta3.RunQueryResponse; import com.google.gcloud.datastore.DatastoreException; /** diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/spi/DefaultDatastoreRpc.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/spi/DefaultDatastoreRpc.java index 093322fa4117..1fb0fa3a26c6 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/spi/DefaultDatastoreRpc.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/spi/DefaultDatastoreRpc.java @@ -16,64 +16,58 @@ package com.google.gcloud.datastore.spi; -import com.google.api.services.datastore.DatastoreV1.AllocateIdsRequest; -import com.google.api.services.datastore.DatastoreV1.AllocateIdsResponse; -import com.google.api.services.datastore.DatastoreV1.BeginTransactionRequest; -import com.google.api.services.datastore.DatastoreV1.BeginTransactionResponse; -import com.google.api.services.datastore.DatastoreV1.CommitRequest; -import com.google.api.services.datastore.DatastoreV1.CommitResponse; -import com.google.api.services.datastore.DatastoreV1.LookupRequest; -import com.google.api.services.datastore.DatastoreV1.LookupResponse; -import com.google.api.services.datastore.DatastoreV1.RollbackRequest; -import com.google.api.services.datastore.DatastoreV1.RollbackResponse; -import com.google.api.services.datastore.DatastoreV1.RunQueryRequest; -import com.google.api.services.datastore.DatastoreV1.RunQueryResponse; -import com.google.api.services.datastore.client.Datastore; -import com.google.api.services.datastore.client.DatastoreFactory; -import com.google.api.services.datastore.client.DatastoreOptions.Builder; -import com.google.common.base.Preconditions; +import com.google.datastore.v1beta3.AllocateIdsRequest; +import com.google.datastore.v1beta3.AllocateIdsResponse; +import com.google.datastore.v1beta3.BeginTransactionRequest; +import com.google.datastore.v1beta3.BeginTransactionResponse; +import com.google.datastore.v1beta3.CommitRequest; +import com.google.datastore.v1beta3.CommitResponse; +import com.google.datastore.v1beta3.LookupRequest; +import com.google.datastore.v1beta3.LookupResponse; +import com.google.datastore.v1beta3.RollbackRequest; +import com.google.datastore.v1beta3.RollbackResponse; +import com.google.datastore.v1beta3.RunQueryRequest; +import com.google.datastore.v1beta3.RunQueryResponse; import com.google.gcloud.datastore.DatastoreException; import com.google.gcloud.datastore.DatastoreOptions; -import org.json.JSONException; -import org.json.JSONObject; -import org.json.JSONTokener; - import java.io.IOException; import java.net.InetAddress; import java.net.URL; public class DefaultDatastoreRpc implements DatastoreRpc { - private final Datastore client; + private final com.google.datastore.v1beta3.client.Datastore client; public DefaultDatastoreRpc(DatastoreOptions options) { - String normalizedHost = normalizeHost(options.host()); - client = DatastoreFactory.get().create( - new Builder() - .dataset(options.projectId()) - .host(normalizedHost) - .initializer(options.httpRequestInitializer()) - .build()); - } - - private static String normalizeHost(String host) { - host = host.toLowerCase(); - if (includesScheme(host)) { - Preconditions.checkArgument(!(host.startsWith("https://") && isLocalHost(host)), - "\"https\" is not supported for localhost. Use \"http\" instead."); - return host; + com.google.datastore.v1beta3.client.DatastoreOptions.Builder clientBuilder = + new com.google.datastore.v1beta3.client.DatastoreOptions.Builder() + .projectId(options.projectId()) + .initializer(options.httpRequestInitializer()); + String normalizedHost = options.host() != null ? options.host().toLowerCase() : ""; + if (isLocalHost(normalizedHost)) { + clientBuilder = clientBuilder.localHost(removeScheme(normalizedHost)); + } else if (!removeScheme(com.google.datastore.v1beta3.client.DatastoreFactory.DEFAULT_HOST) + .equals(removeScheme(normalizedHost)) + && !normalizedHost.isEmpty()) { + String fullURL = normalizedHost; + if (fullURL.charAt(fullURL.length() - 1) != '/') { + fullURL = fullURL + '/'; + } + fullURL = fullURL + + com.google.datastore.v1beta3.client.DatastoreFactory.VERSION + + "/projects/" + + options.projectId(); + clientBuilder = clientBuilder.projectId(null).projectEndpoint(fullURL); } - return "http://" + host; + client = com.google.datastore.v1beta3.client.DatastoreFactory.get() + .create(clientBuilder.build()); } private static boolean isLocalHost(String host) { - if (host != null) { + if (!host.isEmpty()) { try { - String normalizedHost = host; - if (!includesScheme(normalizedHost)) { - normalizedHost = "http://" + normalizedHost; - } + String normalizedHost = "http://" + removeScheme(host); InetAddress hostAddr = InetAddress.getByName(new URL(normalizedHost).getHost()); return hostAddr.isAnyLocalAddress() || hostAddr.isLoopbackAddress(); } catch (Exception e) { @@ -83,38 +77,38 @@ private static boolean isLocalHost(String host) { return false; } - private static boolean includesScheme(String url) { - return url.startsWith("http://") || url.startsWith("https://"); + private static String removeScheme(String url) { + if (url != null) { + if (url.startsWith("https://")) { + return url.substring("https://".length()); + } else if (url.startsWith("http://")) { + return url.substring("http://".length()); + } + } + return url; } private static DatastoreException translate( - com.google.api.services.datastore.client.DatastoreException exception) { - String message = exception.getMessage(); - int code = exception.getCode(); + com.google.datastore.v1beta3.client.DatastoreException exception) { String reason = ""; - if (message != null) { - try { - JSONObject json = new JSONObject(new JSONTokener(message)); - JSONObject error = json.getJSONObject("error").getJSONArray("errors").getJSONObject(0); - reason = error.getString("reason"); - message = error.getString("message"); - } catch (JSONException ignore) { - // ignore - will be converted to unknown - } + if (exception.getCode() != null) { + reason = exception.getCode().name(); } - if (reason == null) { + if (reason.isEmpty()) { if (exception.getCause() instanceof IOException) { return new DatastoreException((IOException) exception.getCause()); } } - return new DatastoreException(code, message, reason, exception); + return new DatastoreException( + exception.getCode().ordinal(), exception.getMessage(), reason, exception); } @Override public AllocateIdsResponse allocateIds(AllocateIdsRequest request) { try { return client.allocateIds(request); - } catch (com.google.api.services.datastore.client.DatastoreException ex) { + } catch (com.google.datastore.v1beta3.client.DatastoreException ex) { + throw translate(ex); } } @@ -123,7 +117,7 @@ public AllocateIdsResponse allocateIds(AllocateIdsRequest request) { public BeginTransactionResponse beginTransaction(BeginTransactionRequest request) { try { return client.beginTransaction(request); - } catch (com.google.api.services.datastore.client.DatastoreException ex) { + } catch (com.google.datastore.v1beta3.client.DatastoreException ex) { throw translate(ex); } } @@ -132,7 +126,7 @@ public BeginTransactionResponse beginTransaction(BeginTransactionRequest request public CommitResponse commit(CommitRequest request) { try { return client.commit(request); - } catch (com.google.api.services.datastore.client.DatastoreException ex) { + } catch (com.google.datastore.v1beta3.client.DatastoreException ex) { throw translate(ex); } } @@ -141,7 +135,7 @@ public CommitResponse commit(CommitRequest request) { public LookupResponse lookup(LookupRequest request) { try { return client.lookup(request); - } catch (com.google.api.services.datastore.client.DatastoreException ex) { + } catch (com.google.datastore.v1beta3.client.DatastoreException ex) { throw translate(ex); } } @@ -150,7 +144,7 @@ public LookupResponse lookup(LookupRequest request) { public RollbackResponse rollback(RollbackRequest request) { try { return client.rollback(request); - } catch (com.google.api.services.datastore.client.DatastoreException ex) { + } catch (com.google.datastore.v1beta3.client.DatastoreException ex) { throw translate(ex); } } @@ -159,7 +153,7 @@ public RollbackResponse rollback(RollbackRequest request) { public RunQueryResponse runQuery(RunQueryRequest request) { try { return client.runQuery(request); - } catch (com.google.api.services.datastore.client.DatastoreException ex) { + } catch (com.google.datastore.v1beta3.client.DatastoreException ex) { throw translate(ex); } } diff --git a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/testing/LocalGcdHelper.java b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/testing/LocalGcdHelper.java index fdb6774f810f..6f1a76b0a482 100644 --- a/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/testing/LocalGcdHelper.java +++ b/gcloud-java-datastore/src/main/java/com/google/gcloud/datastore/testing/LocalGcdHelper.java @@ -77,11 +77,11 @@ public class LocalGcdHelper { public static final String DEFAULT_PROJECT_ID = "projectid1"; public static final int DEFAULT_PORT = 8080; - private static final String GCD_VERSION = "v1beta2"; - private static final String GCD_BUILD = "rev1-2.1.2b"; + private static final String GCD_VERSION = "v1beta3"; + private static final String GCD_BUILD = "1.0.0"; private static final String GCD_BASENAME = "gcd-" + GCD_VERSION + "-" + GCD_BUILD; private static final String GCD_FILENAME = GCD_BASENAME + ".zip"; - private static final String MD5_CHECKSUM = "d84384cdfa8658e1204f4f8be51300e8"; + private static final String MD5_CHECKSUM = "72156cc993835c57f72789519b85249b"; private static final URL GCD_URL; private static final String GCLOUD = "gcloud"; private static final Path INSTALLED_GCD_PATH; @@ -419,7 +419,7 @@ public void start(double consistency) throws IOException, InterruptedException { // If cloud is available we use it, otherwise we download and start gcd if (INSTALLED_GCD_PATH == null) { downloadGcd(); - gcdExecutablePath = gcdPath.resolve(GCD_BASENAME); + gcdExecutablePath = gcdPath.resolve("gcd"); } else { gcdExecutablePath = INSTALLED_GCD_PATH; } @@ -654,7 +654,7 @@ private static Map parseArgs(String[] args) { public static boolean isActive(String projectId, int port) { try { StringBuilder urlBuilder = new StringBuilder("http://localhost:").append(port); - urlBuilder.append("/datastore/v1beta2/datasets/").append(projectId).append("/lookup"); + urlBuilder.append("/datastore/v1beta3/projects/").append(projectId).append(":lookup"); URL url = new URL(urlBuilder.toString()); try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), UTF_8))) { diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/BaseDatastoreBatchWriterTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/BaseDatastoreBatchWriterTest.java index ad8e0cee266a..7e5938358299 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/BaseDatastoreBatchWriterTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/BaseDatastoreBatchWriterTest.java @@ -21,7 +21,6 @@ import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals; -import com.google.api.services.datastore.DatastoreV1; import com.google.common.collect.ImmutableList; import org.easymock.EasyMock; @@ -29,6 +28,7 @@ import org.junit.Before; import org.junit.Test; +import java.util.LinkedList; import java.util.List; public class BaseDatastoreBatchWriterTest { @@ -84,15 +84,16 @@ public void tearDown() { public void testAdd() throws Exception { Entity entity2 = Entity.builder(ENTITY2).key(Key.builder(KEY1).name("name2").build()).build(); - DatastoreV1.Mutation pb = DatastoreV1.Mutation.newBuilder() - .addInsert(ENTITY1.toPb()) - .addInsert(entity2.toPb()) - .addInsert(Entity.builder(KEY2, INCOMPLETE_ENTITY_1).build().toPb()) - .addInsert(Entity.builder(KEY3, INCOMPLETE_ENTITY_2).build().toPb()) - .build(); + List pbs = new LinkedList<>(); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setInsert(ENTITY1.toPb()).build()); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder() + .setInsert(Entity.builder(KEY2, INCOMPLETE_ENTITY_1).build().toPb()).build()); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder() + .setInsert(Entity.builder(KEY3, INCOMPLETE_ENTITY_2).build().toPb()).build()); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setInsert(entity2.toPb()).build()); List entities = batchWriter .add(ENTITY1, INCOMPLETE_ENTITY_1, INCOMPLETE_ENTITY_2, entity2); - assertEquals(pb, batchWriter.toMutationPb().build()); + assertEquals(pbs, batchWriter.toMutationPbList()); assertEquals(ENTITY1, entities.get(0)); assertEquals(Entity.builder(KEY2, INCOMPLETE_ENTITY_1).build(), entities.get(1)); assertEquals(Entity.builder(KEY3, INCOMPLETE_ENTITY_2).build(), entities.get(2)); @@ -101,12 +102,11 @@ public void testAdd() throws Exception { @Test public void testAddAfterDelete() throws Exception { - DatastoreV1.Mutation pb = DatastoreV1.Mutation.newBuilder() - .addUpsert(ENTITY1.toPb()) - .build(); + List pbs = new LinkedList<>(); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setUpsert(ENTITY1.toPb()).build()); batchWriter.delete(KEY1); batchWriter.add(ENTITY1); - assertEquals(pb, batchWriter.toMutationPb().build()); + assertEquals(pbs, batchWriter.toMutationPbList()); } @Test(expected = DatastoreException.class) @@ -135,14 +135,15 @@ public void testAddWhenNotActive() throws Exception { @Test public void testAddWithDeferredAllocation() throws Exception { - DatastoreV1.Mutation pb = DatastoreV1.Mutation.newBuilder() - .addInsert(ENTITY1.toPb()) - .addInsertAutoId(INCOMPLETE_ENTITY_1.toPb()) - .addInsertAutoId(INCOMPLETE_ENTITY_2.toPb()) - .build(); + List pbs = new LinkedList<>(); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder() + .setInsert(INCOMPLETE_ENTITY_1.toPb()).build()); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder() + .setInsert(INCOMPLETE_ENTITY_2.toPb()).build()); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setInsert(ENTITY1.toPb()).build()); batchWriter.addWithDeferredIdAllocation(ENTITY1, INCOMPLETE_ENTITY_1); batchWriter.addWithDeferredIdAllocation(INCOMPLETE_ENTITY_2); - assertEquals(pb, batchWriter.toMutationPb().build()); + assertEquals(pbs, batchWriter.toMutationPbList()); } @Test(expected = DatastoreException.class) @@ -153,47 +154,43 @@ public void testAddWithDeferredAllocationWhenNotActive() throws Exception { @Test public void testUpdate() throws Exception { - DatastoreV1.Mutation pb = DatastoreV1.Mutation.newBuilder() - .addUpdate(ENTITY1.toPb()) - .addUpdate(ENTITY2.toPb()) - .addUpdate(ENTITY3.toPb()) - .build(); + List pbs = new LinkedList<>(); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setUpdate(ENTITY1.toPb()).build()); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setUpdate(ENTITY2.toPb()).build()); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setUpdate(ENTITY3.toPb()).build()); batchWriter.update(ENTITY1, ENTITY2); batchWriter.update(ENTITY3); - assertEquals(pb, batchWriter.toMutationPb().build()); + assertEquals(pbs, batchWriter.toMutationPbList()); } @Test public void testUpdateAfterUpdate() throws Exception { Entity entity = Entity.builder(ENTITY1).set("foo", "bar").build(); - DatastoreV1.Mutation pb = DatastoreV1.Mutation.newBuilder() - .addUpdate(entity.toPb()) - .build(); + List pbs = new LinkedList<>(); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setUpdate(entity.toPb()).build()); batchWriter.update(ENTITY1); batchWriter.update(entity); - assertEquals(pb, batchWriter.toMutationPb().build()); + assertEquals(pbs, batchWriter.toMutationPbList()); } @Test public void testUpdateAfterAdd() throws Exception { Entity entity = Entity.builder(ENTITY1).set("foo", "bar").build(); - DatastoreV1.Mutation pb = DatastoreV1.Mutation.newBuilder() - .addUpsert(entity.toPb()) - .build(); + List pbs = new LinkedList<>(); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setUpsert(entity.toPb()).build()); batchWriter.add(ENTITY1); batchWriter.update(entity); - assertEquals(pb, batchWriter.toMutationPb().build()); + assertEquals(pbs, batchWriter.toMutationPbList()); } @Test public void testUpdateAfterPut() throws Exception { Entity entity = Entity.builder(ENTITY1).set("foo", "bar").build(); - DatastoreV1.Mutation pb = DatastoreV1.Mutation.newBuilder() - .addUpsert(entity.toPb()) - .build(); + List pbs = new LinkedList<>(); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setUpsert(entity.toPb()).build()); batchWriter.put(ENTITY1); batchWriter.update(entity); - assertEquals(pb, batchWriter.toMutationPb().build()); + assertEquals(pbs, batchWriter.toMutationPbList()); } @Test(expected = DatastoreException.class) @@ -210,58 +207,53 @@ public void testUpdateWhenNotActive() throws Exception { @Test public void testPut() throws Exception { - DatastoreV1.Mutation pb = DatastoreV1.Mutation.newBuilder() - .addUpsert(ENTITY1.toPb()) - .addUpsert(ENTITY2.toPb()) - .addUpsert(ENTITY3.toPb()) - .build(); + List pbs = new LinkedList<>(); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setUpsert(ENTITY1.toPb()).build()); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setUpsert(ENTITY2.toPb()).build()); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setUpsert(ENTITY3.toPb()).build()); batchWriter.put(ENTITY1, ENTITY2); batchWriter.put(ENTITY3); - assertEquals(pb, batchWriter.toMutationPb().build()); + assertEquals(pbs, batchWriter.toMutationPbList()); } @Test public void testPutAfterPut() throws Exception { Entity entity = Entity.builder(ENTITY1).set("foo", "bar").build(); - DatastoreV1.Mutation pb = DatastoreV1.Mutation.newBuilder() - .addUpsert(entity.toPb()) - .build(); + List pbs = new LinkedList<>(); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setUpsert(entity.toPb()).build()); batchWriter.put(ENTITY1); batchWriter.put(entity); - assertEquals(pb, batchWriter.toMutationPb().build()); + assertEquals(pbs, batchWriter.toMutationPbList()); } @Test public void testPutAfterAdd() throws Exception { Entity entity = Entity.builder(ENTITY1).set("foo", "bar").build(); - DatastoreV1.Mutation pb = DatastoreV1.Mutation.newBuilder() - .addUpsert(entity.toPb()) - .build(); + List pbs = new LinkedList<>(); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setUpsert(entity.toPb()).build()); batchWriter.add(ENTITY1); batchWriter.put(entity); - assertEquals(pb, batchWriter.toMutationPb().build()); + assertEquals(pbs, batchWriter.toMutationPbList()); } @Test public void testPutAfterUpdate() throws Exception { Entity entity = Entity.builder(ENTITY1).set("foo", "bar").build(); - DatastoreV1.Mutation pb = DatastoreV1.Mutation.newBuilder() - .addUpsert(entity.toPb()) - .build(); + List pbs = new LinkedList<>(); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setUpsert(entity.toPb()).build()); batchWriter.update(ENTITY1); batchWriter.put(entity); - assertEquals(pb, batchWriter.toMutationPb().build()); + assertEquals(pbs, batchWriter.toMutationPbList()); } @Test public void testPutAfterDelete() throws Exception { Entity entity = Entity.builder(ENTITY1).set("foo", "bar").build(); - DatastoreV1.Mutation pb = DatastoreV1.Mutation.newBuilder() - .addUpsert(entity.toPb()) - .build(); + List pbs = new LinkedList<>(); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setUpsert(entity.toPb()).build()); batchWriter.delete(KEY1); batchWriter.put(entity); - assertEquals(pb, batchWriter.toMutationPb().build()); + assertEquals(pbs, batchWriter.toMutationPbList()); } @Test(expected = DatastoreException.class) @@ -272,46 +264,44 @@ public void testPutWhenNotActive() throws Exception { @Test public void testDelete() throws Exception { - DatastoreV1.Mutation pb = DatastoreV1.Mutation.newBuilder() - .addDelete(KEY1.toPb()) - .addDelete(KEY2.toPb()) - .addDelete(KEY3.toPb()) - .build(); + List pbs = new LinkedList<>(); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setDelete(KEY1.toPb()).build()); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setDelete(KEY2.toPb()).build()); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setDelete(KEY3.toPb()).build()); batchWriter.delete(KEY1, KEY2); batchWriter.delete(KEY3); - assertEquals(pb, batchWriter.toMutationPb().build()); + assertEquals(pbs, batchWriter.toMutationPbList()); } @Test public void testDeleteAfterAdd() throws Exception { - DatastoreV1.Mutation pb = DatastoreV1.Mutation.newBuilder() - .addInsertAutoId(INCOMPLETE_ENTITY_1.toPb()) - .addDelete(KEY1.toPb()) - .build(); + List pbs = new LinkedList<>(); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder() + .setInsert(INCOMPLETE_ENTITY_1.toPb()).build()); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setDelete(KEY1.toPb()).build()); batchWriter.add(ENTITY1); batchWriter.addWithDeferredIdAllocation(INCOMPLETE_ENTITY_1); batchWriter.delete(KEY1); - assertEquals(pb, batchWriter.toMutationPb().build()); + assertEquals(pbs, batchWriter.toMutationPbList()); } + @Test public void testDeleteAfterUpdate() throws Exception { - DatastoreV1.Mutation pb = DatastoreV1.Mutation.newBuilder() - .addDelete(KEY1.toPb()) - .build(); + List pbs = new LinkedList<>(); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setDelete(KEY1.toPb()).build()); batchWriter.update(ENTITY1); batchWriter.delete(KEY1); - assertEquals(pb, batchWriter.toMutationPb().build()); + assertEquals(pbs, batchWriter.toMutationPbList()); } @Test public void testDeleteAfterPut() throws Exception { - DatastoreV1.Mutation pb = DatastoreV1.Mutation.newBuilder() - .addDelete(KEY1.toPb()) - .build(); + List pbs = new LinkedList<>(); + pbs.add(com.google.datastore.v1beta3.Mutation.newBuilder().setDelete(KEY1.toPb()).build()); batchWriter.put(ENTITY1); batchWriter.delete(KEY1); - assertEquals(pb, batchWriter.toMutationPb().build()); + assertEquals(pbs, batchWriter.toMutationPbList()); } @Test(expected = DatastoreException.class) diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/BaseEntityTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/BaseEntityTest.java index a69ea5e20e3b..bd8bdeebc6da 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/BaseEntityTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/BaseEntityTest.java @@ -35,6 +35,7 @@ public class BaseEntityTest { private static final Blob BLOB = Blob.copyFrom(new byte[]{1, 2}); private static final DateTime DATE_TIME = DateTime.now(); + private static final LatLng LAT_LNG = new LatLng(37.422035, -122.084124); private static final Key KEY = Key.builder("ds1", "k1", "n1").build(); private static final Entity ENTITY = Entity.builder(KEY).set("name", "foo").build(); private static final IncompleteKey INCOMPLETE_KEY = IncompleteKey.builder("ds1", "k1").build(); @@ -62,9 +63,9 @@ public void setUp() { builder = new Builder(); builder.set("blob", BLOB).set("boolean", true).set("dateTime", DATE_TIME); builder.set("double", 1.25).set("key", KEY).set("string", "hello world"); - builder.set("long", 125).setNull("null").set("entity", ENTITY); + builder.set("long", 125).setNull("null").set("entity", ENTITY).set("latLng", LAT_LNG); builder.set("partialEntity", PARTIAL_ENTITY).set("stringValue", StringValue.of("bla")); - builder.set("list1", NullValue.of(), StringValue.of("foo")); + builder.set("list1", NullValue.of(), StringValue.of("foo"), LatLngValue.of(LAT_LNG)); builder.set("list2", ImmutableList.of(LongValue.of(10), DoubleValue.of(2))); builder.set("list3", Collections.singletonList(BooleanValue.of(true))); builder.set( @@ -77,6 +78,7 @@ public void setUp() { builder.set("entityList", ENTITY, PARTIAL_ENTITY); builder.set("stringList", "s1", "s2", "s3"); builder.set("longList", 1, 23, 456); + builder.set("latLngList", LAT_LNG, LAT_LNG); } @Test @@ -159,6 +161,12 @@ public void testGetDateTime() throws Exception { assertEquals(dateTime, entity.getDateTime("dateTime")); } + @Test + public void testGetLatLng() throws Exception { + BaseEntity entity = builder.build(); + assertEquals(LAT_LNG, entity.getLatLng("latLng")); + } + @Test public void testGetKey() throws Exception { BaseEntity entity = builder.build(); @@ -181,9 +189,10 @@ public void testGetEntity() throws Exception { public void testGetList() throws Exception { BaseEntity entity = builder.build(); List> list = entity.getList("list1"); - assertEquals(2, list.size()); + assertEquals(3, list.size()); assertEquals(NullValue.of(), list.get(0)); assertEquals("foo", list.get(1).get()); + assertEquals(LAT_LNG, list.get(2).get()); list = entity.getList("list2"); assertEquals(2, list.size()); assertEquals(Long.valueOf(10), list.get(0).get()); @@ -217,12 +226,13 @@ public void testGetBlob() throws Exception { @Test public void testNames() throws Exception { - Set names = ImmutableSet.builder() - .add("string", "stringValue", "boolean", "double", "long", "list1", "list2", "list3") - .add("entity", "partialEntity", "null", "dateTime", "blob", "key", "blobList") - .add("booleanList", "dateTimeList", "doubleList", "keyList", "entityList", "stringList") - .add("longList") - .build(); + Set names = + ImmutableSet.builder() + .add("string", "stringValue", "boolean", "double", "long", "list1", "list2", "list3") + .add("entity", "partialEntity", "null", "dateTime", "blob", "key", "blobList") + .add("booleanList", "dateTimeList", "doubleList", "keyList", "entityList", "stringList") + .add("longList", "latLng", "latLngList") + .build(); BaseEntity entity = builder.build(); assertEquals(names, entity.names()); } diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/BaseKeyTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/BaseKeyTest.java index 43db4695b191..974231d51c21 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/BaseKeyTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/BaseKeyTest.java @@ -17,7 +17,6 @@ package com.google.gcloud.datastore; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import com.google.common.collect.ImmutableList; @@ -83,7 +82,8 @@ public void testBadDatasetInSetter() throws Exception { public void testNamespace() throws Exception { Builder builder = new Builder("ds", "k"); BaseKey key = builder.build(); - assertNull(key.namespace()); + assertTrue(key.namespace() != null); + assertTrue(key.namespace().isEmpty()); key = builder.namespace("ns").build(); assertEquals("ns", key.namespace()); } diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/BlobValueTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/BlobValueTest.java index 40d0299d8fb3..2a4c0dc956e3 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/BlobValueTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/BlobValueTest.java @@ -37,19 +37,16 @@ public void testToBuilder() throws Exception { public void testOf() throws Exception { BlobValue value = BlobValue.of(CONTENT); assertEquals(CONTENT, value.get()); - assertFalse(value.hasIndexed()); - assertFalse(value.hasMeaning()); + assertFalse(value.excludeFromIndexes()); } @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { BlobValue.Builder builder = BlobValue.builder(CONTENT); - BlobValue value = builder.meaning(1).indexed(false).build(); + BlobValue value = builder.meaning(1).excludeFromIndexes(true).build(); assertEquals(CONTENT, value.get()); - assertTrue(value.hasMeaning()); - assertEquals(Integer.valueOf(1), value.meaning()); - assertTrue(value.hasIndexed()); - assertFalse(value.indexed()); + assertEquals(1, value.meaning()); + assertTrue(value.excludeFromIndexes()); } } diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/BooleanValueTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/BooleanValueTest.java index 16bbe9cbf518..bff3d67c9465 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/BooleanValueTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/BooleanValueTest.java @@ -35,19 +35,16 @@ public void testToBuilder() throws Exception { public void testOf() throws Exception { BooleanValue value = BooleanValue.of(false); assertFalse(value.get()); - assertFalse(value.hasIndexed()); - assertFalse(value.hasMeaning()); + assertFalse(value.excludeFromIndexes()); } @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { BooleanValue.Builder builder = BooleanValue.builder(true); - BooleanValue value = builder.meaning(1).indexed(true).build(); + BooleanValue value = builder.meaning(1).excludeFromIndexes(true).build(); assertTrue(value.get()); - assertTrue(value.hasMeaning()); - assertEquals(Integer.valueOf(1), value.meaning()); - assertTrue(value.hasIndexed()); - assertTrue(value.indexed()); + assertEquals(1, value.meaning()); + assertTrue(value.excludeFromIndexes()); } } diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DatastoreExceptionTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DatastoreExceptionTest.java index f7bdcb89bcec..e5bc50eee046 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DatastoreExceptionTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DatastoreExceptionTest.java @@ -38,29 +38,29 @@ public class DatastoreExceptionTest { @Test public void testDatastoreException() throws Exception { - DatastoreException exception = new DatastoreException(409, "message", "ABORTED"); - assertEquals(409, exception.code()); + DatastoreException exception = new DatastoreException(10, "message", "ABORTED"); + assertEquals(10, exception.code()); assertEquals("ABORTED", exception.reason()); assertEquals("message", exception.getMessage()); assertTrue(exception.retryable()); assertTrue(exception.idempotent()); - exception = new DatastoreException(403, "message", "DEADLINE_EXCEEDED"); - assertEquals(403, exception.code()); + exception = new DatastoreException(4, "message", "DEADLINE_EXCEEDED"); + assertEquals(4, exception.code()); assertEquals("DEADLINE_EXCEEDED", exception.reason()); assertEquals("message", exception.getMessage()); assertTrue(exception.retryable()); assertTrue(exception.idempotent()); - exception = new DatastoreException(503, "message", "UNAVAILABLE"); - assertEquals(503, exception.code()); + exception = new DatastoreException(14, "message", "UNAVAILABLE"); + assertEquals(14, exception.code()); assertEquals("UNAVAILABLE", exception.reason()); assertEquals("message", exception.getMessage()); assertTrue(exception.retryable()); assertTrue(exception.idempotent()); - exception = new DatastoreException(500, "message", "INTERNAL"); - assertEquals(500, exception.code()); + exception = new DatastoreException(2, "message", "INTERNAL"); + assertEquals(2, exception.code()); assertEquals("INTERNAL", exception.reason()); assertEquals("message", exception.getMessage()); assertFalse(exception.retryable()); @@ -77,7 +77,7 @@ public void testDatastoreException() throws Exception { @Test public void testTranslateAndThrow() throws Exception { - DatastoreException cause = new DatastoreException(503, "message", "UNAVAILABLE"); + DatastoreException cause = new DatastoreException(14, "message", "UNAVAILABLE"); RetryHelper.RetryHelperException exceptionMock = createMock(RetryHelper.RetryHelperException.class); expect(exceptionMock.getCause()).andReturn(cause).times(2); @@ -85,7 +85,7 @@ public void testTranslateAndThrow() throws Exception { try { DatastoreException.translateAndThrow(exceptionMock); } catch (BaseServiceException ex) { - assertEquals(503, ex.code()); + assertEquals(14, ex.code()); assertEquals("message", ex.getMessage()); assertTrue(ex.retryable()); assertTrue(ex.idempotent()); diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DatastoreHelperTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DatastoreHelperTest.java index 55c8d0cf3ce6..61b266a9abc2 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DatastoreHelperTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DatastoreHelperTest.java @@ -27,6 +27,7 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterators; import com.google.gcloud.datastore.Datastore.TransactionCallable; @@ -66,52 +67,100 @@ public void testAllocateId() throws Exception { } @Test - public void testGet() throws Exception { + public void testGetWithDatastore() throws Exception { Datastore datastore = createStrictMock(Datastore.class); IncompleteKey pKey1 = IncompleteKey.builder("ds", "k").build(); Key key1 = Key.builder(pKey1, 1).build(); Entity entity1 = Entity.builder(key1).build(); Key key2 = Key.builder(pKey1, 2).build(); - expect(datastore.get(new Key[]{key1})) + ReadOption eventualConsistency = ReadOption.eventualConsistency(); + expect(datastore.get(Collections.singletonList(key1))) .andReturn(Collections.singletonList(entity1).iterator()); - expect(datastore.get(new Key[]{key2})) + expect(datastore.get(Collections.singletonList(key2))) .andReturn(Collections.emptyIterator()); + expect(datastore.get(Collections.singletonList(key1), eventualConsistency)) + .andReturn(Collections.singletonList(entity1).iterator()); replay(datastore); assertEquals(entity1, DatastoreHelper.get(datastore, key1)); assertNull(DatastoreHelper.get(datastore, key2)); + assertEquals(entity1, DatastoreHelper.get(datastore, key1, eventualConsistency)); verify(datastore); } + @Test + public void testGetWithTransaction() throws Exception { + Transaction transaction = createStrictMock(Transaction.class); + IncompleteKey pKey1 = IncompleteKey.builder("ds", "k").build(); + Key key1 = Key.builder(pKey1, 1).build(); + Entity entity1 = Entity.builder(key1).build(); + Key key2 = Key.builder(pKey1, 2).build(); + expect(transaction.get(new Key[] {key1})) + .andReturn(Collections.singletonList(entity1).iterator()); + expect(transaction.get(new Key[] {key2})).andReturn(Collections.emptyIterator()); + replay(transaction); + assertEquals(entity1, DatastoreHelper.get(transaction, key1)); + assertNull(DatastoreHelper.get(transaction, key2)); + verify(transaction); + } + @Test public void testAdd() throws Exception { Datastore datastore = createStrictMock(Datastore.class); IncompleteKey pKey = IncompleteKey.builder("ds", "k").build(); Key key = Key.builder(pKey, 1).build(); Entity entity = Entity.builder(key).build(); - expect(datastore.add(new Entity[]{entity})) - .andReturn(Collections.singletonList(entity)); + expect(datastore.add(new Entity[] {entity})).andReturn(Collections.singletonList(entity)); replay(datastore); assertEquals(entity, DatastoreHelper.add(datastore, entity)); verify(datastore); } @Test - public void testFetch() throws Exception { + public void testFetchWithDatastore() throws Exception { Datastore datastore = createStrictMock(Datastore.class); IncompleteKey pKey1 = IncompleteKey.builder("ds", "k").build(); Key key1 = Key.builder(pKey1, 1).build(); Key key2 = Key.builder(pKey1, "a").build(); Entity entity1 = Entity.builder(key1).build(); Entity entity2 = Entity.builder(key2).build(); - expect(datastore.get(key1, key2)).andReturn(Iterators.forArray(entity1, entity2)).once(); + ReadOption eventualConsistency = ReadOption.eventualConsistency(); + expect(datastore.get(ImmutableList.of(key1, key2))) + .andReturn(Iterators.forArray(entity1, entity2)) + .once(); + expect(datastore.get(ImmutableList.of(key1, key2), eventualConsistency)) + .andReturn(Iterators.forArray(entity1, entity2)) + .once(); replay(datastore); - List values = DatastoreHelper.fetch(datastore, key1, key2); + List values = DatastoreHelper.fetch(datastore, new Key[] {key1, key2}); + assertEquals(2, values.size()); + assertEquals(entity1, values.get(0)); + assertEquals(entity2, values.get(1)); + values = DatastoreHelper.fetch(datastore, new Key[] {key1, key2}, eventualConsistency); assertEquals(2, values.size()); assertEquals(entity1, values.get(0)); assertEquals(entity2, values.get(1)); verify(datastore); } + @Test + public void testFetchWithTransaction() throws Exception { + Transaction transaction = createStrictMock(Transaction.class); + IncompleteKey pKey1 = IncompleteKey.builder("ds", "k").build(); + Key key1 = Key.builder(pKey1, 1).build(); + Key key2 = Key.builder(pKey1, "a").build(); + Entity entity1 = Entity.builder(key1).build(); + Entity entity2 = Entity.builder(key2).build(); + expect(transaction.get(new Key[] {key1, key2})) + .andReturn(Iterators.forArray(entity1, entity2)) + .once(); + replay(transaction); + List values = DatastoreHelper.fetch(transaction, new Key[] {key1, key2}); + assertEquals(2, values.size()); + assertEquals(entity1, values.get(0)); + assertEquals(entity2, values.get(1)); + verify(transaction); + } + @Test public void testRunInTransaction() throws Exception { final Datastore datastore = createStrictMock(Datastore.class); diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DatastoreOptionsTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DatastoreOptionsTest.java index 1d188c7f4e94..5b77c035a714 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DatastoreOptionsTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DatastoreOptionsTest.java @@ -17,8 +17,6 @@ package com.google.gcloud.datastore; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; @@ -65,16 +63,10 @@ public void testHost() throws Exception { @Test public void testNamespace() throws Exception { - assertNull(options.build().namespace()); + assertTrue(options.build().namespace().isEmpty()); assertEquals("ns1", options.namespace("ns1").build().namespace()); } - @Test - public void testForce() throws Exception { - assertFalse(options.build().force()); - assertTrue(options.force(true).build().force()); - } - @Test public void testDatastore() throws Exception { assertSame(datastoreRpc, options.build().rpc()); @@ -82,12 +74,11 @@ public void testDatastore() throws Exception { @Test public void testToBuilder() throws Exception { - DatastoreOptions original = options.namespace("ns1").force(true).build(); + DatastoreOptions original = options.namespace("ns1").build(); DatastoreOptions copy = original.toBuilder().build(); assertEquals(original.projectId(), copy.projectId()); assertEquals(original.namespace(), copy.namespace()); assertEquals(original.host(), copy.host()); - assertEquals(original.force(), copy.force()); assertEquals(original.retryParams(), copy.retryParams()); assertEquals(original.authCredentials(), copy.authCredentials()); } diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DatastoreTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DatastoreTest.java index e3829a2e71ce..7819c9d689a8 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DatastoreTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DatastoreTest.java @@ -25,18 +25,22 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import com.google.api.services.datastore.DatastoreV1; -import com.google.api.services.datastore.DatastoreV1.EntityResult; -import com.google.api.services.datastore.DatastoreV1.QueryResultBatch; -import com.google.api.services.datastore.DatastoreV1.RunQueryRequest; -import com.google.api.services.datastore.DatastoreV1.RunQueryResponse; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; +import com.google.datastore.v1beta3.EntityResult; +import com.google.datastore.v1beta3.LookupRequest; +import com.google.datastore.v1beta3.LookupResponse; +import com.google.datastore.v1beta3.PartitionId; +import com.google.datastore.v1beta3.QueryResultBatch; +import com.google.datastore.v1beta3.ReadOptions; +import com.google.datastore.v1beta3.ReadOptions.ReadConsistency; +import com.google.datastore.v1beta3.RunQueryRequest; +import com.google.datastore.v1beta3.RunQueryResponse; import com.google.gcloud.AuthCredentials; import com.google.gcloud.RetryParams; import com.google.gcloud.datastore.Query.ResultType; import com.google.gcloud.datastore.StructuredQuery.OrderBy; -import com.google.gcloud.datastore.StructuredQuery.Projection; import com.google.gcloud.datastore.StructuredQuery.PropertyFilter; import com.google.gcloud.datastore.spi.DatastoreRpc; import com.google.gcloud.datastore.spi.DatastoreRpcFactory; @@ -70,7 +74,8 @@ public class DatastoreTest { private static final String KIND3 = "kind3"; private static final NullValue NULL_VALUE = NullValue.of(); private static final StringValue STR_VALUE = StringValue.of("str"); - private static final BooleanValue BOOL_VALUE = BooleanValue.builder(false).indexed(false).build(); + private static final BooleanValue BOOL_VALUE = BooleanValue.builder(false) + .excludeFromIndexes(true).build(); private static final IncompleteKey INCOMPLETE_KEY1 = IncompleteKey.builder(PROJECT_ID, KIND1).build(); private static final IncompleteKey INCOMPLETE_KEY2 = @@ -87,6 +92,8 @@ public class DatastoreTest { .build(); private static final ListValue LIST_VALUE2 = ListValue.of(Collections.singletonList(KEY_VALUE)); private static final DateTimeValue DATE_TIME_VALUE = new DateTimeValue(DateTime.now()); + private static final LatLngValue LAT_LNG_VALUE = + new LatLngValue(new LatLng(37.422035, -122.084124)); private static final FullEntity PARTIAL_ENTITY1 = FullEntity.builder(INCOMPLETE_KEY2).set("str", STR_VALUE).set("bool", BOOL_VALUE) .set("list", LIST_VALUE1).build(); @@ -99,6 +106,7 @@ public class DatastoreTest { private static final Entity ENTITY1 = Entity.builder(KEY1) .set("str", STR_VALUE) .set("date", DATE_TIME_VALUE) + .set("latLng", LAT_LNG_VALUE) .set("bool", BOOL_VALUE) .set("partial1", EntityValue.of(PARTIAL_ENTITY1)) .set("list", LIST_VALUE2) @@ -109,7 +117,10 @@ public class DatastoreTest { .set("null", NULL_VALUE).set("partial1", PARTIAL_ENTITY2).set("partial2", ENTITY2).build(); private DatastoreOptions options; + private DatastoreOptions rpcMockOptions; private Datastore datastore; + private DatastoreRpcFactory rpcFactoryMock; + private DatastoreRpc rpcMock; private static LocalGcdHelper gcdHelper; private static final int PORT = LocalGcdHelper.findAvailablePort(LocalGcdHelper.DEFAULT_PORT); @@ -128,11 +139,19 @@ public static void beforeClass() throws IOException, InterruptedException { public void setUp() { options = DatastoreOptions.builder() .projectId(PROJECT_ID) - .host("http://localhost:" + PORT) + .host("localhost:" + PORT) .authCredentials(AuthCredentials.noAuth()) .retryParams(RetryParams.noRetries()) .build(); datastore = options.service(); + rpcFactoryMock = EasyMock.createStrictMock(DatastoreRpcFactory.class); + rpcMock = EasyMock.createStrictMock(DatastoreRpc.class); + rpcMockOptions = options + .toBuilder() + .retryParams(RetryParams.defaultInstance()) + .serviceRpcFactory(rpcFactoryMock) + .build(); + EasyMock.expect(rpcFactoryMock.create(rpcMockOptions)).andReturn(rpcMock); StructuredQuery query = Query.keyQueryBuilder().build(); QueryResults result = datastore.run(query); datastore.delete(Iterators.toArray(result, Key.class)); @@ -423,6 +442,26 @@ public void testRunGqlQueryWithCasting() { assertFalse(results3.hasNext()); } + @Test + public void testGqlQueryPagination() throws DatastoreException { + List responses = buildResponsesForQueryPagination(); + for (int i = 0; i < responses.size(); i++) { + EasyMock.expect(rpcMock.runQuery(EasyMock.anyObject(RunQueryRequest.class))) + .andReturn(responses.get(i)); + } + EasyMock.replay(rpcFactoryMock, rpcMock); + Datastore mockDatastore = rpcMockOptions.service(); + QueryResults results = + mockDatastore.run(Query.gqlQueryBuilder(ResultType.KEY, "select __key__ from *").build()); + int count = 0; + while (results.hasNext()) { + count += 1; + results.next(); + } + assertEquals(count, 5); + EasyMock.verify(rpcFactoryMock, rpcMock); + } + @Test public void testRunStructuredQuery() { Query query = @@ -440,7 +479,7 @@ public void testRunStructuredQuery() { StructuredQuery keyOnlyProjectionQuery = Query.projectionEntityQueryBuilder() - .kind(KIND1).projection(Projection.property("__key__")).build(); + .kind(KIND1).projection("__key__").build(); QueryResults results3 = datastore.run(keyOnlyProjectionQuery); assertTrue(results3.hasNext()); ProjectionEntity projectionEntity = results3.next(); @@ -450,9 +489,9 @@ public void testRunStructuredQuery() { StructuredQuery projectionQuery = Query.projectionEntityQueryBuilder() .kind(KIND2) - .projection(Projection.property("age"), Projection.first("name")) + .projection("age") .filter(PropertyFilter.gt("age", 18)) - .groupBy("age") + .distinctOn("age") .orderBy(OrderBy.asc("age")) .limit(10) .build(); @@ -462,17 +501,68 @@ public void testRunStructuredQuery() { ProjectionEntity entity = results4.next(); assertEquals(ENTITY2.key(), entity.key()); assertEquals(20, entity.getLong("age")); - assertEquals("Dan", entity.getString("name")); - assertEquals(2, entity.properties().size()); + assertEquals(1, entity.properties().size()); assertFalse(results4.hasNext()); } @Test + public void testStructuredQueryPagination() throws DatastoreException { + List responses = buildResponsesForQueryPagination(); + for (int i = 0; i < responses.size(); i++) { + EasyMock.expect(rpcMock.runQuery(EasyMock.anyObject(RunQueryRequest.class))) + .andReturn(responses.get(i)); + } + EasyMock.replay(rpcFactoryMock, rpcMock); + Datastore datastore = rpcMockOptions.service(); + QueryResults results = datastore.run(Query.keyQueryBuilder().build()); + int count = 0; + while (results.hasNext()) { + count += 1; + results.next(); + } + assertEquals(count, 5); + EasyMock.verify(rpcFactoryMock, rpcMock); + } + + private List buildResponsesForQueryPagination() { + Entity entity4 = Entity.builder(KEY4).set("value", StringValue.of("value")).build(); + Entity entity5 = Entity.builder(KEY5).set("value", "value").build(); + datastore.add(ENTITY3, entity4, entity5); + List responses = new ArrayList<>(); + Query query = Query.keyQueryBuilder().build(); + RunQueryRequest.Builder requestPb = RunQueryRequest.newBuilder(); + query.populatePb(requestPb); + QueryResultBatch queryResultBatchPb = RunQueryResponse.newBuilder() + .mergeFrom(((DatastoreImpl) datastore).runQuery(requestPb.build())) + .getBatch(); + QueryResultBatch queryResultBatchPb1 = QueryResultBatch.newBuilder() + .mergeFrom(queryResultBatchPb) + .setMoreResults(QueryResultBatch.MoreResultsType.NOT_FINISHED) + .clearEntityResults() + .addAllEntityResults(queryResultBatchPb.getEntityResultsList().subList(0, 1)) + .setEndCursor(queryResultBatchPb.getEntityResultsList().get(0).getCursor()) + .build(); + responses.add(RunQueryResponse.newBuilder().setBatch(queryResultBatchPb1).build()); + QueryResultBatch queryResultBatchPb2 = QueryResultBatch.newBuilder() + .mergeFrom(queryResultBatchPb) + .setMoreResults(QueryResultBatch.MoreResultsType.NOT_FINISHED) + .clearEntityResults() + .addAllEntityResults(queryResultBatchPb.getEntityResultsList().subList(1, 3)) + .setEndCursor(queryResultBatchPb.getEntityResultsList().get(2).getCursor()) + .build(); + responses.add(RunQueryResponse.newBuilder().setBatch(queryResultBatchPb2).build()); + QueryResultBatch queryResultBatchPb3 = QueryResultBatch.newBuilder() + .mergeFrom(queryResultBatchPb) + .setMoreResults(QueryResultBatch.MoreResultsType.NO_MORE_RESULTS) + .clearEntityResults() + .addAllEntityResults(queryResultBatchPb.getEntityResultsList().subList(3, 5)) + .setEndCursor(queryResultBatchPb.getEntityResultsList().get(4).getCursor()) + .build(); + responses.add(RunQueryResponse.newBuilder().setBatch(queryResultBatchPb3).build()); + return responses; + } + public void testQueryPaginationWithLimit() throws DatastoreException { - DatastoreRpcFactory rpcFactoryMock = EasyMock.createStrictMock(DatastoreRpcFactory.class); - DatastoreRpc rpcMock = EasyMock.createStrictMock(DatastoreRpc.class); - EasyMock.expect(rpcFactoryMock.create(EasyMock.anyObject(DatastoreOptions.class))) - .andReturn(rpcMock); List responses = buildResponsesForQueryPaginationWithLimit(); List endCursors = Lists.newArrayListWithCapacity(responses.size()); for (RunQueryResponse response : responses) { @@ -483,17 +573,13 @@ public void testQueryPaginationWithLimit() throws DatastoreException { } } EasyMock.replay(rpcFactoryMock, rpcMock); - Datastore mockDatastore = options.toBuilder() - .retryParams(RetryParams.defaultInstance()) - .serviceRpcFactory(rpcFactoryMock) - .build() - .service(); + Datastore datastore = rpcMockOptions.service(); int limit = 2; int totalCount = 0; Iterator cursorIter = endCursors.iterator(); StructuredQuery query = Query.entityQueryBuilder().limit(limit).build(); while (true) { - QueryResults results = mockDatastore.run(query); + QueryResults results = datastore.run(query); int resultCount = 0; while (results.hasNext()) { results.next(); @@ -527,16 +613,16 @@ private List buildResponsesForQueryPaginationWithLimit() { QueryResultBatch queryResultBatchPb1 = QueryResultBatch.newBuilder() .mergeFrom(queryResultBatchPb) .setMoreResults(QueryResultBatch.MoreResultsType.NOT_FINISHED) - .clearEntityResult() - .addAllEntityResult(queryResultBatchPb.getEntityResultList().subList(0, 1)) + .clearEntityResults() + .addAllEntityResults(queryResultBatchPb.getEntityResultsList().subList(0, 1)) .setEndCursor(ByteString.copyFromUtf8("a")) .build(); responses.add(RunQueryResponse.newBuilder().setBatch(queryResultBatchPb1).build()); QueryResultBatch queryResultBatchPb2 = QueryResultBatch.newBuilder() .mergeFrom(queryResultBatchPb) .setMoreResults(QueryResultBatch.MoreResultsType.MORE_RESULTS_AFTER_LIMIT) - .clearEntityResult() - .addAllEntityResult(queryResultBatchPb.getEntityResultList().subList(1, 2)) + .clearEntityResults() + .addAllEntityResults(queryResultBatchPb.getEntityResultsList().subList(1, 2)) .setEndCursor( ByteString.copyFrom(new byte[] {(byte) 0x80})) // test invalid UTF-8 string .build(); @@ -544,22 +630,43 @@ private List buildResponsesForQueryPaginationWithLimit() { QueryResultBatch queryResultBatchPb3 = QueryResultBatch.newBuilder() .mergeFrom(queryResultBatchPb) .setMoreResults(QueryResultBatch.MoreResultsType.MORE_RESULTS_AFTER_LIMIT) - .clearEntityResult() - .addAllEntityResult(queryResultBatchPb.getEntityResultList().subList(2, 4)) + .clearEntityResults() + .addAllEntityResults(queryResultBatchPb.getEntityResultsList().subList(2, 4)) .setEndCursor(ByteString.copyFromUtf8("b")) .build(); responses.add(RunQueryResponse.newBuilder().setBatch(queryResultBatchPb3).build()); QueryResultBatch queryResultBatchPb4 = QueryResultBatch.newBuilder() .mergeFrom(queryResultBatchPb) .setMoreResults(QueryResultBatch.MoreResultsType.NO_MORE_RESULTS) - .clearEntityResult() - .addAllEntityResult(queryResultBatchPb.getEntityResultList().subList(4, 5)) + .clearEntityResults() + .addAllEntityResults(queryResultBatchPb.getEntityResultsList().subList(4, 5)) .setEndCursor(ByteString.copyFromUtf8("c")) .build(); responses.add(RunQueryResponse.newBuilder().setBatch(queryResultBatchPb4).build()); return responses; } + @Test + public void testEventualConsistencyQuery() { + ReadOptions readOption = + ReadOptions.newBuilder().setReadConsistencyValue(ReadConsistency.EVENTUAL_VALUE).build(); + com.google.datastore.v1beta3.GqlQuery query = com.google.datastore.v1beta3.GqlQuery.newBuilder() + .setQueryString("FROM * SELECT *") + .build(); + RunQueryRequest.Builder expectedRequest = RunQueryRequest.newBuilder() + .setReadOptions(readOption) + .setGqlQuery(query) + .setPartitionId(PartitionId.newBuilder().setProjectId(PROJECT_ID) + .build()); + EasyMock.expect(rpcMock.runQuery(expectedRequest.build())) + .andReturn(RunQueryResponse.newBuilder().build()); + EasyMock.replay(rpcFactoryMock, rpcMock); + Datastore datastore = rpcMockOptions.service(); + datastore.run( + Query.gqlQueryBuilder("FROM * SELECT *").build(), ReadOption.eventualConsistency()); + EasyMock.verify(rpcFactoryMock, rpcMock); + } + @Test public void testToUrlSafe() { byte[][] invalidUtf8 = @@ -627,12 +734,36 @@ public void testGet() { assertEquals(LIST_VALUE2, value3); DateTimeValue value4 = entity.getValue("date"); assertEquals(DATE_TIME_VALUE, value4); - FullEntity value5 = entity.getEntity("partial1"); - assertEquals(PARTIAL_ENTITY1, value5); - assertEquals(5, entity.names().size()); + LatLngValue value5 = entity.getValue("latLng"); + assertEquals(LAT_LNG_VALUE, value5); + FullEntity value6 = entity.getEntity("partial1"); + assertEquals(PARTIAL_ENTITY1, value6); + assertEquals(6, entity.names().size()); assertFalse(entity.contains("bla")); } + @Test + public void testLookupEventualConsistency() { + ReadOptions readOption = + ReadOptions.newBuilder().setReadConsistencyValue(ReadConsistency.EVENTUAL_VALUE).build(); + com.google.datastore.v1beta3.Key key = com.google.datastore.v1beta3.Key.newBuilder() + .setPartitionId(PartitionId.newBuilder().setProjectId(PROJECT_ID).build()) + .addPath(com.google.datastore.v1beta3.Key.PathElement.newBuilder() + .setKind("kind1").setName("name").build()) + .build(); + LookupRequest lookupRequest = + LookupRequest.newBuilder().setReadOptions(readOption).addKeys(key).build(); + EasyMock.expect(rpcMock.lookup(lookupRequest)) + .andReturn(LookupResponse.newBuilder().build()) + .times(3); + EasyMock.replay(rpcFactoryMock, rpcMock); + Datastore datastore = rpcMockOptions.service(); + datastore.get(KEY1, ReadOption.eventualConsistency()); + datastore.get(ImmutableList.of(KEY1), ReadOption.eventualConsistency()); + datastore.fetch(ImmutableList.of(KEY1), ReadOption.eventualConsistency()); + EasyMock.verify(rpcFactoryMock, rpcMock); + } + @Test public void testGetArrayNoDeferredResults() { datastore.put(ENTITY3); @@ -651,7 +782,8 @@ public void testGetArrayNoDeferredResults() { assertEquals(PARTIAL_ENTITY2, partial1); assertEquals(ENTITY2, partial2); assertEquals(ValueType.BOOLEAN, entity3.getValue("bool").type()); - assertEquals(6, entity3.names().size()); + assertEquals(LAT_LNG_VALUE, entity3.getValue("latLng")); + assertEquals(7, entity3.names().size()); assertFalse(entity3.contains("bla")); try { entity3.getString("str"); @@ -689,26 +821,26 @@ public void testFetchArrayDeferredResults() throws DatastoreException { } private Datastore createDatastoreForDeferredLookup() throws DatastoreException { - List keysPb = new ArrayList<>(); + List keysPb = new ArrayList<>(); keysPb.add(KEY1.toPb()); keysPb.add(KEY2.toPb()); keysPb.add(KEY3.toPb()); keysPb.add(KEY4.toPb()); keysPb.add(KEY5.toPb()); - List lookupRequests = new ArrayList<>(); - lookupRequests.add(DatastoreV1.LookupRequest.newBuilder().addAllKey(keysPb).build()); + List lookupRequests = new ArrayList<>(); + lookupRequests.add(LookupRequest.newBuilder().addAllKeys(keysPb).build()); lookupRequests.add( - DatastoreV1.LookupRequest.newBuilder() - .addKey(keysPb.get(2)) - .addKey(keysPb.get(3)) - .addKey(keysPb.get(5)) + LookupRequest.newBuilder() + .addKeys(keysPb.get(2)) + .addKeys(keysPb.get(3)) + .addKeys(keysPb.get(5)) .build()); - lookupRequests.add(DatastoreV1.LookupRequest.newBuilder().addKey(keysPb.get(5)).build()); + lookupRequests.add(LookupRequest.newBuilder().addKeys(keysPb.get(5)).build()); Entity entity4 = Entity.builder(KEY4).set("value", StringValue.of("value")).build(); Entity entity5 = Entity.builder(KEY5).set("value", "value").build(); - List lookupResponses = new ArrayList<>(); + List lookupResponses = new ArrayList<>(); lookupResponses.add( - DatastoreV1.LookupResponse.newBuilder() + LookupResponse.newBuilder() .addFound(EntityResult.newBuilder().setEntity(ENTITY1.toPb())) .addFound(EntityResult.newBuilder().setEntity(entity4.toPb())) .addDeferred(keysPb.get(2)) @@ -716,29 +848,20 @@ private Datastore createDatastoreForDeferredLookup() throws DatastoreException { .addDeferred(keysPb.get(5)) .build()); lookupResponses.add( - DatastoreV1.LookupResponse.newBuilder() + LookupResponse.newBuilder() .addFound(EntityResult.newBuilder().setEntity(ENTITY3.toPb())) .addFound(EntityResult.newBuilder().setEntity(entity4.toPb())) .addDeferred(keysPb.get(5)) .build()); lookupResponses.add( - DatastoreV1.LookupResponse.newBuilder() + LookupResponse.newBuilder() .addFound(EntityResult.newBuilder().setEntity(entity5.toPb())) .build()); - DatastoreRpcFactory rpcFactoryMock = EasyMock.createStrictMock(DatastoreRpcFactory.class); - DatastoreRpc rpcMock = EasyMock.createStrictMock(DatastoreRpc.class); - EasyMock.expect(rpcFactoryMock.create(EasyMock.anyObject(DatastoreOptions.class))) - .andReturn(rpcMock); for (int i = 0; i < lookupRequests.size(); i++) { EasyMock.expect(rpcMock.lookup(lookupRequests.get(i))).andReturn(lookupResponses.get(i)); } EasyMock.replay(rpcFactoryMock, rpcMock); - DatastoreOptions options = - this.options.toBuilder() - .retryParams(RetryParams.defaultInstance()) - .serviceRpcFactory(rpcFactoryMock) - .build(); - return options.service(); + return rpcMockOptions.service(); } @Test @@ -766,7 +889,6 @@ public void testAddEntity() { assertNotNull(datastore.get(entities.get(2).key())); } - @Test public void testUpdate() { List keys = datastore.fetch(ENTITY1.key(), ENTITY3.key()); @@ -835,23 +957,15 @@ public void testKeyFactory() { @Test public void testRetryableException() throws Exception { - DatastoreV1.LookupRequest requestPb = - DatastoreV1.LookupRequest.newBuilder().addKey(KEY1.toPb()).build(); - DatastoreV1.LookupResponse responsePb = DatastoreV1.LookupResponse.newBuilder() - .addFound(EntityResult.newBuilder().setEntity(ENTITY1.toPb())).build(); - DatastoreRpcFactory rpcFactoryMock = EasyMock.createStrictMock(DatastoreRpcFactory.class); - DatastoreRpc rpcMock = EasyMock.createStrictMock(DatastoreRpc.class); - EasyMock.expect(rpcFactoryMock.create(EasyMock.anyObject(DatastoreOptions.class))) - .andReturn(rpcMock); + LookupRequest requestPb = LookupRequest.newBuilder().addKeys(KEY1.toPb()).build(); + LookupResponse responsePb = LookupResponse.newBuilder() + .addFound(EntityResult.newBuilder().setEntity(ENTITY1.toPb())) + .build(); EasyMock.expect(rpcMock.lookup(requestPb)) - .andThrow(new DatastoreException(503, "UNAVAILABLE", "UNAVAILABLE", null)) + .andThrow(new DatastoreException(14, "UNAVAILABLE", "UNAVAILABLE", null)) .andReturn(responsePb); EasyMock.replay(rpcFactoryMock, rpcMock); - DatastoreOptions options = this.options.toBuilder() - .retryParams(RetryParams.defaultInstance()) - .serviceRpcFactory(rpcFactoryMock) - .build(); - Datastore datastore = options.service(); + Datastore datastore = rpcMockOptions.service(); Entity entity = datastore.get(KEY1); assertEquals(ENTITY1, entity); EasyMock.verify(rpcFactoryMock, rpcMock); @@ -859,23 +973,13 @@ public void testRetryableException() throws Exception { @Test public void testNonRetryableException() throws Exception { - DatastoreV1.LookupRequest requestPb = - DatastoreV1.LookupRequest.newBuilder().addKey(KEY1.toPb()).build(); - DatastoreRpcFactory rpcFactoryMock = EasyMock.createStrictMock(DatastoreRpcFactory.class); - DatastoreRpc rpcMock = EasyMock.createStrictMock(DatastoreRpc.class); - EasyMock.expect(rpcFactoryMock.create(EasyMock.anyObject(DatastoreOptions.class))) - .andReturn(rpcMock); + LookupRequest requestPb = LookupRequest.newBuilder().addKeys(KEY1.toPb()).build(); EasyMock.expect(rpcMock.lookup(requestPb)) .andThrow( new DatastoreException(DatastoreException.UNKNOWN_CODE, "denied", "PERMISSION_DENIED")) .times(1); EasyMock.replay(rpcFactoryMock, rpcMock); - RetryParams retryParams = RetryParams.builder().retryMinAttempts(2).build(); - DatastoreOptions options = this.options.toBuilder() - .retryParams(retryParams) - .serviceRpcFactory(rpcFactoryMock) - .build(); - Datastore datastore = options.service(); + Datastore datastore = rpcMockOptions.service(); thrown.expect(DatastoreException.class); thrown.expectMessage("denied"); datastore.get(KEY1); @@ -884,21 +988,11 @@ public void testNonRetryableException() throws Exception { @Test public void testRuntimeException() throws Exception { - DatastoreV1.LookupRequest requestPb = - DatastoreV1.LookupRequest.newBuilder().addKey(KEY1.toPb()).build(); - DatastoreRpcFactory rpcFactoryMock = EasyMock.createStrictMock(DatastoreRpcFactory.class); - DatastoreRpc rpcMock = EasyMock.createStrictMock(DatastoreRpc.class); - EasyMock.expect(rpcFactoryMock.create(EasyMock.anyObject(DatastoreOptions.class))) - .andReturn(rpcMock); + LookupRequest requestPb = LookupRequest.newBuilder().addKeys(KEY1.toPb()).build(); String exceptionMessage = "Artificial runtime exception"; - EasyMock.expect(rpcMock.lookup(requestPb)) - .andThrow(new RuntimeException(exceptionMessage)); + EasyMock.expect(rpcMock.lookup(requestPb)).andThrow(new RuntimeException(exceptionMessage)); EasyMock.replay(rpcFactoryMock, rpcMock); - DatastoreOptions options = this.options.toBuilder() - .retryParams(RetryParams.defaultInstance()) - .serviceRpcFactory(rpcFactoryMock) - .build(); - Datastore datastore = options.service(); + Datastore datastore = rpcMockOptions.service(); thrown.expect(DatastoreException.class); thrown.expectMessage(exceptionMessage); datastore.get(KEY1); diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DateTimeValueTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DateTimeValueTest.java index d7fef2ca69b9..c90e8c88ba52 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DateTimeValueTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DateTimeValueTest.java @@ -37,19 +37,16 @@ public void testToBuilder() throws Exception { public void testOf() throws Exception { DateTimeValue value = DateTimeValue.of(CONTENT); assertEquals(CONTENT, value.get()); - assertFalse(value.hasIndexed()); - assertFalse(value.hasMeaning()); + assertFalse(value.excludeFromIndexes()); } @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { DateTimeValue.Builder builder = DateTimeValue.builder(CONTENT); - DateTimeValue value = builder.meaning(1).indexed(false).build(); + DateTimeValue value = builder.meaning(1).excludeFromIndexes(true).build(); assertEquals(CONTENT, value.get()); - assertTrue(value.hasMeaning()); - assertEquals(Integer.valueOf(1), value.meaning()); - assertTrue(value.hasIndexed()); - assertFalse(value.indexed()); + assertEquals(1, value.meaning()); + assertTrue(value.excludeFromIndexes()); } } diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DoubleValueTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DoubleValueTest.java index fa39511a45de..24d9113ce873 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DoubleValueTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/DoubleValueTest.java @@ -37,19 +37,16 @@ public void testToBuilder() throws Exception { public void testOf() throws Exception { DoubleValue value = DoubleValue.of(CONTENT); assertEquals(CONTENT, value.get()); - assertFalse(value.hasIndexed()); - assertFalse(value.hasMeaning()); + assertFalse(value.excludeFromIndexes()); } @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { DoubleValue.Builder builder = DoubleValue.builder(CONTENT); - DoubleValue value = builder.meaning(1).indexed(false).build(); + DoubleValue value = builder.meaning(1).excludeFromIndexes(true).build(); assertEquals(CONTENT, value.get()); - assertTrue(value.hasMeaning()); - assertEquals(Integer.valueOf(1), value.meaning()); - assertTrue(value.hasIndexed()); - assertFalse(value.indexed()); + assertEquals(1, value.meaning()); + assertTrue(value.excludeFromIndexes()); } } diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/EntityValueTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/EntityValueTest.java index cd1f7af38067..e7df91ac0016 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/EntityValueTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/EntityValueTest.java @@ -38,25 +38,16 @@ public void testToBuilder() throws Exception { public void testOf() throws Exception { EntityValue value = EntityValue.of(CONTENT); assertEquals(CONTENT, value.get()); - assertTrue(value.hasIndexed()); - assertFalse(value.indexed()); - assertFalse(value.hasMeaning()); - } - - @Test(expected = IllegalArgumentException.class) - public void testIndexedNotAllowed() { - EntityValue.builder(CONTENT).indexed(true); + assertFalse(value.excludeFromIndexes()); } @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { EntityValue.Builder builder = EntityValue.builder(CONTENT); - EntityValue value = builder.meaning(1).indexed(false).build(); + EntityValue value = builder.meaning(1).excludeFromIndexes(true).build(); assertEquals(CONTENT, value.get()); - assertTrue(value.hasMeaning()); - assertEquals(Integer.valueOf(1), value.meaning()); - assertTrue(value.hasIndexed()); - assertFalse(value.indexed()); + assertEquals(1, value.meaning()); + assertTrue(value.excludeFromIndexes()); } } diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/KeyFactoryTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/KeyFactoryTest.java index 92851bd87efe..dacb348c2172 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/KeyFactoryTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/KeyFactoryTest.java @@ -17,7 +17,6 @@ package com.google.gcloud.datastore; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Before; @@ -55,7 +54,7 @@ public void testReset() { key = keyFactory.newKey(); assertEquals("k1", key.kind()); assertEquals(PROJECT_ID, key.projectId()); - assertNull(key.namespace()); + assertTrue(key.namespace().isEmpty()); assertTrue(key.ancestors().isEmpty()); keyFactory = new KeyFactory(PROJECT_ID, "ns1").kind("k"); @@ -75,9 +74,9 @@ public void testReset() { @Test public void testNewKey() throws Exception { Key key = keyFactory.newKey(1); - verifyKey(key, 1L, null); + verifyKey(key, 1L, ""); key = keyFactory.newKey("n"); - verifyKey(key, "n", null); + verifyKey(key, "n", ""); PathElement p1 = PathElement.of("k1", "n"); PathElement p2 = PathElement.of("k2", 10); key = keyFactory.namespace("ns").ancestors(p1, p2).newKey("k3"); @@ -87,7 +86,7 @@ public void testNewKey() throws Exception { @Test public void testNewIncompleteKey() throws Exception { IncompleteKey key = keyFactory.newKey(); - verifyIncompleteKey(key, null); + verifyIncompleteKey(key, ""); PathElement p1 = PathElement.of("k1", "n"); PathElement p2 = PathElement.of("k2", 10); key = keyFactory.namespace("ns").ancestors(p1, p2).newKey(); diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/KeyValueTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/KeyValueTest.java index 131a80462a62..b2e916983b8a 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/KeyValueTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/KeyValueTest.java @@ -37,19 +37,16 @@ public void testToBuilder() throws Exception { public void testOf() throws Exception { KeyValue value = KeyValue.of(CONTENT); assertEquals(CONTENT, value.get()); - assertFalse(value.hasIndexed()); - assertFalse(value.hasMeaning()); + assertFalse(value.excludeFromIndexes()); } @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { KeyValue.Builder builder = KeyValue.builder(CONTENT); - KeyValue value = builder.meaning(1).indexed(false).build(); + KeyValue value = builder.meaning(1).excludeFromIndexes(true).build(); assertEquals(CONTENT, value.get()); - assertTrue(value.hasMeaning()); - assertEquals(Integer.valueOf(1), value.meaning()); - assertTrue(value.hasIndexed()); - assertFalse(value.indexed()); + assertEquals(1, value.meaning()); + assertTrue(value.excludeFromIndexes()); } } diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/LatLngTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/LatLngTest.java new file mode 100644 index 000000000000..1955ec236300 --- /dev/null +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/LatLngTest.java @@ -0,0 +1,77 @@ +/* + * Copyright 2015 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.gcloud.datastore; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +public class LatLngTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private static LatLng gp1 = new LatLng(37.422035, -122.084124); + private static LatLng gp2 = new LatLng(0.0, 0.0); + + private static final String INVALID_LAT_MESSAGE = + "latitude must be in the range [-90, 90] degrees"; + private static final String INVALID_LNG_MESSAGE = + "latitude must be in the range [-180, 180] degrees"; + + @Test + public void testEquals() { + assertEquals(gp1, gp1); + assertNotEquals(gp1, gp2); + } + + @Test + public void testUpperLatRange() { + new LatLng(90, 0); + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage(INVALID_LAT_MESSAGE); + new LatLng(91, 0); + } + + @Test + public void testLowerLatRange() { + new LatLng(-90, 0); + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage(INVALID_LAT_MESSAGE); + new LatLng(-91, 0); + } + + @Test + public void testUpperLngRange() { + new LatLng(0, 180); + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage(INVALID_LNG_MESSAGE); + new LatLng(0, 181); + } + + @Test + public void testLowerLngRange() { + new LatLng(0, 180); + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage(INVALID_LNG_MESSAGE); + new LatLng(0, -181); + } +} + diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/LatLngValueTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/LatLngValueTest.java new file mode 100644 index 000000000000..3a25078237d4 --- /dev/null +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/LatLngValueTest.java @@ -0,0 +1,52 @@ +/* + * Copyright 2015 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.gcloud.datastore; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class LatLngValueTest { + +private static final LatLng CONTENT = new LatLng(37.4, -122.1); + + @Test + public void testToBuilder() throws Exception { + LatLngValue value = LatLngValue.of(CONTENT); + assertEquals(value, value.toBuilder().build()); + } + + @SuppressWarnings("deprecation") + @Test + public void testOf() throws Exception { + LatLngValue value = LatLngValue.of(CONTENT); + assertEquals(CONTENT, value.get()); + assertFalse(value.excludeFromIndexes()); + } + + @SuppressWarnings("deprecation") + @Test + public void testBuilder() throws Exception { + LatLngValue.Builder builder = LatLngValue.builder(CONTENT); + LatLngValue value = builder.meaning(1).excludeFromIndexes(true).build(); + assertEquals(CONTENT, value.get()); + assertEquals(1, value.meaning()); + assertTrue(value.excludeFromIndexes()); + } +} diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/ListValueTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/ListValueTest.java index 7af82c29901d..6245c715d476 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/ListValueTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/ListValueTest.java @@ -42,24 +42,17 @@ public void testToBuilder() throws Exception { public void testOf() throws Exception { ListValue value = ListValue.of(CONTENT); assertEquals(CONTENT, value.get()); - assertFalse(value.hasIndexed()); - assertFalse(value.hasMeaning()); - } - - @Test(expected = DatastoreException.class) - public void testIndexedCannotBeSpecified() { - ListValue.builder().indexed(false); + assertFalse(value.excludeFromIndexes()); } @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { ListValue.Builder builder = ListValue.builder().set(CONTENT); - ListValue value = builder.meaning(1).build(); + ListValue value = builder.meaning(1).excludeFromIndexes(true).build(); assertEquals(CONTENT, value.get()); - assertTrue(value.hasMeaning()); - assertEquals(Integer.valueOf(1), value.meaning()); - assertFalse(value.hasIndexed()); + assertEquals(1, value.meaning()); + assertTrue(value.excludeFromIndexes()); builder = ListValue.builder(); for (Value v : CONTENT) { diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/LongValueTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/LongValueTest.java index c4c899785d68..717c1567bc45 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/LongValueTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/LongValueTest.java @@ -37,19 +37,16 @@ public void testToBuilder() throws Exception { public void testOf() throws Exception { LongValue value = LongValue.of(CONTENT); assertEquals(CONTENT, value.get()); - assertFalse(value.hasIndexed()); - assertFalse(value.hasMeaning()); + assertFalse(value.excludeFromIndexes()); } @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { LongValue.Builder builder = LongValue.builder(CONTENT); - LongValue value = builder.meaning(1).indexed(false).build(); + LongValue value = builder.meaning(1).excludeFromIndexes(true).build(); assertEquals(CONTENT, value.get()); - assertTrue(value.hasMeaning()); - assertEquals(Integer.valueOf(1), value.meaning()); - assertTrue(value.hasIndexed()); - assertFalse(value.indexed()); + assertEquals(1, value.meaning()); + assertTrue(value.excludeFromIndexes()); } } diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/NullValueTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/NullValueTest.java index a42fdaf0229f..0856fced7992 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/NullValueTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/NullValueTest.java @@ -31,24 +31,20 @@ public void testToBuilder() throws Exception { assertEquals(value, value.toBuilder().build()); } - @SuppressWarnings("deprecation") @Test public void testOf() throws Exception { NullValue value = NullValue.of(); assertNull(value.get()); - assertFalse(value.hasIndexed()); - assertFalse(value.hasMeaning()); + assertFalse(value.excludeFromIndexes()); } @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { NullValue.Builder builder = NullValue.builder(); - NullValue value = builder.meaning(1).indexed(false).build(); + NullValue value = builder.meaning(1).excludeFromIndexes(true).build(); assertNull(value.get()); - assertTrue(value.hasMeaning()); - assertEquals(Integer.valueOf(1), value.meaning()); - assertTrue(value.hasIndexed()); - assertFalse(value.indexed()); + assertEquals(1, value.meaning()); + assertTrue(value.excludeFromIndexes()); } } diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/RawValueTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/RawValueTest.java index 4d63bc89bacb..1ab1c36538de 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/RawValueTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/RawValueTest.java @@ -20,13 +20,11 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import com.google.api.services.datastore.DatastoreV1; - import org.junit.Test; public class RawValueTest { - private static final DatastoreV1.Value CONTENT = StringValue.of("hello").toPb(); + private static final com.google.datastore.v1beta3.Value CONTENT = StringValue.of("hello").toPb(); @Test public void testToBuilder() throws Exception { @@ -34,24 +32,20 @@ public void testToBuilder() throws Exception { assertEquals(value, value.toBuilder().build()); } - @SuppressWarnings("deprecation") @Test public void testOf() throws Exception { RawValue value = RawValue.of(CONTENT); assertEquals(CONTENT, value.get()); - assertFalse(value.hasIndexed()); - assertFalse(value.hasMeaning()); + assertFalse(value.excludeFromIndexes()); } @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { RawValue.Builder builder = RawValue.builder(CONTENT); - RawValue value = builder.meaning(1).indexed(false).build(); + RawValue value = builder.meaning(1).excludeFromIndexes(true).build(); assertEquals(CONTENT, value.get()); - assertTrue(value.hasMeaning()); - assertEquals(Integer.valueOf(1), value.meaning()); - assertTrue(value.hasIndexed()); - assertFalse(value.indexed()); + assertEquals(1, value.meaning()); + assertTrue(value.excludeFromIndexes()); } } diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/SerializationTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/SerializationTest.java index b9e78800ffab..3679aba6825c 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/SerializationTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/SerializationTest.java @@ -18,13 +18,11 @@ import static java.nio.charset.StandardCharsets.UTF_8; -import com.google.api.services.datastore.DatastoreV1; import com.google.gcloud.AuthCredentials; import com.google.gcloud.BaseSerializationTest; import com.google.gcloud.Restorable; import com.google.gcloud.datastore.StructuredQuery.CompositeFilter; import com.google.gcloud.datastore.StructuredQuery.OrderBy; -import com.google.gcloud.datastore.StructuredQuery.Projection; import com.google.gcloud.datastore.StructuredQuery.PropertyFilter; public class SerializationTest extends BaseSerializationTest { @@ -36,6 +34,7 @@ public class SerializationTest extends BaseSerializationTest { IncompleteKey.builder(KEY1, "v").ancestors(PathElement.of("p", 1)).build(); private static final Key KEY2 = Key.builder(KEY1, "v", 2).build(); private static final DateTime DATE_TIME1 = DateTime.now(); + private static final LatLng LAT_LNG = new LatLng(37.422035, -122.084124); private static final Blob BLOB1 = Blob.copyFrom(UTF_8.encode("hello world")); private static final Cursor CURSOR1 = Cursor.copyFrom(new byte[] {1, 2}); private static final Cursor CURSOR2 = Cursor.copyFrom(new byte[] {10}); @@ -58,40 +57,42 @@ public class SerializationTest extends BaseSerializationTest { .kind("k") .filter(PropertyFilter.eq("p1", "hello")) .build(); - private static final Query QUERY3 = Query.projectionEntityQueryBuilder() - .kind("k") - .namespace("ns1") - .projection(Projection.property("p")) - .limit(100) - .offset(5) - .startCursor(CURSOR1) - .endCursor(CURSOR2) - .filter(CompositeFilter.and(PropertyFilter.gt("p1", 10), PropertyFilter.eq("a", "v"))) - .addGroupBy("p") - .addOrderBy(OrderBy.asc("p")) - .build(); + private static final Query QUERY3 = + Query.projectionEntityQueryBuilder() + .kind("k") + .namespace("ns1") + .projection("p") + .limit(100) + .offset(5) + .startCursor(CURSOR1) + .endCursor(CURSOR2) + .filter(CompositeFilter.and(PropertyFilter.gt("p1", 10), PropertyFilter.eq("a", "v"))) + .addDistinctOn("p") + .addOrderBy(OrderBy.asc("p")) + .build(); private static final KeyValue KEY_VALUE = KeyValue.of(KEY1); - private static final NullValue NULL_VALUE = NullValue.builder().indexed(true).build(); + private static final NullValue NULL_VALUE = NullValue.builder().excludeFromIndexes(true).build(); private static final StringValue STRING_VALUE = StringValue.of("hello"); private static final LongValue LONG_VALUE = LongValue.of(123); private static final DoubleValue DOUBLE_VALUE = DoubleValue.of(12.34); private static final BooleanValue BOOLEAN_VALUE = BooleanValue.of(true); private static final DateTimeValue DATE_AND_TIME_VALUE = DateTimeValue.of(DateTime.now()); private static final BlobValue BLOB_VALUE = BlobValue.of(BLOB1); - private static final RawValue RAW_VALUE = RawValue.of( - DatastoreV1.Value.newBuilder().setBlobKeyValue("blob-key").setMeaning(18).build()); + private static final RawValue RAW_VALUE = + RawValue.of(com.google.datastore.v1beta3.Value.newBuilder().setMeaning(18).build()); + private static final LatLngValue LAT_LNG_VALUE = LatLngValue.of(LAT_LNG); private static final Entity ENTITY1 = Entity.builder(KEY1).build(); private static final Entity ENTITY2 = Entity.builder(KEY2).set("null", NullValue.of()).build(); private static final Entity ENTITY3 = Entity.builder(KEY2) .set("p1", StringValue.builder("hi1").meaning(10).build()) - .set("p2", StringValue.builder("hi2").meaning(11).indexed(false).build()) - .set("p3", LongValue.builder(100).indexed(false).meaning(100).build()) + .set("p2", StringValue.builder("hi2").meaning(11).excludeFromIndexes(true).build()) + .set("p3", LongValue.builder(100).excludeFromIndexes(true).meaning(100).build()) .set("blob", BLOB1) .build(); private static final FullEntity EMBEDDED_ENTITY = Entity.builder(INCOMPLETE_KEY1) .set("p1", STRING_VALUE) - .set("p2", LongValue.builder(100).indexed(false).meaning(100).build()) + .set("p2", LongValue.builder(100).excludeFromIndexes(true).meaning(100).build()) .build(); private static final EntityValue EMBEDDED_ENTITY_VALUE1 = EntityValue.of(ENTITY1); private static final EntityValue EMBEDDED_ENTITY_VALUE2 = EntityValue.of(ENTITY2); @@ -115,14 +116,13 @@ protected java.io.Serializable[] serializableObjects() { DatastoreOptions otherOptions = options.toBuilder() .namespace("ns1") .authCredentials(null) - .force(true) .build(); return new java.io.Serializable[]{KEY1, KEY2, INCOMPLETE_KEY1, INCOMPLETE_KEY2, ENTITY1, ENTITY2, ENTITY3, EMBEDDED_ENTITY, PROJECTION_ENTITY, DATE_TIME1, BLOB1, CURSOR1, GQL1, GQL2, QUERY1, QUERY2, QUERY3, NULL_VALUE, KEY_VALUE, STRING_VALUE, EMBEDDED_ENTITY_VALUE1, EMBEDDED_ENTITY_VALUE2, EMBEDDED_ENTITY_VALUE3, LIST_VALUE, LONG_VALUE, DOUBLE_VALUE, - BOOLEAN_VALUE, DATE_AND_TIME_VALUE, BLOB_VALUE, RAW_VALUE, DATASTORE_EXCEPTION, options, - otherOptions}; + BOOLEAN_VALUE, DATE_AND_TIME_VALUE, BLOB_VALUE, RAW_VALUE, LAT_LNG_VALUE, + DATASTORE_EXCEPTION, options, otherOptions}; } @Override diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/StringValueTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/StringValueTest.java index a2cacd6574aa..4f02568bf924 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/StringValueTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/StringValueTest.java @@ -32,24 +32,20 @@ public void testToBuilder() throws Exception { assertEquals(value, value.toBuilder().build()); } - @SuppressWarnings("deprecation") @Test public void testOf() throws Exception { StringValue value = StringValue.of(CONTENT); assertEquals(CONTENT, value.get()); - assertFalse(value.hasIndexed()); - assertFalse(value.hasMeaning()); + assertFalse(value.excludeFromIndexes()); } @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { StringValue.Builder builder = StringValue.builder(CONTENT); - StringValue value = builder.meaning(1).indexed(false).build(); + StringValue value = builder.meaning(1).excludeFromIndexes(true).build(); assertEquals(CONTENT, value.get()); - assertTrue(value.hasMeaning()); - assertEquals(Integer.valueOf(1), value.meaning()); - assertTrue(value.hasIndexed()); - assertFalse(value.indexed()); + assertEquals(1, value.meaning()); + assertTrue(value.excludeFromIndexes()); } } diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/StructuredQueryTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/StructuredQueryTest.java index 4b6589efd723..cab98ab53837 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/StructuredQueryTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/StructuredQueryTest.java @@ -25,7 +25,6 @@ import com.google.gcloud.datastore.StructuredQuery.CompositeFilter; import com.google.gcloud.datastore.StructuredQuery.Filter; import com.google.gcloud.datastore.StructuredQuery.OrderBy; -import com.google.gcloud.datastore.StructuredQuery.Projection; import com.google.gcloud.datastore.StructuredQuery.PropertyFilter; import org.junit.Test; @@ -45,12 +44,12 @@ public class StructuredQueryTest { private static final OrderBy ORDER_BY_1 = OrderBy.asc("p2"); private static final OrderBy ORDER_BY_2 = OrderBy.desc("p3"); private static final List ORDER_BY = ImmutableList.of(ORDER_BY_1, ORDER_BY_2); - private static final Projection PROJECTION1 = Projection.property("p4"); - private static final Projection PROJECTION2 = Projection.property("p5"); - private static final List PROJECTION = ImmutableList.of(PROJECTION1, PROJECTION2); - private static final String GROUP_BY1 = "p6"; - private static final String GROUP_BY2 = "p7"; - private static final List GROUP_BY = ImmutableList.of(GROUP_BY1, GROUP_BY2); + private static final String PROJECTION1 = "p4"; + private static final String PROJECTION2 = "p5"; + private static final List PROJECTION = ImmutableList.of(PROJECTION1, PROJECTION2); + private static final String DISTINCT_ON1 = "p6"; + private static final String DISTINCT_ON2 = "p7"; + private static final List DISTINCT_ON = ImmutableList.of(DISTINCT_ON1, DISTINCT_ON2); private static final EntityQuery ENTITY_QUERY = Query.entityQueryBuilder() .namespace(NAMESPACE) .kind(KIND) @@ -82,30 +81,28 @@ public class StructuredQueryTest { .filter(FILTER) .orderBy(ORDER_BY_1, ORDER_BY_2) .projection(PROJECTION1, PROJECTION2) - .groupBy(GROUP_BY1, GROUP_BY2) + .distinctOn(DISTINCT_ON1, DISTINCT_ON2) .build(); @Test public void testEntityQueryBuilder() { compareBaseBuilderFields(ENTITY_QUERY); assertTrue(ENTITY_QUERY.projection().isEmpty()); - assertTrue(ENTITY_QUERY.groupBy().isEmpty()); + assertTrue(ENTITY_QUERY.distinctOn().isEmpty()); } @Test public void testKeyQueryBuilder() { compareBaseBuilderFields(KEY_QUERY); - assertEquals( - ImmutableList.of(Projection.property(StructuredQuery.KEY_PROPERTY_NAME)), - KEY_QUERY.projection()); - assertTrue(KEY_QUERY.groupBy().isEmpty()); + assertEquals(ImmutableList.of(StructuredQuery.KEY_PROPERTY_NAME), KEY_QUERY.projection()); + assertTrue(KEY_QUERY.distinctOn().isEmpty()); } @Test public void testProjectionEntityQueryBuilder() { compareBaseBuilderFields(PROJECTION_QUERY); assertEquals(PROJECTION, PROJECTION_QUERY.projection()); - assertEquals(GROUP_BY, PROJECTION_QUERY.groupBy()); + assertEquals(DISTINCT_ON, PROJECTION_QUERY.distinctOn()); } private void compareBaseBuilderFields(StructuredQuery query) { @@ -138,7 +135,7 @@ private void compareMergedQuery(StructuredQuery expected, StructuredQuery assertEquals(expected.filter(), actual.filter()); assertEquals(expected.orderBy(), actual.orderBy()); assertEquals(expected.projection(), actual.projection()); - assertEquals(expected.groupBy(), actual.groupBy()); + assertEquals(expected.distinctOn(), actual.distinctOn()); } @Test diff --git a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/ValueTest.java b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/ValueTest.java index 891668990f66..fb718dffe1e5 100644 --- a/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/ValueTest.java +++ b/gcloud-java-datastore/src/test/java/com/google/gcloud/datastore/ValueTest.java @@ -18,7 +18,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import com.google.common.collect.ImmutableList; @@ -42,21 +41,24 @@ public class ValueTest { private static final NullValue NULL_VALUE = NullValue.of(); private static final StringValue STRING_VALUE = StringValue.of("hello"); private static final RawValue RAW_VALUE = RawValue.of(STRING_VALUE.toPb()); + private static final LatLngValue LAT_LNG_VALUE = + LatLngValue.of(new LatLng(37.422035, -122.084124)); private static final ImmutableMap TYPES = ImmutableMap.builder() - .put(ValueType.NULL, new Object[] {NullValue.class, NULL_VALUE.get()}) - .put(ValueType.KEY, new Object[] {KeyValue.class, KEY}) - .put(ValueType.BLOB, new Object[] {BlobValue.class, BLOB}) - .put(ValueType.BOOLEAN, new Object[] {BooleanValue.class, Boolean.TRUE}) - .put(ValueType.DATE_TIME, new Object[] {DateTimeValue.class, DATE_TIME}) - .put(ValueType.DOUBLE, new Object[] {DoubleValue.class, 1.25D}) - .put(ValueType.ENTITY, new Object[] {EntityValue.class, ENTITY}) - .put(ValueType.LIST, - new Object[] {ListValue.class, ImmutableList.of(NULL_VALUE, STRING_VALUE, RAW_VALUE)}) - .put(ValueType.LONG, new Object[] {LongValue.class, 123L}) - .put(ValueType.RAW_VALUE, new Object[] {RawValue.class, RAW_VALUE.get()}) - .put(ValueType.STRING, new Object[] {StringValue.class, STRING_VALUE.get()}) - .build(); + .put(ValueType.NULL, new Object[] {NullValue.class, NULL_VALUE.get()}) + .put(ValueType.KEY, new Object[] {KeyValue.class, KEY}) + .put(ValueType.BLOB, new Object[] {BlobValue.class, BLOB}) + .put(ValueType.BOOLEAN, new Object[] {BooleanValue.class, Boolean.TRUE}) + .put(ValueType.DATE_TIME, new Object[] {DateTimeValue.class, DATE_TIME}) + .put(ValueType.DOUBLE, new Object[] {DoubleValue.class, 1.25D}) + .put(ValueType.ENTITY, new Object[] {EntityValue.class, ENTITY}) + .put(ValueType.LIST, new Object[] { + ListValue.class, ImmutableList.of(NULL_VALUE, STRING_VALUE, RAW_VALUE)}) + .put(ValueType.LONG, new Object[] {LongValue.class, 123L}) + .put(ValueType.RAW_VALUE, new Object[] {RawValue.class, RAW_VALUE.get()}) + .put(ValueType.LAT_LNG, new Object[] {LatLngValue.class, LAT_LNG_VALUE.get()}) + .put(ValueType.STRING, new Object[] {StringValue.class, STRING_VALUE.get()}) + .build(); private ImmutableMap> typeToValue; @@ -119,67 +121,21 @@ public void testType() throws Exception { } @Test - public void testHasIndexed() throws Exception { + public void testExcludeFromIndexes() throws Exception { for (Map.Entry> entry : typeToValue.entrySet()) { - ValueType valueType = entry.getKey(); - Boolean indexed = entry.getValue().hasIndexed(); - switch (valueType) { - case ENTITY: - assertTrue(indexed); - break; - default: - assertFalse(indexed); - break; - } + assertFalse(entry.getValue().excludeFromIndexes()); } - TestBuilder builder = new TestBuilder(); - assertFalse(builder.build().hasIndexed()); - assertTrue(builder.indexed(false).build().hasIndexed()); - assertTrue(builder.indexed(true).build().hasIndexed()); - } - - @Test - public void testIndexed() throws Exception { - for (Map.Entry> entry : typeToValue.entrySet()) { - ValueType valueType = entry.getKey(); - Boolean indexed = entry.getValue().indexed(); - switch (valueType) { - case ENTITY: - assertFalse(indexed); - break; - default: - assertNull(indexed); - break; - } - } - - TestBuilder builder = new TestBuilder(); - assertNull(builder.build().indexed()); - assertFalse(builder.indexed(false).build().indexed()); - assertTrue(builder.indexed(true).build().indexed()); - } - - @SuppressWarnings("deprecation") - @Test - public void testHasMeaning() throws Exception { - for (Value value : typeToValue.values()) { - assertFalse(value.hasMeaning()); - } - - TestBuilder builder = new TestBuilder(); - assertTrue(builder.meaning(10).build().hasMeaning()); + assertFalse(builder.build().excludeFromIndexes()); + assertTrue(builder.excludeFromIndexes(true).build().excludeFromIndexes()); + assertFalse(builder.excludeFromIndexes(false).build().excludeFromIndexes()); } @SuppressWarnings("deprecation") @Test public void testMeaning() throws Exception { - for (Value value : typeToValue.values()) { - assertNull(value.meaning()); - } - TestBuilder builder = new TestBuilder(); - assertEquals(Integer.valueOf(10), builder.meaning(10).build().meaning()); + assertEquals(10, builder.meaning(10).build().meaning()); } @Test @@ -201,12 +157,11 @@ public void testToBuilder() throws Exception { Set content = Collections.singleton("bla"); @SuppressWarnings("rawtypes") ValueBuilder builder = new TestBuilder(); - builder.meaning(1).set(content).indexed(true); + builder.meaning(1).set(content).excludeFromIndexes(true); Value value = builder.build(); builder = value.toBuilder(); - assertEquals(Integer.valueOf(1), value.meaning()); - assertTrue(value.hasIndexed()); - assertTrue(value.indexed()); + assertEquals(1, value.meaning()); + assertTrue(value.excludeFromIndexes()); assertEquals(ValueType.LIST, value.type()); assertEquals(content, value.get()); assertEquals(value, builder.build()); diff --git a/gcloud-java-dns/README.md b/gcloud-java-dns/README.md index 4f65d8e3b814..0bb9a47635a2 100644 --- a/gcloud-java-dns/README.md +++ b/gcloud-java-dns/README.md @@ -22,16 +22,16 @@ If you are using Maven, add this to your pom.xml file com.google.gcloud gcloud-java-dns - 0.1.5 + 0.1.7 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.gcloud:gcloud-java-dns:0.1.5' +compile 'com.google.gcloud:gcloud-java-dns:0.1.7' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.gcloud" % "gcloud-java-dns" % "0.1.5" +libraryDependencies += "com.google.gcloud" % "gcloud-java-dns" % "0.1.7" ``` Example Application @@ -92,7 +92,7 @@ Dns dns = DnsOptions.defaultInstance().service(); For other authentication options, see the [Authentication](https://github.com/GoogleCloudPlatform/gcloud-java#authentication) page. #### Managing Zones -DNS records in `gcloud-java-dns` are managed inside containers called "zones". `ZoneInfo` is a class +Record sets in `gcloud-java-dns` are managed inside containers called "zones". `ZoneInfo` is a class which encapsulates metadata that describe a zone in Google Cloud DNS. `Zone`, a subclass of `ZoneInfo`, adds service-related functionality over `ZoneInfo`. @@ -100,7 +100,7 @@ functionality over `ZoneInfo`. exists within your project, you'll get a helpful error message telling you to choose another name. In the code below, replace "my-unique-zone" with a unique zone name. See more about naming rules [here](https://cloud.google.com/dns/api/v1/managedZones#name).* -In this code snippet, we create a new zone to manage DNS records for domain `someexampledomain.com.` +In this code snippet, we create a new zone to manage record sets for domain `someexampledomain.com.` *Important: The service may require that you verify ownership of the domain for which you are creating a zone. Hence, we recommend that you do so beforehand. You can verify ownership of @@ -125,11 +125,11 @@ ZoneInfo zoneInfo = ZoneInfo.of(zoneName, domainName, description); // Create zone in Google Cloud DNS Zone zone = dns.create(zoneInfo); -System.out.printf("Zone was created and assigned ID %s.%n", zone.id()); +System.out.printf("Zone was created and assigned ID %s.%n", zone.generatedId()); ``` -You now have an empty zone hosted in Google Cloud DNS which is ready to be populated with DNS -records for domain name `someexampledomain.com.` Upon creating the zone, the cloud service +You now have an empty zone hosted in Google Cloud DNS which is ready to be populated with +record sets for domain name `someexampledomain.com.` Upon creating the zone, the cloud service assigned a set of DNS servers to host records for this zone and created the required SOA and NS records for the domain. The following snippet prints the list of servers assigned to the zone created above. First, import @@ -152,15 +152,15 @@ You can now instruct your domain registrar to [update your domain name servers] As soon as this happens and the change propagates through cached values in DNS resolvers, all the DNS queries will be directed to and answered by the Google Cloud DNS service. -#### Creating DNS Records -Now that we have a zone, we can add some DNS records. The DNS records held within zones are +#### Creating Record Sets +Now that we have a zone, we can add some record sets. The record sets held within zones are modified by "change requests". In this example, we create and apply a change request to -our zone that creates a DNS record of type A and points URL www.someexampledomain.com to +our zone that creates a record set of type A and points URL www.someexampledomain.com to IP address 12.13.14.15. Start by adding ```java -import com.google.gcloud.dns.ChangeRequest; -import com.google.gcloud.dns.DnsRecord; +import com.google.gcloud.dns.ChangeRequestInfo; +import com.google.gcloud.dns.RecordSet; import java.util.concurrent.TimeUnit; ``` @@ -168,26 +168,26 @@ import java.util.concurrent.TimeUnit; and proceed with: ```java -// Prepare a www.someexampledomain.com. type A record with ttl of 24 hours +// Prepare a www.someexampledomain.com. type A record set with ttl of 24 hours String ip = "12.13.14.15"; -DnsRecord toCreate = DnsRecord.builder("www.someexampledomain.com.", DnsRecord.Type.A) +RecordSet toCreate = RecordSet.builder("www." + zone.dnsName(), RecordSet.Type.A) .ttl(24, TimeUnit.HOURS) .addRecord(ip) .build(); // Make a change -ChangeRequest changeRequest = ChangeRequest.builder().add(toCreate).build(); +ChangeRequestInfo changeRequest = ChangeRequestInfo.builder().add(toCreate).build(); // Build and apply the change request to our zone changeRequest = zone.applyChangeRequest(changeRequest); ``` -The `addRecord` method of `DnsRecord.Builder` accepts records in the form of -strings. The format of the strings depends on the type of the DNS record to be added. -More information on the supported DNS record types and record formats can be found [here](https://cloud.google.com/dns/what-is-cloud-dns#supported_record_types). +The `addRecord` method of `RecordSet.Builder` accepts records in the form of +strings. The format of the strings depends on the type of the record sets to be added. +More information on the supported record set types and record formats can be found [here](https://cloud.google.com/dns/what-is-cloud-dns#supported_record_types). -If you already have a DNS record, Cloud DNS will return an error upon an attempt to create a duplicate of it. -You can modify the code above to create a DNS record or update it if it already exists by making the +If you already have a record set, Cloud DNS will return an error upon an attempt to create a duplicate of it. +You can modify the code above to create a record set or update it if it already exists by making the following adjustment in your imports ```java @@ -198,21 +198,21 @@ and in the code ```java // Make a change -ChangeRequest.Builder changeBuilder = ChangeRequest.builder().add(toCreate); +ChangeRequestInfo.Builder changeBuilder = ChangeRequestInfo.builder().add(toCreate); // Verify the type A record does not exist yet. // If it does exist, we will overwrite it with our prepared record. -Iterator recordIterator = zone.listDnsRecords().iterateAll(); -while (recordIterator.hasNext()) { - DnsRecord current = recordIterator.next(); +Iterator recordSetIterator = zone.listRecordSets().iterateAll(); +while (recordSetIterator.hasNext()) { + RecordSet current = recordSetIterator.next(); if (toCreate.name().equals(current.name()) && toCreate.type().equals(current.type())) { changeBuilder.delete(current); } } // Build and apply the change request to our zone -ChangeRequest changeRequest = changeBuilder.build(); -zone.applyChangeRequest(changeRequest); +ChangeRequestInfo changeRequest = changeBuilder.build(); +ChangeRequest pendingRequest = zone.applyChangeRequest(changeRequest); ``` You can find more information about changes in the [Cloud DNS documentation] (https://cloud.google.com/dns/what-is-cloud-dns#cloud_dns_api_concepts). @@ -220,13 +220,12 @@ When the change request is applied, it is registered with the Cloud DNS service can wait for its completion as follows: ```java -while (ChangeRequest.Status.PENDING.equals(changeRequest.status())) { +while (!pendingRequest.isDone()) { try { Thread.sleep(500L); } catch (InterruptedException e) { System.err.println("The thread was interrupted while waiting..."); } - changeRequest = dns.getChangeRequest(zone.name(), changeRequest.id()); } System.out.println("The change request has been applied."); ``` @@ -235,15 +234,15 @@ Change requests are applied atomically to all the assigned DNS servers at once. happens, it may still take a while for the change to be registered by the DNS cache resolvers. See more on this topic [here](https://cloud.google.com/dns/monitoring). -#### Listing Zones and DNS Records -Suppose that you have added more zones and DNS records, and now you want to list them. +#### Listing Zones and Record Sets +Suppose that you have added more zones and record sets, and now you want to list them. First, import the following (unless you have done so in the previous section): ```java import java.util.Iterator; ``` -Then add the following code to list all your zones and DNS records. +Then add the following code to list all your zones and record sets. ```java // List all your zones @@ -254,17 +253,25 @@ while (zoneIterator.hasNext()) { counter++; } -// List the DNS records in a particular zone -Iterator recordIterator = zone.listDnsRecords().iterateAll(); -System.out.println(String.format("DNS records inside %s:", zone.name())); -while (recordIterator.hasNext()) { - System.out.println(recordIterator.next()); +// List the record sets in a particular zone +recordSetIterator = zone.listRecordSets().iterateAll(); +System.out.println(String.format("Record sets inside %s:", zone.name())); +while (recordSetIterator.hasNext()) { + System.out.println(recordSetIterator.next()); } ``` -You can also list the history of change requests that were applied to a zone: +You can also list the history of change requests that were applied to a zone. +First add: + +```java +import java.util.ChangeRequest; +``` + +and then: ```java + // List the change requests applied to a particular zone Iterator changeIterator = zone.listChangeRequests().iterateAll(); System.out.println(String.format("The history of changes in %s:", zone.name())); @@ -276,28 +283,26 @@ while (changeIterator.hasNext()) { #### Deleting Zones If you no longer want to host a zone in Cloud DNS, you can delete it. -First, you need to empty the zone by deleting all its records except for the default SOA and NS records. +First, you need to empty the zone by deleting all its records except for the default SOA and NS record sets. ```java -// Make a change for deleting the records -ChangeRequest.Builder changeBuilder = ChangeRequest.builder(); +// Make a change for deleting the record sets +changeBuilder = ChangeRequestInfo.builder(); while (recordIterator.hasNext()) { - DnsRecord current = recordIterator.next(); + RecordSet current = recordIterator.next(); // SOA and NS records cannot be deleted - if (!DnsRecord.Type.SOA.equals(current.type()) && !DnsRecord.Type.NS.equals(current.type())) { + if (!RecordSet.Type.SOA.equals(current.type()) && !RecordSet.Type.NS.equals(current.type())) { changeBuilder.delete(current); } } // Build and apply the change request to our zone if it contains records to delete -ChangeRequest changeRequest = changeBuilder.build(); +ChangeRequestInfo changeRequest = changeBuilder.build(); if (!changeRequest.deletions().isEmpty()) { - changeRequest = dns.applyChangeRequest(zoneName, changeRequest); + ChangeRequest pendingRequest = dns.applyChangeRequest(zoneName, changeRequest); - // Wait for change to finish, but save data traffic by transferring only ID and status - Dns.ChangeRequestOption option = - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS); - while (ChangeRequest.Status.PENDING.equals(changeRequest.status())) { + // Wait for the change request to complete + while (!pendingRequest.isDone()) { System.out.println("Waiting for change to complete. Going to sleep for 500ms..."); try { Thread.sleep(500); @@ -305,9 +310,6 @@ if (!changeRequest.deletions().isEmpty()) { System.err.println("The thread was interrupted while waiting for change request to be " + "processed."); } - - // Update the change, but fetch only change ID and status - changeRequest = dns.getChangeRequest(zoneName, changeRequest.id(), option); } } @@ -324,11 +326,11 @@ if (result) { We composed some of the aforementioned snippets into complete executable code samples. In [CreateZones.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateZone.java) -we create a zone. In [CreateOrUpdateDnsRecords.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateDnsRecords.java) -we create a type A record for a zone, or update an existing type A record to a new IP address. We +we create a zone. In [CreateOrUpdateRecordSets.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateRecordSets.java) +we create a type A record set for a zone, or update an existing type A record set to a new IP address. We demonstrate how to delete a zone in [DeleteZone.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/DeleteZone.java). -Finally, in [ManipulateZonesAndRecords.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecords.java) -we assemble all the code snippets together and create zone, create or update a DNS record, list zones, list DNS records, list changes, and +Finally, in [ManipulateZonesAndRecordSets.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecordSets.java) +we assemble all the code snippets together and create zone, create or update a record set, list zones, list record sets, list changes, and delete a zone. The applications assume that they are running on Compute Engine or from your own desktop. To run any of these examples on App Engine, simply move the code from the main method to your application's servlet class and change the print statements to display on your webpage. diff --git a/gcloud-java-dns/pom.xml b/gcloud-java-dns/pom.xml index b55200b8fc7d..a4928ccf0397 100644 --- a/gcloud-java-dns/pom.xml +++ b/gcloud-java-dns/pom.xml @@ -3,7 +3,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.google.gcloud gcloud-java-dns jar GCloud Java DNS @@ -13,7 +12,7 @@ com.google.gcloud gcloud-java-pom - 0.1.6-SNAPSHOT + 0.1.8-SNAPSHOT gcloud-java-dns diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java index 76d231b704c4..b3a2a2170d8b 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java @@ -20,298 +20,210 @@ import com.google.api.services.dns.model.Change; import com.google.common.base.Function; -import com.google.common.base.MoreObjects; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import org.joda.time.DateTime; -import org.joda.time.format.ISODateTimeFormat; - -import java.io.Serializable; -import java.util.LinkedList; +import java.io.IOException; +import java.io.ObjectInputStream; import java.util.List; import java.util.Objects; /** - * A class representing an atomic update to a collection of {@link DnsRecord}s within a {@code - * Zone}. + * An immutable class representing an atomic update to a collection of {@link RecordSet}s within a + * {@code Zone}. * * @see Google Cloud DNS documentation */ -public class ChangeRequest implements Serializable { - - static final Function FROM_PB_FUNCTION = - new Function() { - @Override - public ChangeRequest apply(com.google.api.services.dns.model.Change pb) { - return ChangeRequest.fromPb(pb); - } - }; - private static final long serialVersionUID = -9027378042756366333L; - private final List additions; - private final List deletions; - private final String id; - private final Long startTimeMillis; - private final Status status; +public class ChangeRequest extends ChangeRequestInfo { - /** - * This enumerates the possible states of a {@code ChangeRequest}. - * - * @see Google Cloud DNS - * documentation - */ - public enum Status { - PENDING, - DONE - } + private static final long serialVersionUID = 5335667200595081449L; + private final DnsOptions options; + private final String zone; + private transient Dns dns; /** * A builder for {@code ChangeRequest}s. */ - public static class Builder { + public static class Builder extends ChangeRequestInfo.Builder { - private List additions = new LinkedList<>(); - private List deletions = new LinkedList<>(); - private String id; - private Long startTimeMillis; - private Status status; + private final Dns dns; + private final String zone; + private final ChangeRequestInfo.BuilderImpl infoBuilder; private Builder(ChangeRequest cr) { - this.additions = Lists.newLinkedList(cr.additions()); - this.deletions = Lists.newLinkedList(cr.deletions()); - this.id = cr.id(); - this.startTimeMillis = cr.startTimeMillis(); - this.status = cr.status(); + this.dns = cr.dns; + this.zone = cr.zone; + this.infoBuilder = new ChangeRequestInfo.BuilderImpl(cr); } - private Builder() { - } - - /** - * Sets a collection of {@link DnsRecord}s which are to be added to the zone upon executing this - * {@code ChangeRequest}. - */ - public Builder additions(List additions) { - this.additions = Lists.newLinkedList(checkNotNull(additions)); + @Override + public Builder additions(List additions) { + infoBuilder.additions(additions); return this; } - /** - * Sets a collection of {@link DnsRecord}s which are to be deleted from the zone upon executing - * this {@code ChangeRequest}. - */ - public Builder deletions(List deletions) { - this.deletions = Lists.newLinkedList(checkNotNull(deletions)); + @Override + public Builder deletions(List deletions) { + infoBuilder.deletions(deletions); return this; } - /** - * Adds a {@link DnsRecord} to be added to the zone upon executing this {@code - * ChangeRequest}. - */ - public Builder add(DnsRecord record) { - this.additions.add(checkNotNull(record)); + @Override + public Builder add(RecordSet recordSet) { + infoBuilder.add(recordSet); return this; } - /** - * Adds a {@link DnsRecord} to be deleted to the zone upon executing this - * {@code ChangeRequest}. - */ - public Builder delete(DnsRecord record) { - this.deletions.add(checkNotNull(record)); + @Override + public Builder delete(RecordSet recordSet) { + infoBuilder.delete(recordSet); return this; } - /** - * Clears the collection of {@link DnsRecord}s which are to be added to the zone upon executing - * this {@code ChangeRequest}. - */ + @Override public Builder clearAdditions() { - this.additions.clear(); + infoBuilder.clearAdditions(); return this; } - /** - * Clears the collection of {@link DnsRecord}s which are to be deleted from the zone upon - * executing this {@code ChangeRequest}. - */ + @Override public Builder clearDeletions() { - this.deletions.clear(); + infoBuilder.clearDeletions(); return this; } - /** - * Removes a single {@link DnsRecord} from the collection of records to be - * added to the zone upon executing this {@code ChangeRequest}. - */ - public Builder removeAddition(DnsRecord record) { - this.additions.remove(record); + @Override + public Builder removeAddition(RecordSet recordSet) { + infoBuilder.removeAddition(recordSet); return this; } - /** - * Removes a single {@link DnsRecord} from the collection of records to be - * deleted from the zone upon executing this {@code ChangeRequest}. - */ - public Builder removeDeletion(DnsRecord record) { - this.deletions.remove(record); + @Override + public Builder removeDeletion(RecordSet recordSet) { + infoBuilder.removeDeletion(recordSet); return this; } - /** - * Associates a server-assigned id to this {@code ChangeRequest}. - */ - Builder id(String id) { - this.id = checkNotNull(id); + @Override + Builder generatedId(String generatedId) { + infoBuilder.generatedId(generatedId); return this; } - /** - * Sets the time when this {@code ChangeRequest} was started by a server. - */ + @Override Builder startTimeMillis(long startTimeMillis) { - this.startTimeMillis = startTimeMillis; + infoBuilder.startTimeMillis(startTimeMillis); return this; } - /** - * Sets the current status of this {@code ChangeRequest}. - */ + @Override Builder status(Status status) { - this.status = checkNotNull(status); + infoBuilder.status(status); return this; } - /** - * Creates a {@code ChangeRequest} instance populated by the values associated with this - * builder. - */ + @Override public ChangeRequest build() { - return new ChangeRequest(this); + return new ChangeRequest(dns, zone, infoBuilder); } } - private ChangeRequest(Builder builder) { - this.additions = ImmutableList.copyOf(builder.additions); - this.deletions = ImmutableList.copyOf(builder.deletions); - this.id = builder.id; - this.startTimeMillis = builder.startTimeMillis; - this.status = builder.status; - } - - /** - * Returns an empty builder for the {@code ChangeRequest} class. - */ - public static Builder builder() { - return new Builder(); + ChangeRequest(Dns dns, String zone, ChangeRequest.BuilderImpl infoBuilder) { + super(infoBuilder); + this.zone = checkNotNull(zone); + this.dns = checkNotNull(dns); + this.options = dns.options(); } /** - * Creates a builder populated with values of this {@code ChangeRequest}. + * Returns the name of the {@link Zone} associated with this change request. */ - public Builder toBuilder() { - return new Builder(this); + public String zone() { + return this.zone; } /** - * Returns the list of {@link DnsRecord}s to be added to the zone upon submitting this {@code - * ChangeRequest}. + * Returns the change request's {@code Dns} object used to issue requests. */ - public List additions() { - return additions; + public Dns dns() { + return dns; } /** - * Returns the list of {@link DnsRecord}s to be deleted from the zone upon submitting this {@code - * ChangeRequest}. + * Applies this change request to the zone identified by {@code zoneName}. + * + * @throws DnsException upon failure or if zone is not found */ - public List deletions() { - return deletions; + public ChangeRequest applyTo(String zoneName, Dns.ChangeRequestOption... options) { + return dns.applyChangeRequest(zoneName, this, options); } /** - * Returns the id assigned to this {@code ChangeRequest} by the server. + * Retrieves the up-to-date information about the change request from Google Cloud DNS. Parameter + * {@code options} can be used to restrict the fields to be included in the updated object the + * same way as in {@link Dns#getChangeRequest(String, String, Dns.ChangeRequestOption...)}. If + * {@code options} are provided, any field other than generatedId which is not included in the + * {@code options} will be {@code null} regardless of whether they are initialized or not in + * {@code this} instance. + * + * @return an object with the updated information or {@code null} if it does not exist + * @throws DnsException upon failure of the API call or if the associated zone was not found */ - public String id() { - return id; + public ChangeRequest reload(Dns.ChangeRequestOption... options) { + return dns.getChangeRequest(zone, generatedId(), options); } /** - * Returns the time when this {@code ChangeRequest} was started by the server. + * Returns {@code true} if the change request has been completed. If the status is not {@link + * Status#DONE} already, the method makes an API call to Google Cloud DNS to update the change + * request first. + * + * @throws DnsException upon failure of the API call or if the associated zone was not found */ - public Long startTimeMillis() { - return startTimeMillis; + public boolean isDone() { + if (status() == Status.DONE) { + return true; + } + ChangeRequest updated = reload(Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); + return updated == null || updated.status() == Status.DONE; } - /** - * Returns the status of this {@code ChangeRequest}. - */ - public Status status() { - return status; + @Override + public Builder toBuilder() { + return new Builder(this); } - com.google.api.services.dns.model.Change toPb() { - com.google.api.services.dns.model.Change pb = - new com.google.api.services.dns.model.Change(); - // set id - if (id() != null) { - pb.setId(id()); - } - // set timestamp - if (startTimeMillis() != null) { - pb.setStartTime(ISODateTimeFormat.dateTime().withZoneUTC().print(startTimeMillis())); - } - // set status - if (status() != null) { - pb.setStatus(status().name().toLowerCase()); + @Override + public boolean equals(Object obj) { + if (obj == null || !obj.getClass().equals(ChangeRequest.class)) { + return false; + } else { + ChangeRequest other = (ChangeRequest) obj; + return Objects.equals(options, other.options) + && Objects.equals(zone, other.zone) + && Objects.equals(toPb(), other.toPb()); } - // set a list of additions - pb.setAdditions(Lists.transform(additions(), DnsRecord.TO_PB_FUNCTION)); - // set a list of deletions - pb.setDeletions(Lists.transform(deletions(), DnsRecord.TO_PB_FUNCTION)); - return pb; } - static ChangeRequest fromPb(com.google.api.services.dns.model.Change pb) { - Builder builder = builder(); - if (pb.getId() != null) { - builder.id(pb.getId()); - } - if (pb.getStartTime() != null) { - builder.startTimeMillis(DateTime.parse(pb.getStartTime()).getMillis()); - } - if (pb.getStatus() != null) { - // we are assuming that status indicated in pb is a lower case version of the enum name - builder.status(ChangeRequest.Status.valueOf(pb.getStatus().toUpperCase())); - } - if (pb.getDeletions() != null) { - builder.deletions(Lists.transform(pb.getDeletions(), DnsRecord.FROM_PB_FUNCTION)); - } - if (pb.getAdditions() != null) { - builder.additions(Lists.transform(pb.getAdditions(), DnsRecord.FROM_PB_FUNCTION)); - } - return builder.build(); + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), options, zone); } - @Override - public boolean equals(Object other) { - return (other instanceof ChangeRequest) && toPb().equals(((ChangeRequest) other).toPb()); + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + this.dns = options.service(); } - @Override - public int hashCode() { - return Objects.hash(additions, deletions, id, startTimeMillis, status); + static ChangeRequest fromPb(Dns dns, String zoneName, Change pb) { + ChangeRequestInfo info = ChangeRequestInfo.fromPb(pb); + return new ChangeRequest(dns, zoneName, new ChangeRequestInfo.BuilderImpl(info)); } - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("additions", additions) - .add("deletions", deletions) - .add("id", id) - .add("startTimeMillis", startTimeMillis) - .add("status", status) - .toString(); + static Function fromPbFunction(final Dns dns, final String zoneName) { + return new Function() { + @Override + public ChangeRequest apply(Change pb) { + return ChangeRequest.fromPb(dns, zoneName, pb); + } + }; } } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequestInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequestInfo.java new file mode 100644 index 000000000000..4a92512996dd --- /dev/null +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequestInfo.java @@ -0,0 +1,358 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.gcloud.dns; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.api.services.dns.model.Change; +import com.google.common.base.Function; +import com.google.common.base.MoreObjects; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; + +import org.joda.time.DateTime; +import org.joda.time.format.ISODateTimeFormat; + +import java.io.Serializable; +import java.util.LinkedList; +import java.util.List; +import java.util.Objects; + +/** + * A class representing an atomic update to a collection of {@link RecordSet}s within a {@code + * Zone}. + * + * @see Google Cloud DNS documentation + */ +public class ChangeRequestInfo implements Serializable { + + static final Function FROM_PB_FUNCTION = + new Function() { + @Override + public ChangeRequestInfo apply(Change pb) { + return ChangeRequestInfo.fromPb(pb); + } + }; + private static final long serialVersionUID = -6029143477639439169L; + private final List additions; + private final List deletions; + private final String generatedId; + private final Long startTimeMillis; + private final ChangeRequestInfo.Status status; + + /** + * This enumerates the possible states of a change request. + * + * @see Google Cloud DNS + * documentation + */ + public enum Status { + PENDING, + DONE + } + + /** + * A builder for {@code ChangeRequestInfo}. + */ + public abstract static class Builder { + + /** + * Sets a collection of {@link RecordSet}s which are to be added to the zone upon executing this + * {@code ChangeRequestInfo}. + */ + public abstract Builder additions(List additions); + + /** + * Sets a collection of {@link RecordSet}s which are to be deleted from the zone upon executing + * this {@code ChangeRequestInfo}. + */ + public abstract Builder deletions(List deletions); + + /** + * Adds a {@link RecordSet} to be added to the zone upon executing this {@code + * ChangeRequestInfo}. + */ + public abstract Builder add(RecordSet recordSet); + + /** + * Adds a {@link RecordSet} to be deleted to the zone upon executing this + * {@code ChangeRequestInfo}. + */ + public abstract Builder delete(RecordSet recordSet); + + /** + * Clears the collection of {@link RecordSet}s which are to be added to the zone upon executing + * this {@code ChangeRequestInfo}. + */ + public abstract Builder clearAdditions(); + + /** + * Clears the collection of {@link RecordSet}s which are to be deleted from the zone upon + * executing this {@code ChangeRequestInfo}. + */ + public abstract Builder clearDeletions(); + + /** + * Removes a single {@link RecordSet} from the collection of records to be + * added to the zone upon executing this {@code ChangeRequestInfo}. + */ + public abstract Builder removeAddition(RecordSet recordSet); + + /** + * Removes a single {@link RecordSet} from the collection of records to be + * deleted from the zone upon executing this {@code ChangeRequestInfo}. + */ + public abstract Builder removeDeletion(RecordSet recordSet); + + /** + * Associates a service-generated id to this {@code ChangeRequestInfo}. + */ + abstract Builder generatedId(String generatedId); + + /** + * Sets the time when this change request was started by a server. + */ + abstract Builder startTimeMillis(long startTimeMillis); + + /** + * Sets the current status of this {@code ChangeRequest}. + */ + abstract Builder status(ChangeRequest.Status status); + + /** + * Creates a {@code ChangeRequestInfo} instance populated by the values associated with this + * builder. + */ + public abstract ChangeRequestInfo build(); + } + + static class BuilderImpl extends Builder { + private List additions; + private List deletions; + private String generatedId; + private Long startTimeMillis; + private ChangeRequestInfo.Status status; + + BuilderImpl() { + this.additions = new LinkedList<>(); + this.deletions = new LinkedList<>(); + } + + BuilderImpl(ChangeRequestInfo info) { + this.additions = Lists.newLinkedList(info.additions()); + this.deletions = Lists.newLinkedList(info.deletions()); + this.generatedId = info.generatedId; + this.startTimeMillis = info.startTimeMillis; + this.status = info.status; + } + + @Override + public Builder additions(List additions) { + this.additions = Lists.newLinkedList(checkNotNull(additions)); + return this; + } + + @Override + public Builder deletions(List deletions) { + this.deletions = Lists.newLinkedList(checkNotNull(deletions)); + return this; + } + + @Override + public Builder add(RecordSet recordSet) { + this.additions.add(checkNotNull(recordSet)); + return this; + } + + @Override + public Builder delete(RecordSet recordSet) { + this.deletions.add(checkNotNull(recordSet)); + return this; + } + + @Override + public Builder clearAdditions() { + this.additions.clear(); + return this; + } + + @Override + public Builder clearDeletions() { + this.deletions.clear(); + return this; + } + + @Override + public Builder removeAddition(RecordSet recordSet) { + this.additions.remove(recordSet); + return this; + } + + @Override + public Builder removeDeletion(RecordSet recordSet) { + this.deletions.remove(recordSet); + return this; + } + + @Override + public ChangeRequestInfo build() { + return new ChangeRequestInfo(this); + } + + @Override + Builder generatedId(String generatedId) { + this.generatedId = checkNotNull(generatedId); + return this; + } + + @Override + Builder startTimeMillis(long startTimeMillis) { + this.startTimeMillis = startTimeMillis; + return this; + } + + @Override + Builder status(ChangeRequestInfo.Status status) { + this.status = checkNotNull(status); + return this; + } + } + + ChangeRequestInfo(BuilderImpl builder) { + this.additions = ImmutableList.copyOf(builder.additions); + this.deletions = ImmutableList.copyOf(builder.deletions); + this.generatedId = builder.generatedId; + this.startTimeMillis = builder.startTimeMillis; + this.status = builder.status; + } + + /** + * Returns an empty builder for the {@code ChangeRequestInfo} class. + */ + public static Builder builder() { + return new BuilderImpl(); + } + + /** + * Creates a builder populated with values of this {@code ChangeRequestInfo}. + */ + public Builder toBuilder() { + return new BuilderImpl(this); + } + + /** + * Returns the list of {@link RecordSet}s to be added to the zone upon submitting this change + * request. + */ + public List additions() { + return additions; + } + + /** + * Returns the list of {@link RecordSet}s to be deleted from the zone upon submitting this change + * request. + */ + public List deletions() { + return deletions; + } + + /** + * Returns the service-generated id for this change request. + */ + public String generatedId() { + return generatedId; + } + + /** + * Returns the time when this change request was started by the server. + */ + public Long startTimeMillis() { + return startTimeMillis; + } + + /** + * Returns the status of this change request. If the change request has not been applied yet, the + * status is {@code PENDING}. + */ + public ChangeRequestInfo.Status status() { + return status; + } + + Change toPb() { + Change pb = new Change(); + // set id + if (generatedId() != null) { + pb.setId(generatedId()); + } + // set timestamp + if (startTimeMillis() != null) { + pb.setStartTime(ISODateTimeFormat.dateTime().withZoneUTC().print(startTimeMillis())); + } + // set status + if (status() != null) { + pb.setStatus(status().name().toLowerCase()); + } + // set a list of additions + pb.setAdditions(Lists.transform(additions(), RecordSet.TO_PB_FUNCTION)); + // set a list of deletions + pb.setDeletions(Lists.transform(deletions(), RecordSet.TO_PB_FUNCTION)); + return pb; + } + + static ChangeRequestInfo fromPb(Change pb) { + Builder builder = builder(); + if (pb.getId() != null) { + builder.generatedId(pb.getId()); + } + if (pb.getStartTime() != null) { + builder.startTimeMillis(DateTime.parse(pb.getStartTime()).getMillis()); + } + if (pb.getStatus() != null) { + // we are assuming that status indicated in pb is a lower case version of the enum name + builder.status(ChangeRequest.Status.valueOf(pb.getStatus().toUpperCase())); + } + if (pb.getDeletions() != null) { + builder.deletions(Lists.transform(pb.getDeletions(), RecordSet.FROM_PB_FUNCTION)); + } + if (pb.getAdditions() != null) { + builder.additions(Lists.transform(pb.getAdditions(), RecordSet.FROM_PB_FUNCTION)); + } + return builder.build(); + } + + @Override + public boolean equals(Object other) { + return other != null && other.getClass().equals(ChangeRequestInfo.class) + && other instanceof ChangeRequestInfo && toPb().equals(((ChangeRequestInfo) other).toPb()); + } + + @Override + public int hashCode() { + return Objects.hash(additions, deletions, generatedId, startTimeMillis, status); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("additions", additions) + .add("deletions", deletions) + .add("generatedId", generatedId) + .add("startTimeMillis", startTimeMillis) + .add("status", status) + .toString(); + } +} diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java index 6ce6b4c19994..2216733ca779 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java @@ -16,14 +16,14 @@ package com.google.gcloud.dns; -import com.google.common.base.Joiner; -import com.google.common.collect.Sets; +import com.google.common.collect.ImmutableList; +import com.google.gcloud.FieldSelector; +import com.google.gcloud.FieldSelector.Helper; import com.google.gcloud.Page; import com.google.gcloud.Service; import com.google.gcloud.dns.spi.DnsRpc; -import java.io.Serializable; -import java.util.Set; +import java.util.List; /** * An interface for the Google Cloud DNS service. @@ -39,29 +39,23 @@ public interface Dns extends Service { * {@link Dns#getProject(ProjectOption...)}. Project ID is always returned, even if not * specified. */ - enum ProjectField { + enum ProjectField implements FieldSelector { PROJECT_ID("id"), PROJECT_NUMBER("number"), QUOTA("quota"); + static final List REQUIRED_FIELDS = ImmutableList.of(PROJECT_ID); + private final String selector; ProjectField(String selector) { this.selector = selector; } - String selector() { + @Override + public String selector() { return selector; } - - static String selector(ProjectField... fields) { - Set fieldStrings = Sets.newHashSetWithExpectedSize(fields.length + 1); - fieldStrings.add(PROJECT_ID.selector()); - for (ProjectField field : fields) { - fieldStrings.add(field.selector()); - } - return Joiner.on(',').join(fieldStrings); - } } /** @@ -71,7 +65,7 @@ static String selector(ProjectField... fields) { * {@link Dns#getZone(String, ZoneOption...)}. The name is always returned, even if not * specified. */ - enum ZoneField { + enum ZoneField implements FieldSelector { CREATION_TIME("creationTime"), DESCRIPTION("description"), DNS_NAME("dnsName"), @@ -80,92 +74,73 @@ enum ZoneField { NAME_SERVER_SET("nameServerSet"), NAME_SERVERS("nameServers"); + static final List REQUIRED_FIELDS = ImmutableList.of(NAME); + private final String selector; ZoneField(String selector) { this.selector = selector; } - String selector() { + @Override + public String selector() { return selector; } - - static String selector(ZoneField... fields) { - Set fieldStrings = Sets.newHashSetWithExpectedSize(fields.length + 1); - fieldStrings.add(NAME.selector()); - for (ZoneField field : fields) { - fieldStrings.add(field.selector()); - } - return Joiner.on(',').join(fieldStrings); - } } /** - * The fields of a DNS record. + * The fields of a record set. * *

These values can be used to specify the fields to include in a partial response when calling - * {@link Dns#listDnsRecords(String, DnsRecordListOption...)}. The name and type are always + * {@link Dns#listRecordSets(String, RecordSetListOption...)}. The name and type are always * returned even if not selected. */ - enum DnsRecordField { + enum RecordSetField implements FieldSelector { DNS_RECORDS("rrdatas"), NAME("name"), TTL("ttl"), TYPE("type"); + static final List REQUIRED_FIELDS = ImmutableList.of(NAME, TYPE); + private final String selector; - DnsRecordField(String selector) { + RecordSetField(String selector) { this.selector = selector; } - String selector() { + @Override + public String selector() { return selector; } - - static String selector(DnsRecordField... fields) { - Set fieldStrings = Sets.newHashSetWithExpectedSize(fields.length + 1); - fieldStrings.add(NAME.selector()); - fieldStrings.add(TYPE.selector()); - for (DnsRecordField field : fields) { - fieldStrings.add(field.selector()); - } - return Joiner.on(',').join(fieldStrings); - } } /** * The fields of a change request. * *

These values can be used to specify the fields to include in a partial response when calling - * {@link Dns#applyChangeRequest(String, ChangeRequest, ChangeRequestOption...)} The ID is always - * returned even if not selected. + * {@link Dns#applyChangeRequest(String, ChangeRequestInfo, ChangeRequestOption...)} The ID is + * always returned even if not selected. */ - enum ChangeRequestField { + enum ChangeRequestField implements FieldSelector { ID("id"), START_TIME("startTime"), STATUS("status"), ADDITIONS("additions"), DELETIONS("deletions"); + static final List REQUIRED_FIELDS = ImmutableList.of(ID); + private final String selector; ChangeRequestField(String selector) { this.selector = selector; } - String selector() { + @Override + public String selector() { return selector; } - - static String selector(ChangeRequestField... fields) { - Set fieldStrings = Sets.newHashSetWithExpectedSize(fields.length + 1); - fieldStrings.add(ID.selector()); - for (ChangeRequestField field : fields) { - fieldStrings.add(field.selector()); - } - return Joiner.on(',').join(fieldStrings); - } } /** @@ -180,28 +155,27 @@ public String selector() { } /** - * Class that for specifying DNS record options. + * Class for specifying record set listing options. */ - class DnsRecordListOption extends AbstractOption implements Serializable { + class RecordSetListOption extends Option { private static final long serialVersionUID = 1009627025381096098L; - DnsRecordListOption(DnsRpc.Option option, Object value) { + RecordSetListOption(DnsRpc.Option option, Object value) { super(option, value); } /** - * Returns an option to specify the DNS record's fields to be returned by the RPC call. + * Returns an option to specify the record set's fields to be returned by the RPC call. * *

If this option is not provided all record fields are returned. {@code - * DnsRecordField.fields} can be used to specify only the fields of interest. The name of the - * DNS record always returned, even if not specified. {@link DnsRecordField} provides a list of - * fields that can be used. + * RecordSetField.fields} can be used to specify only the fields of interest. The name of the + * record set in always returned, even if not specified. {@link RecordSetField} provides a list + * of fields that can be used. */ - public static DnsRecordListOption fields(DnsRecordField... fields) { - StringBuilder builder = new StringBuilder(); - builder.append("nextPageToken,rrsets(").append(DnsRecordField.selector(fields)).append(')'); - return new DnsRecordListOption(DnsRpc.Option.FIELDS, builder.toString()); + public static RecordSetListOption fields(RecordSetField... fields) { + return new RecordSetListOption(DnsRpc.Option.FIELDS, + Helper.listSelector("rrsets", RecordSetField.REQUIRED_FIELDS, fields)); } /** @@ -210,40 +184,40 @@ public static DnsRecordListOption fields(DnsRecordField... fields) { *

The page token (returned from a previous call to list) indicates from where listing should * continue. */ - public static DnsRecordListOption pageToken(String pageToken) { - return new DnsRecordListOption(DnsRpc.Option.PAGE_TOKEN, pageToken); + public static RecordSetListOption pageToken(String pageToken) { + return new RecordSetListOption(DnsRpc.Option.PAGE_TOKEN, pageToken); } /** - * The maximum number of DNS records to return per RPC. + * The maximum number of record sets to return per RPC. * - *

The server can return fewer records than requested. When there are more results than the - * page size, the server will return a page token that can be used to fetch other results. + *

The server can return fewer record sets than requested. When there are more results than + * the page size, the server will return a page token that can be used to fetch other results. */ - public static DnsRecordListOption pageSize(int pageSize) { - return new DnsRecordListOption(DnsRpc.Option.PAGE_SIZE, pageSize); + public static RecordSetListOption pageSize(int pageSize) { + return new RecordSetListOption(DnsRpc.Option.PAGE_SIZE, pageSize); } /** - * Restricts the list to only DNS records with this fully qualified domain name. + * Restricts the list to only record sets with this fully qualified domain name. */ - public static DnsRecordListOption dnsName(String dnsName) { - return new DnsRecordListOption(DnsRpc.Option.NAME, dnsName); + public static RecordSetListOption dnsName(String dnsName) { + return new RecordSetListOption(DnsRpc.Option.NAME, dnsName); } /** - * Restricts the list to return only records of this type. If present, {@link - * Dns.DnsRecordListOption#dnsName(String)} must also be present. + * Restricts the list to return only record sets of this type. If present, {@link + * RecordSetListOption#dnsName(String)} must also be present. */ - public static DnsRecordListOption type(DnsRecord.Type type) { - return new DnsRecordListOption(DnsRpc.Option.DNS_TYPE, type.name()); + public static RecordSetListOption type(RecordSet.Type type) { + return new RecordSetListOption(DnsRpc.Option.DNS_TYPE, type.name()); } } /** * Class for specifying zone field options. */ - class ZoneOption extends AbstractOption implements Serializable { + class ZoneOption extends Option { private static final long serialVersionUID = -8065564464895945037L; @@ -259,14 +233,15 @@ class ZoneOption extends AbstractOption implements Serializable { * specified. {@link ZoneField} provides a list of fields that can be used. */ public static ZoneOption fields(ZoneField... fields) { - return new ZoneOption(DnsRpc.Option.FIELDS, ZoneField.selector(fields)); + return new ZoneOption(DnsRpc.Option.FIELDS, + Helper.selector(ZoneField.REQUIRED_FIELDS, fields)); } } /** * Class for specifying zone listing options. */ - class ZoneListOption extends AbstractOption implements Serializable { + class ZoneListOption extends Option { private static final long serialVersionUID = -2830645032124504717L; @@ -282,9 +257,8 @@ class ZoneListOption extends AbstractOption implements Serializable { * specified. {@link ZoneField} provides a list of fields that can be used. */ public static ZoneListOption fields(ZoneField... fields) { - StringBuilder builder = new StringBuilder(); - builder.append("nextPageToken,managedZones(").append(ZoneField.selector(fields)).append(')'); - return new ZoneListOption(DnsRpc.Option.FIELDS, builder.toString()); + return new ZoneListOption(DnsRpc.Option.FIELDS, + Helper.listSelector("managedZones", ZoneField.REQUIRED_FIELDS, fields)); } /** @@ -301,7 +275,6 @@ public static ZoneListOption pageToken(String pageToken) { * Restricts the list to only zone with this fully qualified domain name. */ public static ZoneListOption dnsName(String dnsName) { - StringBuilder builder = new StringBuilder(); return new ZoneListOption(DnsRpc.Option.DNS_NAME, dnsName); } @@ -319,7 +292,7 @@ public static ZoneListOption pageSize(int pageSize) { /** * Class for specifying project options. */ - class ProjectOption extends AbstractOption implements Serializable { + class ProjectOption extends Option { private static final long serialVersionUID = 6817937338218847748L; @@ -336,14 +309,15 @@ class ProjectOption extends AbstractOption implements Serializable { * can be used. */ public static ProjectOption fields(ProjectField... fields) { - return new ProjectOption(DnsRpc.Option.FIELDS, ProjectField.selector(fields)); + return new ProjectOption(DnsRpc.Option.FIELDS, + Helper.selector(ProjectField.REQUIRED_FIELDS, fields)); } } /** * Class for specifying change request field options. */ - class ChangeRequestOption extends AbstractOption implements Serializable { + class ChangeRequestOption extends Option { private static final long serialVersionUID = 1067273695061077782L; @@ -361,17 +335,15 @@ class ChangeRequestOption extends AbstractOption implements Serializable { * a list of fields that can be used. */ public static ChangeRequestOption fields(ChangeRequestField... fields) { - return new ChangeRequestOption( - DnsRpc.Option.FIELDS, - ChangeRequestField.selector(fields) - ); + return new ChangeRequestOption(DnsRpc.Option.FIELDS, + Helper.selector(ChangeRequestField.REQUIRED_FIELDS, fields)); } } /** * Class for specifying change request listing options. */ - class ChangeRequestListOption extends AbstractOption implements Serializable { + class ChangeRequestListOption extends Option { private static final long serialVersionUID = -900209143895376089L; @@ -389,10 +361,8 @@ class ChangeRequestListOption extends AbstractOption implements Serializable { * a list of fields that can be used. */ public static ChangeRequestListOption fields(ChangeRequestField... fields) { - StringBuilder builder = new StringBuilder(); - builder.append("nextPageToken,changes(").append(ChangeRequestField.selector(fields)) - .append(')'); - return new ChangeRequestListOption(DnsRpc.Option.FIELDS, builder.toString()); + return new ChangeRequestListOption(DnsRpc.Option.FIELDS, + Helper.listSelector("changes", ChangeRequestField.REQUIRED_FIELDS, fields)); } /** @@ -478,16 +448,16 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { boolean delete(String zoneName); // delete does not admit any options /** - * Lists the DNS records in the zone identified by name. + * Lists the record sets in the zone identified by name. * *

The fields to be returned, page size and page tokens can be specified using {@link - * DnsRecordListOption}s. + * RecordSetListOption}s. * * @throws DnsException upon failure or if the zone cannot be found * @see Cloud DNS * ResourceRecordSets: list */ - Page listDnsRecords(String zoneName, DnsRecordListOption... options); + Page listRecordSets(String zoneName, RecordSetListOption... options); /** * Retrieves the information about the current project. The returned fields can be optionally @@ -504,10 +474,10 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { * servers. The fields to be returned can be selected by {@link ChangeRequestOption}s. * * @return the new {@link ChangeRequest} - * @throws DnsException upon failure if zone is not found + * @throws DnsException upon failure or if zone is not found * @see Cloud DNS Changes: create */ - ChangeRequest applyChangeRequest(String zoneName, ChangeRequest changeRequest, + ChangeRequest applyChangeRequest(String zoneName, ChangeRequestInfo changeRequest, ChangeRequestOption... options); /** diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java index a60cfd9151da..3218daa543b2 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java @@ -17,12 +17,11 @@ package com.google.gcloud.dns; import static com.google.common.base.Preconditions.checkArgument; -import static com.google.gcloud.RetryHelper.RetryHelperException; import static com.google.gcloud.RetryHelper.runWithRetries; -import static com.google.gcloud.dns.ChangeRequest.fromPb; import com.google.api.services.dns.model.Change; import com.google.api.services.dns.model.ManagedZone; +import com.google.api.services.dns.model.Project; import com.google.api.services.dns.model.ResourceRecordSet; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; @@ -85,7 +84,7 @@ public Page nextPage() { } } - private static class DnsRecordPageFetcher implements PageImpl.NextPageFetcher { + private static class DnsRecordPageFetcher implements PageImpl.NextPageFetcher { private static final long serialVersionUID = -6039369212511530846L; private final Map requestOptions; @@ -101,8 +100,8 @@ private static class DnsRecordPageFetcher implements PageImpl.NextPageFetcher nextPage() { - return listDnsRecords(zoneName, serviceOptions, requestOptions); + public Page nextPage() { + return listRecordSets(zoneName, serviceOptions, requestOptions); } } @@ -122,8 +121,7 @@ private static Page listZones(final DnsOptions serviceOptions, // this differs from the other list operations since zone is functional and requires dns service Function pbToZoneFunction = new Function() { @Override - public Zone apply( - com.google.api.services.dns.model.ManagedZone zonePb) { + public Zone apply(ManagedZone zonePb) { return Zone.fromPb(serviceOptions.service(), zonePb); } }; @@ -143,7 +141,7 @@ public DnsRpc.ListResult call() { ? ImmutableList.of() : Iterables.transform(result.results(), pbToZoneFunction); return new PageImpl<>(new ZonePageFetcher(serviceOptions, cursor, optionsMap), cursor, zones); - } catch (RetryHelperException e) { + } catch (RetryHelper.RetryHelperException e) { throw DnsException.translateAndThrow(e); } } @@ -169,39 +167,40 @@ public DnsRpc.ListResult call() { // transform that list into change request objects Iterable changes = result.results() == null ? ImmutableList.of() - : Iterables.transform(result.results(), ChangeRequest.FROM_PB_FUNCTION); + : Iterables.transform(result.results(), + ChangeRequest.fromPbFunction(serviceOptions.service(), zoneName)); return new PageImpl<>(new ChangeRequestPageFetcher(zoneName, serviceOptions, cursor, optionsMap), cursor, changes); - } catch (RetryHelperException e) { + } catch (RetryHelper.RetryHelperException e) { throw DnsException.translateAndThrow(e); } } @Override - public Page listDnsRecords(String zoneName, DnsRecordListOption... options) { - return listDnsRecords(zoneName, options(), optionMap(options)); + public Page listRecordSets(String zoneName, RecordSetListOption... options) { + return listRecordSets(zoneName, options(), optionMap(options)); } - private static Page listDnsRecords(final String zoneName, + private static Page listRecordSets(final String zoneName, final DnsOptions serviceOptions, final Map optionsMap) { try { - // get a list of resource record sets + // get a list of record sets final DnsRpc rpc = serviceOptions.rpc(); DnsRpc.ListResult result = runWithRetries( new Callable>() { @Override public DnsRpc.ListResult call() { - return rpc.listDnsRecords(zoneName, optionsMap); + return rpc.listRecordSets(zoneName, optionsMap); } }, serviceOptions.retryParams(), EXCEPTION_HANDLER); String cursor = result.pageToken(); - // transform that list into dns records - Iterable records = result.results() == null - ? ImmutableList.of() - : Iterables.transform(result.results(), DnsRecord.FROM_PB_FUNCTION); + // transform that list into record sets + Iterable recordSets = result.results() == null + ? ImmutableList.of() + : Iterables.transform(result.results(), RecordSet.FROM_PB_FUNCTION); return new PageImpl<>(new DnsRecordPageFetcher(zoneName, serviceOptions, cursor, optionsMap), - cursor, records); - } catch (RetryHelperException e) { + cursor, recordSets); + } catch (RetryHelper.RetryHelperException e) { throw DnsException.translateAndThrow(e); } } @@ -210,10 +209,10 @@ public DnsRpc.ListResult call() { public Zone create(final ZoneInfo zoneInfo, Dns.ZoneOption... options) { final Map optionsMap = optionMap(options); try { - com.google.api.services.dns.model.ManagedZone answer = runWithRetries( - new Callable() { + ManagedZone answer = runWithRetries( + new Callable() { @Override - public com.google.api.services.dns.model.ManagedZone call() { + public ManagedZone call() { return dnsRpc.create(zoneInfo.toPb(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER); @@ -227,10 +226,10 @@ public com.google.api.services.dns.model.ManagedZone call() { public Zone getZone(final String zoneName, Dns.ZoneOption... options) { final Map optionsMap = optionMap(options); try { - com.google.api.services.dns.model.ManagedZone answer = runWithRetries( - new Callable() { + ManagedZone answer = runWithRetries( + new Callable() { @Override - public com.google.api.services.dns.model.ManagedZone call() { + public ManagedZone call() { return dnsRpc.getZone(zoneName, optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER); @@ -258,10 +257,10 @@ public Boolean call() { public ProjectInfo getProject(Dns.ProjectOption... fields) { final Map optionsMap = optionMap(fields); try { - com.google.api.services.dns.model.Project answer = runWithRetries( - new Callable() { + Project answer = runWithRetries( + new Callable() { @Override - public com.google.api.services.dns.model.Project call() { + public Project call() { return dnsRpc.getProject(optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER); @@ -272,19 +271,18 @@ public com.google.api.services.dns.model.Project call() { } @Override - public ChangeRequest applyChangeRequest(final String zoneName, final ChangeRequest changeRequest, - Dns.ChangeRequestOption... options) { + public ChangeRequest applyChangeRequest(final String zoneName, + final ChangeRequestInfo changeRequest, ChangeRequestOption... options) { final Map optionsMap = optionMap(options); try { - com.google.api.services.dns.model.Change answer = - runWithRetries( - new Callable() { - @Override - public com.google.api.services.dns.model.Change call() { - return dnsRpc.applyChangeRequest(zoneName, changeRequest.toPb(), optionsMap); - } - }, options().retryParams(), EXCEPTION_HANDLER); - return answer == null ? null : fromPb(answer); // should never be null + Change answer = runWithRetries( + new Callable() { + @Override + public Change call() { + return dnsRpc.applyChangeRequest(zoneName, changeRequest.toPb(), optionsMap); + } + }, options().retryParams(), EXCEPTION_HANDLER); + return answer == null ? null : ChangeRequest.fromPb(this, zoneName, answer); // not null } catch (RetryHelper.RetryHelperException ex) { throw DnsException.translateAndThrow(ex); } @@ -295,23 +293,22 @@ public ChangeRequest getChangeRequest(final String zoneName, final String change Dns.ChangeRequestOption... options) { final Map optionsMap = optionMap(options); try { - com.google.api.services.dns.model.Change answer = - runWithRetries( - new Callable() { - @Override - public com.google.api.services.dns.model.Change call() { - return dnsRpc.getChangeRequest(zoneName, changeRequestId, optionsMap); - } - }, options().retryParams(), EXCEPTION_HANDLER); - return answer == null ? null : fromPb(answer); + Change answer = runWithRetries( + new Callable() { + @Override + public Change call() { + return dnsRpc.getChangeRequest(zoneName, changeRequestId, optionsMap); + } + }, options().retryParams(), EXCEPTION_HANDLER); + return answer == null ? null : ChangeRequest.fromPb(this, zoneName, answer); } catch (RetryHelper.RetryHelperException ex) { throw DnsException.translateAndThrow(ex); } } - private Map optionMap(AbstractOption... options) { + private Map optionMap(Option... options) { Map temp = Maps.newEnumMap(DnsRpc.Option.class); - for (AbstractOption option : options) { + for (Option option : options) { Object prev = temp.put(option.rpcOption(), option.value()); checkArgument(prev == null, "Duplicate option %s", option); } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/AbstractOption.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Option.java similarity index 88% rename from gcloud-java-dns/src/main/java/com/google/gcloud/dns/AbstractOption.java rename to gcloud-java-dns/src/main/java/com/google/gcloud/dns/Option.java index e12f7412e687..fee99898fb24 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/AbstractOption.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Option.java @@ -27,13 +27,13 @@ /** * A base class for options. */ -abstract class AbstractOption implements Serializable { +abstract class Option implements Serializable { private static final long serialVersionUID = -5912727967831484228L; private final Object value; private final DnsRpc.Option rpcOption; - AbstractOption(DnsRpc.Option rpcOption, Object value) { + Option(DnsRpc.Option rpcOption, Object value) { this.rpcOption = checkNotNull(rpcOption); this.value = value; } @@ -48,10 +48,10 @@ DnsRpc.Option rpcOption() { @Override public boolean equals(Object obj) { - if (!(obj instanceof AbstractOption)) { + if (!(obj instanceof Option)) { return false; } - AbstractOption other = (AbstractOption) obj; + Option other = (Option) obj; return Objects.equals(value, other.value) && Objects.equals(rpcOption, other.rpcOption); } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java index f7b12b94bae8..52edb25ec902 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java @@ -18,6 +18,7 @@ import static com.google.api.client.repackaged.com.google.common.base.Preconditions.checkNotNull; +import com.google.api.services.dns.model.Project; import com.google.common.base.MoreObjects; import java.io.Serializable; @@ -26,8 +27,8 @@ /** * The class provides the Google Cloud DNS information associated with this project. A project is a - * top level container for resources including {@code Zone}s. Projects can be created only in - * the APIs console. + * top level container for resources including {@code Zone}s. Projects can be created only in the + * APIs console. * * @see Google Cloud DNS documentation */ @@ -62,11 +63,11 @@ public static class Quota implements Serializable { * builder. */ Quota(int zones, - int resourceRecordsPerRrset, - int rrsetAdditionsPerChange, - int rrsetDeletionsPerChange, - int rrsetsPerZone, - int totalRrdataSizePerChange) { + int resourceRecordsPerRrset, + int rrsetAdditionsPerChange, + int rrsetDeletionsPerChange, + int rrsetsPerZone, + int totalRrdataSizePerChange) { this.zones = zones; this.resourceRecordsPerRrset = resourceRecordsPerRrset; this.rrsetAdditionsPerChange = rrsetAdditionsPerChange; @@ -83,21 +84,22 @@ public int zones() { } /** - * Returns the maximum allowed number of records per {@link DnsRecord}. + * Returns the maximum allowed number of records per {@link RecordSet}. */ public int resourceRecordsPerRrset() { return resourceRecordsPerRrset; } /** - * Returns the maximum allowed number of {@link DnsRecord}s to add per {@link ChangeRequest}. + * Returns the maximum allowed number of {@link RecordSet}s to add per {@link + * ChangeRequest}. */ public int rrsetAdditionsPerChange() { return rrsetAdditionsPerChange; } /** - * Returns the maximum allowed number of {@link DnsRecord}s to delete per {@link + * Returns the maximum allowed number of {@link RecordSet}s to delete per {@link * ChangeRequest}. */ public int rrsetDeletionsPerChange() { @@ -105,7 +107,7 @@ public int rrsetDeletionsPerChange() { } /** - * Returns the maximum allowed number of {@link DnsRecord}s per {@link ZoneInfo} in the + * Returns the maximum allowed number of {@link RecordSet}s per {@link ZoneInfo} in the * project. */ public int rrsetsPerZone() { @@ -142,14 +144,13 @@ com.google.api.services.dns.model.Quota toPb() { } static Quota fromPb(com.google.api.services.dns.model.Quota pb) { - Quota quota = new Quota(pb.getManagedZones(), + return new Quota(pb.getManagedZones(), pb.getResourceRecordsPerRrset(), pb.getRrsetAdditionsPerChange(), pb.getRrsetDeletionsPerChange(), pb.getRrsetsPerManagedZone(), pb.getTotalRrdataSizePerChange() ); - return quota; } @Override @@ -242,8 +243,8 @@ String id() { return id; } - com.google.api.services.dns.model.Project toPb() { - com.google.api.services.dns.model.Project pb = new com.google.api.services.dns.model.Project(); + Project toPb() { + Project pb = new Project(); pb.setId(id); pb.setNumber(number); if (this.quota != null) { @@ -252,7 +253,7 @@ com.google.api.services.dns.model.Project toPb() { return pb; } - static ProjectInfo fromPb(com.google.api.services.dns.model.Project pb) { + static ProjectInfo fromPb(Project pb) { Builder builder = builder(); if (pb.getId() != null) { builder.id(pb.getId()); diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/RecordSet.java similarity index 80% rename from gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java rename to gcloud-java-dns/src/main/java/com/google/gcloud/dns/RecordSet.java index c4e710bd0365..90beedba1d89 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/RecordSet.java @@ -35,28 +35,28 @@ /** * A class that represents a Google Cloud DNS record set. * - *

A {@code DnsRecord} is the unit of data that will be returned by the DNS servers upon a DNS - * request for a specific domain. The {@code DnsRecord} holds the current state of the DNS records + *

A {@code RecordSet} is the unit of data that will be returned by the DNS servers upon a DNS + * request for a specific domain. The {@code RecordSet} holds the current state of the DNS records * that make up a zone. You can read the records but you cannot modify them directly. Rather, you - * edit the records in a zone by creating a ChangeRequest. + * edit the records in a zone by creating a {@link ChangeRequest}. * * @see Google Cloud DNS * documentation */ -public class DnsRecord implements Serializable { +public class RecordSet implements Serializable { - static final Function FROM_PB_FUNCTION = - new Function() { + static final Function FROM_PB_FUNCTION = + new Function() { @Override - public DnsRecord apply(com.google.api.services.dns.model.ResourceRecordSet pb) { - return DnsRecord.fromPb(pb); + public RecordSet apply(ResourceRecordSet pb) { + return RecordSet.fromPb(pb); } }; - static final Function TO_PB_FUNCTION = - new Function() { + static final Function TO_PB_FUNCTION = + new Function() { @Override - public com.google.api.services.dns.model.ResourceRecordSet apply(DnsRecord error) { - return error.toPb(); + public ResourceRecordSet apply(RecordSet recordSet) { + return recordSet.toPb(); } }; private static final long serialVersionUID = 8148009870800115261L; @@ -124,7 +124,7 @@ public enum Type { } /** - * A builder of {@link DnsRecord}. + * A builder for {@link RecordSet}. */ public static class Builder { @@ -140,9 +140,9 @@ private Builder(String name, Type type) { /** * Creates a builder and pre-populates attributes with the values from the provided {@code - * DnsRecord} instance. + * RecordSet} instance. */ - private Builder(DnsRecord record) { + private Builder(RecordSet record) { this.name = record.name; this.ttl = record.ttl; this.type = record.type; @@ -186,7 +186,7 @@ public Builder records(List records) { } /** - * Sets name for this DNS record set. For example, www.example.com. + * Sets the name for this record set. For example, www.example.com. */ public Builder name(String name) { this.name = checkNotNull(name); @@ -198,7 +198,7 @@ public Builder name(String name) { * The maximum duration must be equivalent to at most {@link Integer#MAX_VALUE} seconds. * * @param duration A non-negative number of time units - * @param unit The unit of the ttl parameter + * @param unit The unit of the ttl parameter */ public Builder ttl(int duration, TimeUnit unit) { checkArgument(duration >= 0, @@ -219,14 +219,14 @@ public Builder type(Type type) { } /** - * Builds the DNS record. + * Builds the record set. */ - public DnsRecord build() { - return new DnsRecord(this); + public RecordSet build() { + return new RecordSet(this); } } - private DnsRecord(Builder builder) { + private RecordSet(Builder builder) { this.name = builder.name; this.rrdatas = ImmutableList.copyOf(builder.rrdatas); this.ttl = builder.ttl; @@ -241,35 +241,35 @@ public Builder toBuilder() { } /** - * Creates a {@code DnsRecord} builder for the given {@code name} and {@code type}. + * Creates a {@code RecordSet} builder for the given {@code name} and {@code type}. */ public static Builder builder(String name, Type type) { return new Builder(name, type); } /** - * Returns the user-assigned name of this DNS record. + * Returns the user-assigned name of this record set. */ public String name() { return name; } /** - * Returns a list of DNS record stored in this record set. + * Returns a list of records stored in this record set. */ public List records() { return rrdatas; } /** - * Returns the number of seconds that this DnsResource can be cached by resolvers. + * Returns the number of seconds that this record set can be cached by resolvers. */ public Integer ttl() { return ttl; } /** - * Returns the type of this DNS record. + * Returns the type of this record set. */ public Type type() { return type; @@ -282,12 +282,11 @@ public int hashCode() { @Override public boolean equals(Object obj) { - return (obj instanceof DnsRecord) && Objects.equals(this.toPb(), ((DnsRecord) obj).toPb()); + return obj instanceof RecordSet && Objects.equals(this.toPb(), ((RecordSet) obj).toPb()); } - com.google.api.services.dns.model.ResourceRecordSet toPb() { - com.google.api.services.dns.model.ResourceRecordSet pb = - new com.google.api.services.dns.model.ResourceRecordSet(); + ResourceRecordSet toPb() { + ResourceRecordSet pb = new ResourceRecordSet(); pb.setName(this.name()); pb.setRrdatas(this.records()); pb.setTtl(this.ttl()); @@ -295,7 +294,7 @@ com.google.api.services.dns.model.ResourceRecordSet toPb() { return pb; } - static DnsRecord fromPb(com.google.api.services.dns.model.ResourceRecordSet pb) { + static RecordSet fromPb(ResourceRecordSet pb) { Builder builder = builder(pb.getName(), Type.valueOf(pb.getType())); if (pb.getRrdatas() != null) { builder.records(pb.getRrdatas()); diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java index 41507647543a..c4250bd206eb 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java @@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkNotNull; +import com.google.api.services.dns.model.ManagedZone; import com.google.gcloud.Page; import java.io.IOException; @@ -28,10 +29,10 @@ /** * A Google Cloud DNS Zone object. * - *

A zone is the container for all of your DNS records that share the same DNS name prefix, for + *

A zone is the container for all of your record sets that share the same DNS name prefix, for * example, example.com. Zones are automatically assigned a set of name servers when they are * created to handle responding to DNS queries for that zone. A zone has quotas for the number of - * resource records that it can include. + * record sets that it can include. * * @see Google Cloud DNS managed zone * documentation @@ -61,8 +62,8 @@ public Builder name(String name) { } @Override - Builder id(String id) { - infoBuilder.id(id); + Builder generatedId(String generatedId) { + infoBuilder.generatedId(generatedId); return this; } @@ -135,25 +136,25 @@ public boolean delete() { } /** - * Lists all {@link DnsRecord}s associated with this zone. The method searches for zone by name. + * Lists all {@link RecordSet}s associated with this zone. The method searches for zone by name. * - * @param options optional restriction on listing and fields of {@link DnsRecord}s returned - * @return a page of DNS records + * @param options optional restriction on listing and fields of {@link RecordSet}s returned + * @return a page of record sets * @throws DnsException upon failure or if the zone is not found */ - public Page listDnsRecords(Dns.DnsRecordListOption... options) { - return dns.listDnsRecords(name(), options); + public Page listRecordSets(Dns.RecordSetListOption... options) { + return dns.listRecordSets(name(), options); } /** - * Submits {@link ChangeRequest} to the service for it to applied to this zone. The method + * Submits {@link ChangeRequestInfo} to the service for it to applied to this zone. The method * searches for zone by name. * * @param options optional restriction on what fields of {@link ChangeRequest} should be returned * @return ChangeRequest with server-assigned ID * @throws DnsException upon failure or if the zone is not found */ - public ChangeRequest applyChangeRequest(ChangeRequest changeRequest, + public ChangeRequest applyChangeRequest(ChangeRequestInfo changeRequest, Dns.ChangeRequestOption... options) { checkNotNull(changeRequest); return dns.applyChangeRequest(name(), changeRequest, options); @@ -205,12 +206,12 @@ public int hashCode() { return Objects.hash(super.hashCode(), options); } - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); + private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { + stream.defaultReadObject(); this.dns = options.service(); } - static Zone fromPb(Dns dns, com.google.api.services.dns.model.ManagedZone zone) { + static Zone fromPb(Dns dns, ManagedZone zone) { ZoneInfo info = ZoneInfo.fromPb(zone); return new Zone(dns, new ZoneInfo.BuilderImpl(info)); } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java index 38a88b67777e..03c23a6ce3d3 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java @@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkNotNull; +import com.google.api.services.dns.model.ManagedZone; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; @@ -38,9 +39,9 @@ */ public class ZoneInfo implements Serializable { - private static final long serialVersionUID = 201601191647L; + private static final long serialVersionUID = -5313169712036079818L; private final String name; - private final String id; + private final String generatedId; private final Long creationTimeMillis; private final String dnsName; private final String description; @@ -57,9 +58,9 @@ public abstract static class Builder { public abstract Builder name(String name); /** - * Sets an id for the zone which is assigned to the zone by the server. + * Sets service-generated id for the zone. */ - abstract Builder id(String id); + abstract Builder generatedId(String generatedId); /** * Sets the time when this zone was created. @@ -98,7 +99,7 @@ public abstract static class Builder { static class BuilderImpl extends Builder { private String name; - private String id; + private String generatedId; private Long creationTimeMillis; private String dnsName; private String description; @@ -114,7 +115,7 @@ private BuilderImpl(String name) { */ BuilderImpl(ZoneInfo info) { this.name = info.name; - this.id = info.id; + this.generatedId = info.generatedId; this.creationTimeMillis = info.creationTimeMillis; this.dnsName = info.dnsName; this.description = info.description; @@ -131,8 +132,8 @@ public Builder name(String name) { } @Override - Builder id(String id) { - this.id = id; + Builder generatedId(String generatedId) { + this.generatedId = generatedId; return this; } @@ -175,7 +176,7 @@ public ZoneInfo build() { ZoneInfo(BuilderImpl builder) { this.name = builder.name; - this.id = builder.id; + this.generatedId = builder.generatedId; this.creationTimeMillis = builder.creationTimeMillis; this.dnsName = builder.dnsName; this.description = builder.description; @@ -199,10 +200,10 @@ public String name() { } /** - * Returns the read-only zone id assigned by the server. + * Returns the service-generated id for this zone. */ - public String id() { - return id; + public String generatedId() { + return generatedId; } /** @@ -248,13 +249,13 @@ public Builder toBuilder() { return new BuilderImpl(this); } - com.google.api.services.dns.model.ManagedZone toPb() { - com.google.api.services.dns.model.ManagedZone pb = - new com.google.api.services.dns.model.ManagedZone(); + ManagedZone toPb() { + ManagedZone pb = + new ManagedZone(); pb.setDescription(this.description()); pb.setDnsName(this.dnsName()); - if (this.id() != null) { - pb.setId(new BigInteger(this.id())); + if (this.generatedId() != null) { + pb.setId(new BigInteger(this.generatedId())); } pb.setName(this.name()); pb.setNameServers(this.nameServers); // do use real attribute value which may be null @@ -267,7 +268,7 @@ com.google.api.services.dns.model.ManagedZone toPb() { return pb; } - static ZoneInfo fromPb(com.google.api.services.dns.model.ManagedZone pb) { + static ZoneInfo fromPb(ManagedZone pb) { Builder builder = new BuilderImpl(pb.getName()); if (pb.getDescription() != null) { builder.description(pb.getDescription()); @@ -276,7 +277,7 @@ static ZoneInfo fromPb(com.google.api.services.dns.model.ManagedZone pb) { builder.dnsName(pb.getDnsName()); } if (pb.getId() != null) { - builder.id(pb.getId().toString()); + builder.generatedId(pb.getId().toString()); } if (pb.getNameServers() != null) { builder.nameServers(pb.getNameServers()); @@ -298,15 +299,15 @@ public boolean equals(Object obj) { @Override public int hashCode() { - return Objects.hash(name, id, creationTimeMillis, dnsName, - description, nameServerSet, nameServers); + return Objects.hash(name, generatedId, creationTimeMillis, dnsName, description, nameServerSet, + nameServers); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("name", name()) - .add("id", id()) + .add("generatedId", generatedId()) .add("description", description()) .add("dnsName", dnsName()) .add("nameServerSet", nameServerSet()) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/package-info.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/package-info.java index 8a137285c357..36f41852400c 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/package-info.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/package-info.java @@ -42,11 +42,11 @@ * String zoneName = "my-unique-zone"; * Zone zone = dns.getZone(zoneName); * String ip = "12.13.14.15"; - * DnsRecord toCreate = DnsRecord.builder("www.someexampledomain.com.", DnsRecord.Type.A) + * RecordSet toCreate = RecordSet.builder("www.someexampledomain.com.", RecordSet.Type.A) * .ttl(24, TimeUnit.HOURS) * .addRecord(ip) * .build(); - * ChangeRequest changeRequest = ChangeRequest.builder().add(toCreate).build(); + * ChangeRequestInfo changeRequest = ChangeRequestInfo.builder().add(toCreate).build(); * zone.applyChangeRequest(changeRequest); * } * diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DefaultDnsRpc.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DefaultDnsRpc.java index f8b8adb87ada..cbebd19d0d73 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DefaultDnsRpc.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DefaultDnsRpc.java @@ -112,7 +112,7 @@ public boolean deleteZone(String zoneName) throws DnsException { } @Override - public ListResult listDnsRecords(String zoneName, Map options) + public ListResult listRecordSets(String zoneName, Map options) throws DnsException { // options are fields, page token, dns name, type try { diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DnsRpc.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DnsRpc.java index bde93b99bfdd..c7478016db27 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DnsRpc.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DnsRpc.java @@ -120,13 +120,13 @@ public String pageToken() { boolean deleteZone(String zoneName) throws DnsException; /** - * Lists DNS records for a given zone. + * Lists record sets for a given zone. * * @param zoneName name of the zone to be listed * @param options a map of options for the service call * @throws DnsException upon failure or if zone was not found */ - ListResult listDnsRecords(String zoneName, Map options) + ListResult listRecordSets(String zoneName, Map options) throws DnsException; /** diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/LocalDnsHelper.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/LocalDnsHelper.java index 3b18ec5ce55b..54edcddb5ade 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/LocalDnsHelper.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/LocalDnsHelper.java @@ -90,8 +90,8 @@ * privileges to manipulate any project. Similarly, the local simulation does not require * verification of domain name ownership. Any request for creating a managed zone will be approved. * The mock does not track quota and will allow the user to exceed it. The mock provides only basic - * validation of the DNS data for records of type A and AAAA. It does not validate any other record - * types. + * validation of the DNS data for record sets of type A and AAAA. It does not validate any other + * record set types. */ public class LocalDnsHelper { @@ -122,7 +122,7 @@ public class LocalDnsHelper { } } - private long delayChange; + private final long delayChange; private final HttpServer server; private final int port; @@ -140,8 +140,8 @@ private enum CallRegex { PROJECT_GET("GET", CONTEXT + "/[^/]+"), RECORD_LIST("GET", CONTEXT + "/[^/]+/managedZones/[^/]+/rrsets"); - private String method; - private String pathRegex; + private final String method; + private final String pathRegex; CallRegex(String method, String pathRegex) { this.pathRegex = pathRegex; @@ -382,7 +382,7 @@ ConcurrentSkipListMap projects() { } /** - * Creates new {@link LocalDnsHelper} instance that listens to requests on the local machine. This + * Creates new {@code LocalDnsHelper} instance that listens to requests on the local machine. This * instance processes changes in separate thread. The parameter determines how long a thread * should wait before processing a change. If it is set to 0, the threading is turned off and the * mock will behave synchronously. @@ -470,7 +470,7 @@ static Response toListResponse(List serializedObjects, String context, S } /** - * Prepares DNS records that are created by default for each zone. + * Prepares record sets that are created by default for each zone. */ private static ImmutableSortedMap defaultRecords(ManagedZone zone) { ResourceRecordSet soa = new ResourceRecordSet(); @@ -508,7 +508,7 @@ static List randomNameservers() { } /** - * Returns a hex string id (used for a dns record) unique within the set of ids. + * Returns a hex string id (used for a record set) unique within the set of ids. */ @VisibleForTesting static String getUniqueId(Set ids) { @@ -521,14 +521,14 @@ static String getUniqueId(Set ids) { } /** - * Tests if a DNS record matches name and type (if provided). Used for filtering. + * Tests if a record set matches name and type (if provided). Used for filtering. */ @VisibleForTesting - static boolean matchesCriteria(ResourceRecordSet record, String name, String type) { - if (type != null && !record.getType().equals(type)) { + static boolean matchesCriteria(ResourceRecordSet recordSet, String name, String type) { + if (type != null && !recordSet.getType().equals(type)) { return false; } - return name == null || record.getName().equals(name); + return name == null || recordSet.getName().equals(name); } /** @@ -871,7 +871,7 @@ Response listZones(String projectId, String query) { } /** - * Lists DNS records for a zone. Next page token is the ID of the last record listed. + * Lists record sets for a zone. Next page token is the ID of the last record listed. */ @VisibleForTesting Response listDnsRecords(String projectId, String zoneName, String query) { @@ -898,18 +898,18 @@ Response listDnsRecords(String projectId, String zoneName, String query) { boolean hasMorePages = false; LinkedList serializedRrsets = new LinkedList<>(); String lastRecordId = null; - for (String recordId : fragment.keySet()) { - ResourceRecordSet record = fragment.get(recordId); - if (matchesCriteria(record, name, type)) { + for (String recordSetId : fragment.keySet()) { + ResourceRecordSet recordSet = fragment.get(recordSetId); + if (matchesCriteria(recordSet, name, type)) { if (sizeReached) { // we do not add this, just note that there would be more and there should be a token hasMorePages = true; break; } else { - lastRecordId = recordId; + lastRecordId = recordSetId; try { serializedRrsets.addLast(jsonFactory.toString( - OptionParsers.extractFields(record, fields))); + OptionParsers.extractFields(recordSet, fields))); } catch (IOException e) { return Error.INTERNAL_ERROR.response(String.format( "Error when serializing resource record set in managed zone %s in project %s", @@ -1128,8 +1128,8 @@ static Response checkRrset(ResourceRecordSet rrset, ZoneContainer zone, int inde } /** - * Checks against duplicate additions (for each record to be added that already exists, we must - * have a matching deletion. Furthermore, check that mandatory SOA and NS records stay. + * Checks against duplicate additions (for each record set to be added that already exists, we + * must have a matching deletion. Furthermore, check that mandatory SOA and NS records stay. */ static Response checkAdditionsDeletions(List additions, List deletions, ZoneContainer zone) { @@ -1139,7 +1139,7 @@ static Response checkAdditionsDeletions(List additions, for (ResourceRecordSet wrappedRrset : zone.dnsRecords().get().values()) { if (rrset.getName().equals(wrappedRrset.getName()) && rrset.getType().equals(wrappedRrset.getType()) - // such a record exist and we must have a deletion + // such a record set exists and we must have a deletion && (deletions == null || !deletions.contains(wrappedRrset))) { return Error.ALREADY_EXISTS.response(String.format( "The 'entity.change.additions[%s]' resource named '%s (%s)' already exists.", @@ -1181,10 +1181,10 @@ static Response checkAdditionsDeletions(List additions, /** * Helper for searching rrsets in a collection. */ - private static ResourceRecordSet findByNameAndType(Iterable records, + private static ResourceRecordSet findByNameAndType(Iterable recordSets, String name, String type) { - if (records != null) { - for (ResourceRecordSet rrset : records) { + if (recordSets != null) { + for (ResourceRecordSet rrset : recordSets) { if ((name == null || name.equals(rrset.getName())) && (type == null || type.equals(rrset.getType()))) { return rrset; @@ -1195,7 +1195,7 @@ private static ResourceRecordSet findByNameAndType(Iterable r } /** - * We only provide the most basic validation for A and AAAA records. + * We only provide the most basic validation for A and AAAA record sets. */ static boolean checkRrData(String data, String type) { switch (type) { @@ -1233,7 +1233,7 @@ static Response checkListOptions(Map options) { return Error.INVALID.response(String.format( "Invalid value for 'parameters.dnsName': '%s'", dnsName)); } - // for listing dns records, name must be fully qualified + // for listing record sets, name must be fully qualified String name = (String) options.get("name"); if (name != null && !name.endsWith(".")) { return Error.INVALID.response(String.format( diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/OptionParsers.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/OptionParsers.java index ecd7e8179efe..bd773a931ef2 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/OptionParsers.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/OptionParsers.java @@ -29,6 +29,9 @@ */ class OptionParsers { + private OptionParsers() { + } + static Map parseListZonesOptions(String query) { Map options = new HashMap<>(); if (query != null) { @@ -166,26 +169,26 @@ static ResourceRecordSet extractFields(ResourceRecordSet fullRecord, String... f if (fields == null || fields.length == 0) { return fullRecord; } - ResourceRecordSet record = new ResourceRecordSet(); + ResourceRecordSet recordSet = new ResourceRecordSet(); for (String field : fields) { switch (field) { case "name": - record.setName(fullRecord.getName()); + recordSet.setName(fullRecord.getName()); break; case "rrdatas": - record.setRrdatas(fullRecord.getRrdatas()); + recordSet.setRrdatas(fullRecord.getRrdatas()); break; case "type": - record.setType(fullRecord.getType()); + recordSet.setType(fullRecord.getType()); break; case "ttl": - record.setTtl(fullRecord.getTtl()); + recordSet.setTtl(fullRecord.getTtl()); break; default: break; } } - return record; + return recordSet; } static Map parseListChangesOptions(String query) { diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/package-info.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/package-info.java new file mode 100644 index 000000000000..a0a0c593c2b7 --- /dev/null +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/package-info.java @@ -0,0 +1,36 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A testing helper for Google Cloud DNS. + * + *

A simple usage example: + * Before the test: + *

 {@code
+ * // Minimum delay before processing change requests (in ms). Setting the delay to 0 makes change
+ * // request processing synchronous.
+ * long delay = 0;
+ * LocalDnsHelper dnsHelper = LocalDnsHelper.create(delay);
+ * Dns dns = dnsHelper.options().service();
+ * dnsHelper.start();
+ * }
+ * + *

After the test: + *

 {@code
+ * dnsHelper.stop();
+ * }
+ */ +package com.google.gcloud.dns.testing; diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestInfoTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestInfoTest.java new file mode 100644 index 000000000000..136a6e0d56ec --- /dev/null +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestInfoTest.java @@ -0,0 +1,219 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.gcloud.dns; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.google.api.services.dns.model.Change; +import com.google.common.collect.ImmutableList; + +import org.junit.Test; + +import java.util.List; + +public class ChangeRequestInfoTest { + + private static final String GENERATED_ID = "cr-id-1"; + private static final Long START_TIME_MILLIS = 12334567890L; + private static final ChangeRequest.Status STATUS = ChangeRequest.Status.PENDING; + private static final String NAME1 = "dns1"; + private static final RecordSet.Type TYPE1 = RecordSet.Type.A; + private static final String NAME2 = "dns2"; + private static final RecordSet.Type TYPE2 = RecordSet.Type.AAAA; + private static final String NAME3 = "dns3"; + private static final RecordSet.Type TYPE3 = RecordSet.Type.MX; + private static final RecordSet RECORD1 = RecordSet.builder(NAME1, TYPE1).build(); + private static final RecordSet RECORD2 = RecordSet.builder(NAME2, TYPE2).build(); + private static final RecordSet RECORD3 = RecordSet.builder(NAME3, TYPE3).build(); + private static final List ADDITIONS = ImmutableList.of(RECORD1, RECORD2); + private static final List DELETIONS = ImmutableList.of(RECORD3); + private static final ChangeRequestInfo CHANGE = ChangeRequest.builder() + .add(RECORD1) + .add(RECORD2) + .delete(RECORD3) + .startTimeMillis(START_TIME_MILLIS) + .status(STATUS) + .generatedId(GENERATED_ID) + .build(); + + @Test + public void testEmptyBuilder() { + ChangeRequestInfo cr = ChangeRequest.builder().build(); + assertNotNull(cr.deletions()); + assertTrue(cr.deletions().isEmpty()); + assertNotNull(cr.additions()); + assertTrue(cr.additions().isEmpty()); + } + + @Test + public void testBuilder() { + assertEquals(GENERATED_ID, CHANGE.generatedId()); + assertEquals(STATUS, CHANGE.status()); + assertEquals(START_TIME_MILLIS, CHANGE.startTimeMillis()); + assertEquals(ADDITIONS, CHANGE.additions()); + assertEquals(DELETIONS, CHANGE.deletions()); + List recordList = ImmutableList.of(RECORD1); + ChangeRequestInfo another = CHANGE.toBuilder().additions(recordList).build(); + assertEquals(recordList, another.additions()); + assertEquals(CHANGE.deletions(), another.deletions()); + another = CHANGE.toBuilder().deletions(recordList).build(); + assertEquals(recordList, another.deletions()); + assertEquals(CHANGE.additions(), another.additions()); + } + + @Test + public void testEqualsAndNotEquals() { + ChangeRequestInfo clone = CHANGE.toBuilder().build(); + assertEquals(CHANGE, clone); + clone = ChangeRequest.fromPb(CHANGE.toPb()); + assertEquals(CHANGE, clone); + clone = CHANGE.toBuilder().generatedId("some-other-id").build(); + assertNotEquals(CHANGE, clone); + clone = CHANGE.toBuilder().startTimeMillis(CHANGE.startTimeMillis() + 1).build(); + assertNotEquals(CHANGE, clone); + clone = CHANGE.toBuilder().add(RECORD3).build(); + assertNotEquals(CHANGE, clone); + clone = CHANGE.toBuilder().delete(RECORD1).build(); + assertNotEquals(CHANGE, clone); + ChangeRequestInfo empty = ChangeRequest.builder().build(); + assertNotEquals(CHANGE, empty); + assertEquals(empty, ChangeRequest.builder().build()); + } + + @Test + public void testSameHashCodeOnEquals() { + ChangeRequestInfo clone = CHANGE.toBuilder().build(); + assertEquals(CHANGE, clone); + assertEquals(CHANGE.hashCode(), clone.hashCode()); + ChangeRequestInfo empty = ChangeRequest.builder().build(); + assertEquals(empty.hashCode(), ChangeRequest.builder().build().hashCode()); + } + + @Test + public void testToAndFromPb() { + assertEquals(CHANGE, ChangeRequest.fromPb(CHANGE.toPb())); + ChangeRequestInfo partial = ChangeRequest.builder().build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + partial = ChangeRequest.builder().generatedId(GENERATED_ID).build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + partial = ChangeRequest.builder().add(RECORD1).build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + partial = ChangeRequest.builder().delete(RECORD1).build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + partial = ChangeRequest.builder().additions(ADDITIONS).build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + partial = ChangeRequest.builder().deletions(DELETIONS).build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + partial = ChangeRequest.builder().startTimeMillis(START_TIME_MILLIS).build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + partial = ChangeRequest.builder().status(STATUS).build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + } + + @Test + public void testToBuilder() { + assertEquals(CHANGE, CHANGE.toBuilder().build()); + ChangeRequestInfo partial = ChangeRequest.builder().build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ChangeRequest.builder().generatedId(GENERATED_ID).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ChangeRequest.builder().add(RECORD1).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ChangeRequest.builder().delete(RECORD1).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ChangeRequest.builder().additions(ADDITIONS).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ChangeRequest.builder().deletions(DELETIONS).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ChangeRequest.builder().startTimeMillis(START_TIME_MILLIS).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ChangeRequest.builder().status(STATUS).build(); + assertEquals(partial, partial.toBuilder().build()); + } + + @Test + public void testClearAdditions() { + ChangeRequestInfo clone = CHANGE.toBuilder().clearAdditions().build(); + assertTrue(clone.additions().isEmpty()); + assertFalse(clone.deletions().isEmpty()); + } + + @Test + public void testAddAddition() { + try { + CHANGE.toBuilder().add(null); + fail("Should not be able to add null RecordSet."); + } catch (NullPointerException e) { + // expected + } + ChangeRequestInfo clone = CHANGE.toBuilder().add(RECORD1).build(); + assertEquals(CHANGE.additions().size() + 1, clone.additions().size()); + } + + @Test + public void testAddDeletion() { + try { + CHANGE.toBuilder().delete(null); + fail("Should not be able to delete null RecordSet."); + } catch (NullPointerException e) { + // expected + } + ChangeRequestInfo clone = CHANGE.toBuilder().delete(RECORD1).build(); + assertEquals(CHANGE.deletions().size() + 1, clone.deletions().size()); + } + + @Test + public void testClearDeletions() { + ChangeRequestInfo clone = CHANGE.toBuilder().clearDeletions().build(); + assertTrue(clone.deletions().isEmpty()); + assertFalse(clone.additions().isEmpty()); + } + + @Test + public void testRemoveAddition() { + ChangeRequestInfo clone = CHANGE.toBuilder().removeAddition(RECORD1).build(); + assertTrue(clone.additions().contains(RECORD2)); + assertFalse(clone.additions().contains(RECORD1)); + assertTrue(clone.deletions().contains(RECORD3)); + clone = CHANGE.toBuilder().removeAddition(RECORD2).removeAddition(RECORD1).build(); + assertFalse(clone.additions().contains(RECORD2)); + assertFalse(clone.additions().contains(RECORD1)); + assertTrue(clone.additions().isEmpty()); + assertTrue(clone.deletions().contains(RECORD3)); + } + + @Test + public void testRemoveDeletion() { + ChangeRequestInfo clone = CHANGE.toBuilder().removeDeletion(RECORD3).build(); + assertTrue(clone.deletions().isEmpty()); + } + + @Test + public void testDateParsing() { + String startTime = "2016-01-26T18:33:43.512Z"; // obtained from service + Change change = CHANGE.toPb().setStartTime(startTime); + ChangeRequestInfo converted = ChangeRequest.fromPb(change); + assertNotNull(converted.startTimeMillis()); + assertEquals(change, converted.toPb()); + assertEquals(change.getStartTime(), converted.toPb().getStartTime()); + } +} diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java index 8b40a4dcff34..2c3be337f033 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java @@ -16,203 +16,158 @@ package com.google.gcloud.dns; +import static org.easymock.EasyMock.createStrictMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.reset; +import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import com.google.common.collect.ImmutableList; +import org.junit.After; +import org.junit.Before; import org.junit.Test; -import java.util.List; - public class ChangeRequestTest { - private static final String ID = "cr-id-1"; - private static final Long START_TIME_MILLIS = 12334567890L; - private static final ChangeRequest.Status STATUS = ChangeRequest.Status.PENDING; - private static final String NAME1 = "dns1"; - private static final DnsRecord.Type TYPE1 = DnsRecord.Type.A; - private static final String NAME2 = "dns2"; - private static final DnsRecord.Type TYPE2 = DnsRecord.Type.AAAA; - private static final String NAME3 = "dns3"; - private static final DnsRecord.Type TYPE3 = DnsRecord.Type.MX; - private static final DnsRecord RECORD1 = DnsRecord.builder(NAME1, TYPE1).build(); - private static final DnsRecord RECORD2 = DnsRecord.builder(NAME2, TYPE2).build(); - private static final DnsRecord RECORD3 = DnsRecord.builder(NAME3, TYPE3).build(); - private static final List ADDITIONS = ImmutableList.of(RECORD1, RECORD2); - private static final List DELETIONS = ImmutableList.of(RECORD3); - private static final ChangeRequest CHANGE = ChangeRequest.builder() - .add(RECORD1) - .add(RECORD2) - .delete(RECORD3) - .startTimeMillis(START_TIME_MILLIS) - .status(STATUS) - .id(ID) + private static final String ZONE_NAME = "dns-zone-name"; + private static final ChangeRequestInfo CHANGE_REQUEST_INFO = ChangeRequest.builder() + .add(RecordSet.builder("name", RecordSet.Type.A).build()) + .delete(RecordSet.builder("othername", RecordSet.Type.AAAA).build()) .build(); - - @Test - public void testEmptyBuilder() { - ChangeRequest cr = ChangeRequest.builder().build(); - assertNotNull(cr.deletions()); - assertTrue(cr.deletions().isEmpty()); - assertNotNull(cr.additions()); - assertTrue(cr.additions().isEmpty()); - } - - @Test - public void testBuilder() { - assertEquals(ID, CHANGE.id()); - assertEquals(STATUS, CHANGE.status()); - assertEquals(START_TIME_MILLIS, CHANGE.startTimeMillis()); - assertEquals(ADDITIONS, CHANGE.additions()); - assertEquals(DELETIONS, CHANGE.deletions()); - List recordList = ImmutableList.of(RECORD1); - ChangeRequest another = CHANGE.toBuilder().additions(recordList).build(); - assertEquals(recordList, another.additions()); - assertEquals(CHANGE.deletions(), another.deletions()); - another = CHANGE.toBuilder().deletions(recordList).build(); - assertEquals(recordList, another.deletions()); - assertEquals(CHANGE.additions(), another.additions()); - } - - @Test - public void testEqualsAndNotEquals() { - ChangeRequest clone = CHANGE.toBuilder().build(); - assertEquals(CHANGE, clone); - clone = ChangeRequest.fromPb(CHANGE.toPb()); - assertEquals(CHANGE, clone); - clone = CHANGE.toBuilder().id("some-other-id").build(); - assertNotEquals(CHANGE, clone); - clone = CHANGE.toBuilder().startTimeMillis(CHANGE.startTimeMillis() + 1).build(); - assertNotEquals(CHANGE, clone); - clone = CHANGE.toBuilder().add(RECORD3).build(); - assertNotEquals(CHANGE, clone); - clone = CHANGE.toBuilder().delete(RECORD1).build(); - assertNotEquals(CHANGE, clone); - ChangeRequest empty = ChangeRequest.builder().build(); - assertNotEquals(CHANGE, empty); - assertEquals(empty, ChangeRequest.builder().build()); + private static final DnsOptions OPTIONS = createStrictMock(DnsOptions.class); + + private Dns dns; + private ChangeRequest changeRequest; + private ChangeRequest changeRequestPending; + private ChangeRequest changeRequestPartial; + + @Before + public void setUp() throws Exception { + dns = createStrictMock(Dns.class); + expect(dns.options()).andReturn(OPTIONS).times(3); + replay(dns); + changeRequest = new ChangeRequest(dns, ZONE_NAME, new ChangeRequestInfo.BuilderImpl( + CHANGE_REQUEST_INFO.toBuilder() + .startTimeMillis(132L) + .generatedId("12") + .status(ChangeRequest.Status.DONE) + .build())); + changeRequestPending = new ChangeRequest(dns, ZONE_NAME, new ChangeRequestInfo.BuilderImpl( + CHANGE_REQUEST_INFO.toBuilder() + .startTimeMillis(132L) + .generatedId("12") + .status(ChangeRequest.Status.PENDING) + .build())); + changeRequestPartial = new ChangeRequest(dns, ZONE_NAME, + new ChangeRequest.BuilderImpl(CHANGE_REQUEST_INFO)); + reset(dns); } - @Test - public void testSameHashCodeOnEquals() { - ChangeRequest clone = CHANGE.toBuilder().build(); - assertEquals(CHANGE, clone); - assertEquals(CHANGE.hashCode(), clone.hashCode()); - ChangeRequest empty = ChangeRequest.builder().build(); - assertEquals(empty.hashCode(), ChangeRequest.builder().build().hashCode()); - } - - @Test - public void testToAndFromPb() { - assertEquals(CHANGE, ChangeRequest.fromPb(CHANGE.toPb())); - ChangeRequest partial = ChangeRequest.builder().build(); - assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - partial = ChangeRequest.builder().id(ID).build(); - assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - partial = ChangeRequest.builder().add(RECORD1).build(); - assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - partial = ChangeRequest.builder().delete(RECORD1).build(); - assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - partial = ChangeRequest.builder().additions(ADDITIONS).build(); - assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - partial = ChangeRequest.builder().deletions(DELETIONS).build(); - assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - partial = ChangeRequest.builder().startTimeMillis(START_TIME_MILLIS).build(); - assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - partial = ChangeRequest.builder().status(STATUS).build(); - assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + @After + public void tearDown() throws Exception { + verify(dns); } @Test - public void testToBuilder() { - assertEquals(CHANGE, CHANGE.toBuilder().build()); - ChangeRequest partial = ChangeRequest.builder().build(); - assertEquals(partial, partial.toBuilder().build()); - partial = ChangeRequest.builder().id(ID).build(); - assertEquals(partial, partial.toBuilder().build()); - partial = ChangeRequest.builder().add(RECORD1).build(); - assertEquals(partial, partial.toBuilder().build()); - partial = ChangeRequest.builder().delete(RECORD1).build(); - assertEquals(partial, partial.toBuilder().build()); - partial = ChangeRequest.builder().additions(ADDITIONS).build(); - assertEquals(partial, partial.toBuilder().build()); - partial = ChangeRequest.builder().deletions(DELETIONS).build(); - assertEquals(partial, partial.toBuilder().build()); - partial = ChangeRequest.builder().startTimeMillis(START_TIME_MILLIS).build(); - assertEquals(partial, partial.toBuilder().build()); - partial = ChangeRequest.builder().status(STATUS).build(); - assertEquals(partial, partial.toBuilder().build()); + public void testConstructor() { + expect(dns.options()).andReturn(OPTIONS); + replay(dns); + assertEquals(new ChangeRequest(dns, ZONE_NAME, + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_INFO)), changeRequestPartial); + assertNotNull(changeRequest.dns()); + assertEquals(ZONE_NAME, changeRequest.zone()); + assertSame(dns, changeRequestPartial.dns()); + assertEquals(ZONE_NAME, changeRequestPartial.zone()); } @Test - public void testClearAdditions() { - ChangeRequest clone = CHANGE.toBuilder().clearAdditions().build(); - assertTrue(clone.additions().isEmpty()); - assertFalse(clone.deletions().isEmpty()); + public void testFromPb() { + expect(dns.options()).andReturn(OPTIONS).times(2); + replay(dns); + assertEquals(changeRequest, ChangeRequest.fromPb(dns, ZONE_NAME, changeRequest.toPb())); + assertEquals(changeRequestPartial, + ChangeRequest.fromPb(dns, ZONE_NAME, changeRequestPartial.toPb())); } @Test - public void testAddAddition() { - try { - CHANGE.toBuilder().add(null); - fail("Should not be able to add null DnsRecord."); - } catch (NullPointerException e) { - // expected - } - ChangeRequest clone = CHANGE.toBuilder().add(RECORD1).build(); - assertEquals(CHANGE.additions().size() + 1, clone.additions().size()); + public void testEqualsAndToBuilder() { + expect(dns.options()).andReturn(OPTIONS).times(2); + replay(dns); + ChangeRequest compare = changeRequest.toBuilder().build(); + assertEquals(changeRequest, compare); + assertEquals(changeRequest.hashCode(), compare.hashCode()); + compare = changeRequestPartial.toBuilder().build(); + assertEquals(changeRequestPartial, compare); + assertEquals(changeRequestPartial.hashCode(), compare.hashCode()); } @Test - public void testAddDeletion() { - try { - CHANGE.toBuilder().delete(null); - fail("Should not be able to delete null DnsRecord."); - } catch (NullPointerException e) { - // expected - } - ChangeRequest clone = CHANGE.toBuilder().delete(RECORD1).build(); - assertEquals(CHANGE.deletions().size() + 1, clone.deletions().size()); - } - - @Test - public void testClearDeletions() { - ChangeRequest clone = CHANGE.toBuilder().clearDeletions().build(); - assertTrue(clone.deletions().isEmpty()); - assertFalse(clone.additions().isEmpty()); + public void testBuilder() { + // one for each build() call because it invokes a constructor + expect(dns.options()).andReturn(OPTIONS).times(9); + replay(dns); + String id = changeRequest.generatedId() + "aaa"; + assertEquals(id, changeRequest.toBuilder().generatedId(id).build().generatedId()); + ChangeRequest modified = + changeRequest.toBuilder().status(ChangeRequest.Status.PENDING).build(); + assertEquals(ChangeRequest.Status.PENDING, modified.status()); + modified = changeRequest.toBuilder().clearDeletions().build(); + assertTrue(modified.deletions().isEmpty()); + modified = changeRequest.toBuilder().clearAdditions().build(); + assertTrue(modified.additions().isEmpty()); + modified = changeRequest.toBuilder().additions(ImmutableList.of()).build(); + assertTrue(modified.additions().isEmpty()); + modified = changeRequest.toBuilder().deletions(ImmutableList.of()).build(); + assertTrue(modified.deletions().isEmpty()); + RecordSet cname = RecordSet.builder("last", RecordSet.Type.CNAME).build(); + modified = changeRequest.toBuilder().add(cname).build(); + assertTrue(modified.additions().contains(cname)); + modified = changeRequest.toBuilder().delete(cname).build(); + assertTrue(modified.deletions().contains(cname)); + modified = changeRequest.toBuilder().startTimeMillis(0L).build(); + assertEquals(Long.valueOf(0), modified.startTimeMillis()); } @Test - public void testRemoveAddition() { - ChangeRequest clone = CHANGE.toBuilder().removeAddition(RECORD1).build(); - assertTrue(clone.additions().contains(RECORD2)); - assertFalse(clone.additions().contains(RECORD1)); - assertTrue(clone.deletions().contains(RECORD3)); - clone = CHANGE.toBuilder().removeAddition(RECORD2).removeAddition(RECORD1).build(); - assertFalse(clone.additions().contains(RECORD2)); - assertFalse(clone.additions().contains(RECORD1)); - assertTrue(clone.additions().isEmpty()); - assertTrue(clone.deletions().contains(RECORD3)); + public void testApplyTo() { + expect(dns.applyChangeRequest(ZONE_NAME, changeRequest)).andReturn(changeRequest); + expect(dns.applyChangeRequest(ZONE_NAME, changeRequest, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME))) + .andReturn(changeRequest); + replay(dns); + assertSame(changeRequest, changeRequest.applyTo(ZONE_NAME)); + assertSame(changeRequest, changeRequest.applyTo(ZONE_NAME, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME))); } @Test - public void testRemoveDeletion() { - ChangeRequest clone = CHANGE.toBuilder().removeDeletion(RECORD3).build(); - assertTrue(clone.deletions().isEmpty()); + public void testReload() { + expect(dns.getChangeRequest(ZONE_NAME, changeRequest.generatedId())).andReturn(changeRequest); + expect(dns.getChangeRequest(ZONE_NAME, changeRequest.generatedId(), + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME))) + .andReturn(changeRequest); + replay(dns); + assertSame(changeRequest, changeRequest.reload()); + assertSame(changeRequest, changeRequest.reload( + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME))); } @Test - public void testDateParsing() { - String startTime = "2016-01-26T18:33:43.512Z"; // obtained from service - com.google.api.services.dns.model.Change change = CHANGE.toPb().setStartTime(startTime); - ChangeRequest converted = ChangeRequest.fromPb(change); - assertNotNull(converted.startTimeMillis()); - assertEquals(change, converted.toPb()); - assertEquals(change.getStartTime(), converted.toPb().getStartTime()); + public void testIsDone() { + replay(dns); + assertTrue(changeRequest.isDone()); + verify(dns); + reset(dns); + expect(dns.getChangeRequest(ZONE_NAME, changeRequest.generatedId(), + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS))) + .andReturn(changeRequest); + replay(dns); + assertTrue(changeRequestPending.isDone()); + verify(dns); } } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java index a97c9c408036..c359871b998c 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java @@ -46,22 +46,22 @@ public class DnsImplTest { private static final String DNS_NAME = "example.com."; private static final String DESCRIPTION = "desc"; private static final String CHANGE_ID = "some change id"; - private static final DnsRecord DNS_RECORD1 = DnsRecord.builder("Something", DnsRecord.Type.AAAA) - .build(); - private static final DnsRecord DNS_RECORD2 = DnsRecord.builder("Different", DnsRecord.Type.AAAA) - .build(); + private static final RecordSet DNS_RECORD1 = + RecordSet.builder("Something", RecordSet.Type.AAAA).build(); + private static final RecordSet DNS_RECORD2 = + RecordSet.builder("Different", RecordSet.Type.AAAA).build(); private static final Integer MAX_SIZE = 20; private static final String PAGE_TOKEN = "some token"; private static final ZoneInfo ZONE_INFO = ZoneInfo.of(ZONE_NAME, DNS_NAME, DESCRIPTION); private static final ProjectInfo PROJECT_INFO = ProjectInfo.builder().build(); - private static final ChangeRequest CHANGE_REQUEST_PARTIAL = ChangeRequest.builder() + private static final ChangeRequestInfo CHANGE_REQUEST_PARTIAL = ChangeRequestInfo.builder() .add(DNS_RECORD1) .build(); - private static final ChangeRequest CHANGE_REQUEST_COMPLETE = ChangeRequest.builder() + private static final ChangeRequestInfo CHANGE_REQUEST_COMPLETE = ChangeRequestInfo.builder() .add(DNS_RECORD1) .startTimeMillis(123L) .status(ChangeRequest.Status.PENDING) - .id(CHANGE_ID) + .generatedId(CHANGE_ID) .build(); // Result lists @@ -91,12 +91,12 @@ public class DnsImplTest { Dns.ChangeRequestListOption.pageToken(PAGE_TOKEN), Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.STATUS), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING)}; - private static final Dns.DnsRecordListOption[] DNS_RECORD_LIST_OPTIONS = { - Dns.DnsRecordListOption.pageSize(MAX_SIZE), - Dns.DnsRecordListOption.pageToken(PAGE_TOKEN), - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TTL), - Dns.DnsRecordListOption.dnsName(DNS_NAME), - Dns.DnsRecordListOption.type(DnsRecord.Type.AAAA)}; + private static final Dns.RecordSetListOption[] DNS_RECORD_LIST_OPTIONS = { + Dns.RecordSetListOption.pageSize(MAX_SIZE), + Dns.RecordSetListOption.pageToken(PAGE_TOKEN), + Dns.RecordSetListOption.fields(Dns.RecordSetField.TTL), + Dns.RecordSetListOption.dnsName(DNS_NAME), + Dns.RecordSetListOption.type(RecordSet.Type.AAAA)}; // Other private static final Map EMPTY_RPC_OPTIONS = ImmutableMap.of(); @@ -215,27 +215,30 @@ public void testProjectGetWithOptions() { @Test public void testGetChangeRequest() { - EasyMock.expect(dnsRpcMock.getChangeRequest(ZONE_INFO.name(), CHANGE_REQUEST_COMPLETE.id(), - EMPTY_RPC_OPTIONS)).andReturn(CHANGE_REQUEST_COMPLETE.toPb()); + EasyMock.expect(dnsRpcMock.getChangeRequest(ZONE_INFO.name(), + CHANGE_REQUEST_COMPLETE.generatedId(), EMPTY_RPC_OPTIONS)) + .andReturn(CHANGE_REQUEST_COMPLETE.toPb()); EasyMock.replay(dnsRpcMock); dns = options.service(); // creates DnsImpl ChangeRequest changeRequest = dns.getChangeRequest(ZONE_INFO.name(), - CHANGE_REQUEST_COMPLETE.id()); - assertEquals(CHANGE_REQUEST_COMPLETE, changeRequest); + CHANGE_REQUEST_COMPLETE.generatedId()); + assertEquals(new ChangeRequest(dns, ZONE_INFO.name(), + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_COMPLETE)), changeRequest); } @Test public void testGetChangeRequestWithOptions() { Capture> capturedOptions = Capture.newInstance(); EasyMock.expect(dnsRpcMock.getChangeRequest(EasyMock.eq(ZONE_INFO.name()), - EasyMock.eq(CHANGE_REQUEST_COMPLETE.id()), EasyMock.capture(capturedOptions))) + EasyMock.eq(CHANGE_REQUEST_COMPLETE.generatedId()), EasyMock.capture(capturedOptions))) .andReturn(CHANGE_REQUEST_COMPLETE.toPb()); EasyMock.replay(dnsRpcMock); dns = options.service(); // creates DnsImpl ChangeRequest changeRequest = dns.getChangeRequest(ZONE_INFO.name(), - CHANGE_REQUEST_COMPLETE.id(), CHANGE_GET_FIELDS); + CHANGE_REQUEST_COMPLETE.generatedId(), CHANGE_GET_FIELDS); String selector = (String) capturedOptions.getValue().get(CHANGE_GET_FIELDS.rpcOption()); - assertEquals(CHANGE_REQUEST_COMPLETE, changeRequest); + assertEquals(new ChangeRequest(dns, ZONE_INFO.name(), + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_COMPLETE)), changeRequest); assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.selector())); assertTrue(selector.contains(Dns.ChangeRequestField.ID.selector())); } @@ -248,7 +251,8 @@ public void testApplyChangeRequest() { dns = options.service(); // creates DnsImpl ChangeRequest changeRequest = dns.applyChangeRequest(ZONE_INFO.name(), CHANGE_REQUEST_PARTIAL); - assertEquals(CHANGE_REQUEST_COMPLETE, changeRequest); + assertEquals(new ChangeRequest(dns, ZONE_INFO.name(), + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_COMPLETE)), changeRequest); } @Test @@ -262,7 +266,8 @@ public void testApplyChangeRequestWithOptions() { ChangeRequest changeRequest = dns.applyChangeRequest(ZONE_INFO.name(), CHANGE_REQUEST_PARTIAL, CHANGE_GET_FIELDS); String selector = (String) capturedOptions.getValue().get(CHANGE_GET_FIELDS.rpcOption()); - assertEquals(CHANGE_REQUEST_COMPLETE, changeRequest); + assertEquals(new ChangeRequest(dns, ZONE_INFO.name(), + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_COMPLETE)), changeRequest); assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.selector())); assertTrue(selector.contains(Dns.ChangeRequestField.ID.selector())); } @@ -275,8 +280,12 @@ public void testListChangeRequests() { EasyMock.replay(dnsRpcMock); dns = options.service(); // creates DnsImpl Page changeRequestPage = dns.listChangeRequests(ZONE_INFO.name()); - assertTrue(Lists.newArrayList(changeRequestPage.values()).contains(CHANGE_REQUEST_COMPLETE)); - assertTrue(Lists.newArrayList(changeRequestPage.values()).contains(CHANGE_REQUEST_PARTIAL)); + assertTrue(Lists.newArrayList(changeRequestPage.values()).contains( + new ChangeRequest(dns, ZONE_INFO.name(), + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_COMPLETE)))); + assertTrue(Lists.newArrayList(changeRequestPage.values()).contains( + new ChangeRequest(dns, ZONE_INFO.name(), + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_PARTIAL)))); assertEquals(2, Lists.newArrayList(changeRequestPage.values()).size()); } @@ -288,8 +297,12 @@ public void testListChangeRequestsWithOptions() { EasyMock.replay(dnsRpcMock); dns = options.service(); // creates DnsImpl Page changeRequestPage = dns.listChangeRequests(ZONE_NAME, CHANGE_LIST_OPTIONS); - assertTrue(Lists.newArrayList(changeRequestPage.values()).contains(CHANGE_REQUEST_COMPLETE)); - assertTrue(Lists.newArrayList(changeRequestPage.values()).contains(CHANGE_REQUEST_PARTIAL)); + assertTrue(Lists.newArrayList(changeRequestPage.values()).contains( + new ChangeRequest(dns, ZONE_INFO.name(), + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_COMPLETE)))); + assertTrue(Lists.newArrayList(changeRequestPage.values()).contains( + new ChangeRequest(dns, ZONE_INFO.name(), + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_PARTIAL)))); assertEquals(2, Lists.newArrayList(changeRequestPage.values()).size()); Integer size = (Integer) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[0].rpcOption()); assertEquals(MAX_SIZE, size); @@ -338,11 +351,11 @@ public void testListZonesWithOptions() { @Test public void testListDnsRecords() { - EasyMock.expect(dnsRpcMock.listDnsRecords(ZONE_INFO.name(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(dnsRpcMock.listRecordSets(ZONE_INFO.name(), EMPTY_RPC_OPTIONS)) .andReturn(LIST_OF_PB_DNS_RECORDS); EasyMock.replay(dnsRpcMock); dns = options.service(); // creates DnsImpl - Page dnsPage = dns.listDnsRecords(ZONE_INFO.name()); + Page dnsPage = dns.listRecordSets(ZONE_INFO.name()); assertEquals(2, Lists.newArrayList(dnsPage.values()).size()); assertTrue(Lists.newArrayList(dnsPage.values()).contains(DNS_RECORD1)); assertTrue(Lists.newArrayList(dnsPage.values()).contains(DNS_RECORD2)); @@ -351,11 +364,11 @@ public void testListDnsRecords() { @Test public void testListDnsRecordsWithOptions() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(dnsRpcMock.listDnsRecords(EasyMock.eq(ZONE_NAME), + EasyMock.expect(dnsRpcMock.listRecordSets(EasyMock.eq(ZONE_NAME), EasyMock.capture(capturedOptions))).andReturn(LIST_OF_PB_DNS_RECORDS); EasyMock.replay(dnsRpcMock); dns = options.service(); // creates DnsImpl - Page dnsPage = dns.listDnsRecords(ZONE_NAME, DNS_RECORD_LIST_OPTIONS); + Page dnsPage = dns.listRecordSets(ZONE_NAME, DNS_RECORD_LIST_OPTIONS); assertEquals(2, Lists.newArrayList(dnsPage.values()).size()); assertTrue(Lists.newArrayList(dnsPage.values()).contains(DNS_RECORD1)); assertTrue(Lists.newArrayList(dnsPage.values()).contains(DNS_RECORD2)); @@ -365,8 +378,8 @@ public void testListDnsRecordsWithOptions() { .get(DNS_RECORD_LIST_OPTIONS[1].rpcOption()); assertEquals(PAGE_TOKEN, selector); selector = (String) capturedOptions.getValue().get(DNS_RECORD_LIST_OPTIONS[2].rpcOption()); - assertTrue(selector.contains(Dns.DnsRecordField.NAME.selector())); - assertTrue(selector.contains(Dns.DnsRecordField.TTL.selector())); + assertTrue(selector.contains(Dns.RecordSetField.NAME.selector())); + assertTrue(selector.contains(Dns.RecordSetField.TTL.selector())); selector = (String) capturedOptions.getValue().get(DNS_RECORD_LIST_OPTIONS[3].rpcOption()); assertEquals(DNS_RECORD_LIST_OPTIONS[3].value(), selector); String type = (String) capturedOptions.getValue().get(DNS_RECORD_LIST_OPTIONS[4] diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java index 2e233e2df62a..df86d6ebd495 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java @@ -30,36 +30,36 @@ public class DnsTest { private static final String DNS_NAME = "www.example.com."; @Test - public void testDnsRecordListOption() { + public void testRecordSetListOption() { // dns name String dnsName = "some name"; - Dns.DnsRecordListOption dnsRecordListOption = Dns.DnsRecordListOption.dnsName(dnsName); - assertEquals(dnsName, dnsRecordListOption.value()); - assertEquals(DnsRpc.Option.NAME, dnsRecordListOption.rpcOption()); + Dns.RecordSetListOption recordSetListOption = Dns.RecordSetListOption.dnsName(dnsName); + assertEquals(dnsName, recordSetListOption.value()); + assertEquals(DnsRpc.Option.NAME, recordSetListOption.rpcOption()); // page token - dnsRecordListOption = Dns.DnsRecordListOption.pageToken(PAGE_TOKEN); - assertEquals(PAGE_TOKEN, dnsRecordListOption.value()); - assertEquals(DnsRpc.Option.PAGE_TOKEN, dnsRecordListOption.rpcOption()); + recordSetListOption = Dns.RecordSetListOption.pageToken(PAGE_TOKEN); + assertEquals(PAGE_TOKEN, recordSetListOption.value()); + assertEquals(DnsRpc.Option.PAGE_TOKEN, recordSetListOption.rpcOption()); // page size - dnsRecordListOption = Dns.DnsRecordListOption.pageSize(PAGE_SIZE); - assertEquals(PAGE_SIZE, dnsRecordListOption.value()); - assertEquals(DnsRpc.Option.PAGE_SIZE, dnsRecordListOption.rpcOption()); + recordSetListOption = Dns.RecordSetListOption.pageSize(PAGE_SIZE); + assertEquals(PAGE_SIZE, recordSetListOption.value()); + assertEquals(DnsRpc.Option.PAGE_SIZE, recordSetListOption.rpcOption()); // record type - DnsRecord.Type recordType = DnsRecord.Type.AAAA; - dnsRecordListOption = Dns.DnsRecordListOption.type(recordType); - assertEquals(recordType.name(), dnsRecordListOption.value()); - assertEquals(DnsRpc.Option.DNS_TYPE, dnsRecordListOption.rpcOption()); + RecordSet.Type recordType = RecordSet.Type.AAAA; + recordSetListOption = Dns.RecordSetListOption.type(recordType); + assertEquals(recordType.name(), recordSetListOption.value()); + assertEquals(DnsRpc.Option.DNS_TYPE, recordSetListOption.rpcOption()); // fields - dnsRecordListOption = Dns.DnsRecordListOption.fields(Dns.DnsRecordField.NAME, - Dns.DnsRecordField.TTL); - assertEquals(DnsRpc.Option.FIELDS, dnsRecordListOption.rpcOption()); - assertTrue(dnsRecordListOption.value() instanceof String); - assertTrue(((String) dnsRecordListOption.value()).contains( - Dns.DnsRecordField.NAME.selector())); - assertTrue(((String) dnsRecordListOption.value()).contains( - Dns.DnsRecordField.TTL.selector())); - assertTrue(((String) dnsRecordListOption.value()).contains( - Dns.DnsRecordField.NAME.selector())); + recordSetListOption = Dns.RecordSetListOption.fields(Dns.RecordSetField.NAME, + Dns.RecordSetField.TTL); + assertEquals(DnsRpc.Option.FIELDS, recordSetListOption.rpcOption()); + assertTrue(recordSetListOption.value() instanceof String); + assertTrue(((String) recordSetListOption.value()).contains( + Dns.RecordSetField.NAME.selector())); + assertTrue(((String) recordSetListOption.value()).contains( + Dns.RecordSetField.TTL.selector())); + assertTrue(((String) recordSetListOption.value()).contains( + Dns.RecordSetField.NAME.selector())); } @Test diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/AbstractOptionTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/OptionTest.java similarity index 66% rename from gcloud-java-dns/src/test/java/com/google/gcloud/dns/AbstractOptionTest.java rename to gcloud-java-dns/src/test/java/com/google/gcloud/dns/OptionTest.java index d88ea85c5846..e9906354f963 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/AbstractOptionTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/OptionTest.java @@ -18,24 +18,27 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertNull; import com.google.gcloud.dns.spi.DnsRpc; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; -public class AbstractOptionTest { +public class OptionTest { private static final DnsRpc.Option RPC_OPTION = DnsRpc.Option.DNS_TYPE; private static final DnsRpc.Option ANOTHER_RPC_OPTION = DnsRpc.Option.DNS_NAME; private static final String VALUE = "some value"; private static final String OTHER_VALUE = "another value"; - private static final AbstractOption OPTION = new AbstractOption(RPC_OPTION, VALUE) {}; - private static final AbstractOption OPTION_EQUALS = new AbstractOption(RPC_OPTION, VALUE) {}; - private static final AbstractOption OPTION_NOT_EQUALS1 = - new AbstractOption(RPC_OPTION, OTHER_VALUE) {}; - private static final AbstractOption OPTION_NOT_EQUALS2 = - new AbstractOption(ANOTHER_RPC_OPTION, VALUE) {}; + private static final Option OPTION = new Option(RPC_OPTION, VALUE) {}; + private static final Option OPTION_EQUALS = new Option(RPC_OPTION, VALUE) {}; + private static final Option OPTION_NOT_EQUALS1 = new Option(RPC_OPTION, OTHER_VALUE) {}; + private static final Option OPTION_NOT_EQUALS2 = new Option(ANOTHER_RPC_OPTION, VALUE) {}; + + @Rule + public ExpectedException thrown = ExpectedException.none(); @Test public void testEquals() { @@ -53,12 +56,10 @@ public void testHashCode() { public void testConstructor() { assertEquals(RPC_OPTION, OPTION.rpcOption()); assertEquals(VALUE, OPTION.value()); - try { - new AbstractOption(null, VALUE) {}; - fail("Cannot build with empty option."); - } catch (NullPointerException e) { - // expected - } - new AbstractOption(RPC_OPTION, null) {}; // null value is ok + Option option = new Option(RPC_OPTION, null) {}; + assertEquals(RPC_OPTION, option.rpcOption()); + assertNull(option.value()); + thrown.expect(NullPointerException.class); + new Option(null, VALUE) {}; } } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/RecordSetTest.java similarity index 53% rename from gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java rename to gcloud-java-dns/src/test/java/com/google/gcloud/dns/RecordSetTest.java index 5fc972cede78..fc888bf8a697 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/RecordSetTest.java @@ -16,7 +16,6 @@ package com.google.gcloud.dns; -import static com.google.gcloud.dns.DnsRecord.builder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; @@ -26,35 +25,35 @@ import java.util.concurrent.TimeUnit; -public class DnsRecordTest { +public class RecordSetTest { private static final String NAME = "example.com."; private static final Integer TTL = 3600; private static final TimeUnit UNIT = TimeUnit.HOURS; private static final Integer UNIT_TTL = 1; - private static final DnsRecord.Type TYPE = DnsRecord.Type.AAAA; - private static final DnsRecord record = builder(NAME, TYPE) + private static final RecordSet.Type TYPE = RecordSet.Type.AAAA; + private static final RecordSet recordSet = RecordSet.builder(NAME, TYPE) .ttl(UNIT_TTL, UNIT) .build(); @Test public void testDefaultDnsRecord() { - DnsRecord record = builder(NAME, TYPE).build(); - assertEquals(0, record.records().size()); - assertEquals(TYPE, record.type()); - assertEquals(NAME, record.name()); + RecordSet recordSet = RecordSet.builder(NAME, TYPE).build(); + assertEquals(0, recordSet.records().size()); + assertEquals(TYPE, recordSet.type()); + assertEquals(NAME, recordSet.name()); } @Test public void testBuilder() { - assertEquals(NAME, record.name()); - assertEquals(TTL, record.ttl()); - assertEquals(TYPE, record.type()); - assertEquals(0, record.records().size()); + assertEquals(NAME, recordSet.name()); + assertEquals(TTL, recordSet.ttl()); + assertEquals(TYPE, recordSet.type()); + assertEquals(0, recordSet.records().size()); // verify that one can add records to the record set - String testingRecord = "Testing record"; - String anotherTestingRecord = "Another record 123"; - DnsRecord anotherRecord = record.toBuilder() + String testingRecord = "Testing recordSet"; + String anotherTestingRecord = "Another recordSet 123"; + RecordSet anotherRecord = recordSet.toBuilder() .addRecord(testingRecord) .addRecord(anotherTestingRecord) .build(); @@ -66,71 +65,72 @@ public void testBuilder() { @Test public void testValidTtl() { try { - builder(NAME, TYPE).ttl(-1, TimeUnit.SECONDS); + RecordSet.builder(NAME, TYPE).ttl(-1, TimeUnit.SECONDS); fail("A negative value is not acceptable for ttl."); } catch (IllegalArgumentException e) { // expected } - builder(NAME, TYPE).ttl(0, TimeUnit.SECONDS); - builder(NAME, TYPE).ttl(Integer.MAX_VALUE, TimeUnit.SECONDS); + RecordSet.builder(NAME, TYPE).ttl(0, TimeUnit.SECONDS); + RecordSet.builder(NAME, TYPE).ttl(Integer.MAX_VALUE, TimeUnit.SECONDS); try { - builder(NAME, TYPE).ttl(Integer.MAX_VALUE, TimeUnit.HOURS); + RecordSet.builder(NAME, TYPE).ttl(Integer.MAX_VALUE, TimeUnit.HOURS); fail("This value is too large for int."); } catch (IllegalArgumentException e) { // expected } - DnsRecord record = DnsRecord.builder(NAME, TYPE).ttl(UNIT_TTL, UNIT).build(); + RecordSet record = RecordSet.builder(NAME, TYPE).ttl(UNIT_TTL, UNIT).build(); assertEquals(TTL, record.ttl()); } @Test public void testEqualsAndNotEquals() { - DnsRecord clone = record.toBuilder().build(); - assertEquals(record, clone); - clone = record.toBuilder().addRecord("another record").build(); - assertNotEquals(record, clone); + RecordSet clone = recordSet.toBuilder().build(); + assertEquals(recordSet, clone); + clone = recordSet.toBuilder().addRecord("another recordSet").build(); + assertNotEquals(recordSet, clone); String differentName = "totally different name"; - clone = record.toBuilder().name(differentName).build(); - assertNotEquals(record, clone); - clone = record.toBuilder().ttl(record.ttl() + 1, TimeUnit.SECONDS).build(); - assertNotEquals(record, clone); - clone = record.toBuilder().type(DnsRecord.Type.TXT).build(); - assertNotEquals(record, clone); + clone = recordSet.toBuilder().name(differentName).build(); + assertNotEquals(recordSet, clone); + clone = recordSet.toBuilder().ttl(recordSet.ttl() + 1, TimeUnit.SECONDS).build(); + assertNotEquals(recordSet, clone); + clone = recordSet.toBuilder().type(RecordSet.Type.TXT).build(); + assertNotEquals(recordSet, clone); } @Test public void testSameHashCodeOnEquals() { - int hash = record.hashCode(); - DnsRecord clone = record.toBuilder().build(); + int hash = recordSet.hashCode(); + RecordSet clone = recordSet.toBuilder().build(); assertEquals(clone.hashCode(), hash); } @Test public void testToAndFromPb() { - assertEquals(record, DnsRecord.fromPb(record.toPb())); - DnsRecord partial = builder(NAME, TYPE).build(); - assertEquals(partial, DnsRecord.fromPb(partial.toPb())); - partial = builder(NAME, TYPE).addRecord("test").build(); - assertEquals(partial, DnsRecord.fromPb(partial.toPb())); - partial = builder(NAME, TYPE).ttl(15, TimeUnit.SECONDS).build(); - assertEquals(partial, DnsRecord.fromPb(partial.toPb())); + assertEquals(recordSet, RecordSet.fromPb(recordSet.toPb())); + RecordSet partial = RecordSet.builder(NAME, TYPE).build(); + assertEquals(partial, RecordSet.fromPb(partial.toPb())); + partial = RecordSet.builder(NAME, TYPE).addRecord("test").build(); + assertEquals(partial, RecordSet.fromPb(partial.toPb())); + partial = RecordSet.builder(NAME, TYPE).ttl(15, TimeUnit.SECONDS).build(); + assertEquals(partial, RecordSet.fromPb(partial.toPb())); } @Test public void testToBuilder() { - assertEquals(record, record.toBuilder().build()); - DnsRecord partial = builder(NAME, TYPE).build(); + assertEquals(recordSet, recordSet.toBuilder().build()); + RecordSet partial = RecordSet.builder(NAME, TYPE).build(); assertEquals(partial, partial.toBuilder().build()); - partial = builder(NAME, TYPE).addRecord("test").build(); + partial = RecordSet.builder(NAME, TYPE).addRecord("test").build(); assertEquals(partial, partial.toBuilder().build()); - partial = builder(NAME, TYPE).ttl(15, TimeUnit.SECONDS).build(); + partial = RecordSet.builder(NAME, TYPE).ttl(15, TimeUnit.SECONDS).build(); assertEquals(partial, partial.toBuilder().build()); } @Test public void clearRecordSet() { // make sure that we are starting not empty - DnsRecord clone = record.toBuilder().addRecord("record").addRecord("another").build(); + RecordSet clone = + recordSet.toBuilder().addRecord("record").addRecord("another").build(); assertNotEquals(0, clone.records().size()); clone = clone.toBuilder().clearRecords().build(); assertEquals(0, clone.records().size()); @@ -141,7 +141,7 @@ public void clearRecordSet() { public void removeFromRecordSet() { String recordString = "record"; // make sure that we are starting not empty - DnsRecord clone = record.toBuilder().addRecord(recordString).build(); + RecordSet clone = recordSet.toBuilder().addRecord(recordString).build(); assertNotEquals(0, clone.records().size()); clone = clone.toBuilder().removeRecord(recordString).build(); assertEquals(0, clone.records().size()); diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java index 7a0c32036878..7742d4c59a48 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java @@ -31,7 +31,7 @@ public class SerializationTest extends BaseSerializationTest { private static final ZoneInfo FULL_ZONE_INFO = Zone.of("some zone name", "www.example.com", "some descriptions").toBuilder() .creationTimeMillis(132L) - .id("123333") + .generatedId("123333") .nameServers(ImmutableList.of("server 1", "server 2")) .nameServerSet("specificationstring") .build(); @@ -45,8 +45,8 @@ public class SerializationTest extends BaseSerializationTest { .build(); private static final Dns.ZoneListOption ZONE_LIST_OPTION = Dns.ZoneListOption.dnsName("www.example.com."); - private static final Dns.DnsRecordListOption DNS_REOCRD_LIST_OPTION = - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TTL); + private static final Dns.RecordSetListOption RECORD_SET_LIST_OPTION = + Dns.RecordSetListOption.fields(Dns.RecordSetField.TTL); private static final Dns.ChangeRequestListOption CHANGE_REQUEST_LIST_OPTION = Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.STATUS); private static final Dns.ZoneOption ZONE_OPTION = @@ -63,21 +63,26 @@ public class SerializationTest extends BaseSerializationTest { private static final Zone FULL_ZONE = new Zone(DNS, new ZoneInfo.BuilderImpl(FULL_ZONE_INFO)); private static final Zone PARTIAL_ZONE = new Zone(DNS, new ZoneInfo.BuilderImpl(PARTIAL_ZONE_INFO)); - private static final ChangeRequest CHANGE_REQUEST_PARTIAL = ChangeRequest.builder().build(); - private static final DnsRecord DNS_RECORD_PARTIAL = - DnsRecord.builder("www.www.com", DnsRecord.Type.AAAA).build(); - private static final DnsRecord DNS_RECORD_COMPLETE = - DnsRecord.builder("www.sadfa.com", DnsRecord.Type.A) + private static final ChangeRequestInfo CHANGE_REQUEST_INFO_PARTIAL = + ChangeRequest.builder().build(); + private static final ChangeRequest CHANGE_REQUEST_PARTIAL = new ChangeRequest(DNS, "name", + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_INFO_PARTIAL)); + private static final RecordSet RECORD_SET_PARTIAL = + RecordSet.builder("www.www.com", RecordSet.Type.AAAA).build(); + private static final RecordSet RECORD_SET_COMPLETE = + RecordSet.builder("www.sadfa.com", RecordSet.Type.A) .ttl(12, TimeUnit.HOURS) .addRecord("record") .build(); - private static final ChangeRequest CHANGE_REQUEST_COMPLETE = ChangeRequest.builder() - .add(DNS_RECORD_COMPLETE) - .delete(DNS_RECORD_PARTIAL) + private static final ChangeRequestInfo CHANGE_REQUEST_INFO_COMPLETE = ChangeRequestInfo.builder() + .add(RECORD_SET_COMPLETE) + .delete(RECORD_SET_PARTIAL) .status(ChangeRequest.Status.PENDING) - .id("some id") + .generatedId("some id") .startTimeMillis(132L) .build(); + private static final ChangeRequest CHANGE_REQUEST_COMPLETE = new ChangeRequest(DNS, "name", + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_INFO_COMPLETE)); @Override protected Serializable[] serializableObjects() { @@ -89,10 +94,11 @@ protected Serializable[] serializableObjects() { .authCredentials(null) .build(); return new Serializable[]{FULL_ZONE_INFO, PARTIAL_ZONE_INFO, ZONE_LIST_OPTION, - DNS_REOCRD_LIST_OPTION, CHANGE_REQUEST_LIST_OPTION, ZONE_OPTION, CHANGE_REQUEST_OPTION, + RECORD_SET_LIST_OPTION, CHANGE_REQUEST_LIST_OPTION, ZONE_OPTION, CHANGE_REQUEST_OPTION, PROJECT_OPTION, PARTIAL_PROJECT_INFO, FULL_PROJECT_INFO, OPTIONS, FULL_ZONE, PARTIAL_ZONE, - OPTIONS, CHANGE_REQUEST_PARTIAL, DNS_RECORD_PARTIAL, DNS_RECORD_COMPLETE, - CHANGE_REQUEST_COMPLETE, options, otherOptions}; + OPTIONS, CHANGE_REQUEST_INFO_PARTIAL, CHANGE_REQUEST_PARTIAL, RECORD_SET_PARTIAL, + RECORD_SET_COMPLETE, CHANGE_REQUEST_INFO_COMPLETE, CHANGE_REQUEST_COMPLETE, options, + otherOptions}; } @Override diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneInfoTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneInfoTest.java index 923672bb85a7..b537735c3c4e 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneInfoTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneInfoTest.java @@ -21,6 +21,7 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import com.google.api.services.dns.model.ManagedZone; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; @@ -32,7 +33,7 @@ public class ZoneInfoTest { private static final String NAME = "mz-example.com"; - private static final String ID = "123456"; + private static final String GENERATED_ID = "123456"; private static final Long CREATION_TIME_MILLIS = 1123468321321L; private static final String DNS_NAME = "example.com."; private static final String DESCRIPTION = "description for the zone"; @@ -43,7 +44,7 @@ public class ZoneInfoTest { private static final List NAME_SERVERS = ImmutableList.of(NS1, NS2, NS3); private static final ZoneInfo INFO = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder() .creationTimeMillis(CREATION_TIME_MILLIS) - .id(ID) + .generatedId(GENERATED_ID) .nameServerSet(NAME_SERVER_SET) .nameServers(NAME_SERVERS) .build(); @@ -53,7 +54,7 @@ public void testOf() { ZoneInfo partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION); assertTrue(partial.nameServers().isEmpty()); assertEquals(NAME, partial.name()); - assertNull(partial.id()); + assertNull(partial.generatedId()); assertNull(partial.creationTimeMillis()); assertNull(partial.nameServerSet()); assertEquals(DESCRIPTION, partial.description()); @@ -67,7 +68,7 @@ public void testBuilder() { assertEquals(NS2, INFO.nameServers().get(1)); assertEquals(NS3, INFO.nameServers().get(2)); assertEquals(NAME, INFO.name()); - assertEquals(ID, INFO.id()); + assertEquals(GENERATED_ID, INFO.generatedId()); assertEquals(CREATION_TIME_MILLIS, INFO.creationTimeMillis()); assertEquals(NAME_SERVER_SET, INFO.nameServerSet()); assertEquals(DESCRIPTION, INFO.description()); @@ -91,7 +92,7 @@ public void testEqualsAndNotEquals() { assertNotEquals(INFO, clone); clone = INFO.toBuilder().dnsName(differentName).build(); assertNotEquals(INFO, clone); - clone = INFO.toBuilder().id(INFO.id() + "1111").build(); + clone = INFO.toBuilder().generatedId(INFO.generatedId() + "1111").build(); assertNotEquals(INFO, clone); clone = INFO.toBuilder().nameServerSet(INFO.nameServerSet() + "salt").build(); assertNotEquals(INFO, clone); @@ -109,7 +110,9 @@ public void testToBuilder() { assertEquals(INFO, INFO.toBuilder().build()); ZoneInfo partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION); assertEquals(partial, partial.toBuilder().build()); - partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder().id(ID).build(); + partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder() + .generatedId(GENERATED_ID) + .build(); assertEquals(partial, partial.toBuilder().build()); partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder() .creationTimeMillis(CREATION_TIME_MILLIS).build(); @@ -128,7 +131,9 @@ public void testToAndFromPb() { assertEquals(INFO, ZoneInfo.fromPb(INFO.toPb())); ZoneInfo partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION); assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); - partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder().id(ID).build(); + partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder() + .generatedId(GENERATED_ID) + .build(); assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder() .creationTimeMillis(CREATION_TIME_MILLIS).build(); @@ -151,10 +156,10 @@ public void testEmptyNameServers() { @Test public void testDateParsing() { - com.google.api.services.dns.model.ManagedZone pb = INFO.toPb(); + ManagedZone pb = INFO.toPb(); pb.setCreationTime("2016-01-19T18:00:12.854Z"); // a real value obtained from Google Cloud DNS ZoneInfo mz = ZoneInfo.fromPb(pb); // parses the string timestamp to millis - com.google.api.services.dns.model.ManagedZone pbClone = mz.toPb(); // converts it back to string + ManagedZone pbClone = mz.toPb(); // converts it back to string assertEquals(pb, pbClone); assertEquals(pb.getCreationTime(), pbClone.getCreationTime()); } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java index 759c34fc1167..5407d4f248b7 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java @@ -45,40 +45,42 @@ public class ZoneTest { private static final String ZONE_ID = "123"; private static final ZoneInfo ZONE_INFO = Zone.of(ZONE_NAME, "example.com", "description") .toBuilder() - .id(ZONE_ID) + .generatedId(ZONE_ID) .creationTimeMillis(123478946464L) .build(); private static final ZoneInfo NO_ID_INFO = ZoneInfo.of(ZONE_NAME, "another-example.com", "description").toBuilder() - .creationTimeMillis(893123464L) - .build(); + .creationTimeMillis(893123464L) + .build(); private static final Dns.ZoneOption ZONE_FIELD_OPTIONS = Dns.ZoneOption.fields(Dns.ZoneField.CREATION_TIME); - private static final Dns.DnsRecordListOption DNS_RECORD_OPTIONS = - Dns.DnsRecordListOption.dnsName("some-dns"); + private static final Dns.RecordSetListOption DNS_RECORD_OPTIONS = + Dns.RecordSetListOption.dnsName("some-dns"); private static final Dns.ChangeRequestOption CHANGE_REQUEST_FIELD_OPTIONS = Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME); private static final Dns.ChangeRequestListOption CHANGE_REQUEST_LIST_OPTIONS = Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.START_TIME); - private static final ChangeRequest CHANGE_REQUEST = ChangeRequest.builder().id("someid").build(); - private static final ChangeRequest CHANGE_REQUEST_AFTER = CHANGE_REQUEST.toBuilder() - .startTimeMillis(123465L).build(); - private static final ChangeRequest CHANGE_REQUEST_NO_ID = ChangeRequest.builder().build(); + private static final ChangeRequestInfo CHANGE_REQUEST = + ChangeRequestInfo.builder().generatedId("someid").build(); + private static final ChangeRequestInfo CHANGE_REQUEST_NO_ID = + ChangeRequestInfo.builder().build(); private static final DnsException EXCEPTION = createStrictMock(DnsException.class); private static final DnsOptions OPTIONS = createStrictMock(DnsOptions.class); private Dns dns; private Zone zone; private Zone zoneNoId; + private ChangeRequest changeRequestAfter; @Before public void setUp() throws Exception { dns = createStrictMock(Dns.class); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS).times(3); replay(dns); zone = new Zone(dns, new ZoneInfo.BuilderImpl(ZONE_INFO)); zoneNoId = new Zone(dns, new ZoneInfo.BuilderImpl(NO_ID_INFO)); + changeRequestAfter = new ChangeRequest(dns, ZONE_NAME, new ChangeRequestInfo.BuilderImpl( + CHANGE_REQUEST.toBuilder().startTimeMillis(123465L).build())); reset(dns); } @@ -97,8 +99,7 @@ public void testConstructor() { @Test public void deleteByNameAndFound() { - expect(dns.delete(ZONE_NAME)).andReturn(true); - expect(dns.delete(ZONE_NAME)).andReturn(true); + expect(dns.delete(ZONE_NAME)).andReturn(true).times(2); replay(dns); boolean result = zone.delete(); assertTrue(result); @@ -108,8 +109,7 @@ public void deleteByNameAndFound() { @Test public void deleteByNameAndNotFound() { - expect(dns.delete(ZONE_NAME)).andReturn(false); - expect(dns.delete(ZONE_NAME)).andReturn(false); + expect(dns.delete(ZONE_NAME)).andReturn(false).times(2); replay(dns); boolean result = zoneNoId.delete(); assertFalse(result); @@ -120,51 +120,47 @@ public void deleteByNameAndNotFound() { @Test public void listDnsRecordsByNameAndFound() { @SuppressWarnings("unchecked") - Page pageMock = createStrictMock(Page.class); + Page pageMock = createStrictMock(Page.class); replay(pageMock); - expect(dns.listDnsRecords(ZONE_NAME)).andReturn(pageMock); - expect(dns.listDnsRecords(ZONE_NAME)).andReturn(pageMock); + expect(dns.listRecordSets(ZONE_NAME)).andReturn(pageMock).times(2); // again for options - expect(dns.listDnsRecords(ZONE_NAME, DNS_RECORD_OPTIONS)).andReturn(pageMock); - expect(dns.listDnsRecords(ZONE_NAME, DNS_RECORD_OPTIONS)).andReturn(pageMock); + expect(dns.listRecordSets(ZONE_NAME, DNS_RECORD_OPTIONS)).andReturn(pageMock).times(2); replay(dns); - Page result = zone.listDnsRecords(); + Page result = zone.listRecordSets(); assertSame(pageMock, result); - result = zoneNoId.listDnsRecords(); + result = zoneNoId.listRecordSets(); assertSame(pageMock, result); verify(pageMock); - zone.listDnsRecords(DNS_RECORD_OPTIONS); // check options - zoneNoId.listDnsRecords(DNS_RECORD_OPTIONS); // check options + zone.listRecordSets(DNS_RECORD_OPTIONS); // check options + zoneNoId.listRecordSets(DNS_RECORD_OPTIONS); // check options } @Test public void listDnsRecordsByNameAndNotFound() { - expect(dns.listDnsRecords(ZONE_NAME)).andThrow(EXCEPTION); - expect(dns.listDnsRecords(ZONE_NAME)).andThrow(EXCEPTION); + expect(dns.listRecordSets(ZONE_NAME)).andThrow(EXCEPTION).times(2); // again for options - expect(dns.listDnsRecords(ZONE_NAME, DNS_RECORD_OPTIONS)).andThrow(EXCEPTION); - expect(dns.listDnsRecords(ZONE_NAME, DNS_RECORD_OPTIONS)).andThrow(EXCEPTION); + expect(dns.listRecordSets(ZONE_NAME, DNS_RECORD_OPTIONS)).andThrow(EXCEPTION).times(2); replay(dns); try { - zoneNoId.listDnsRecords(); + zoneNoId.listRecordSets(); fail("Parent container not found, should throw an exception."); } catch (DnsException e) { // expected } try { - zone.listDnsRecords(); + zone.listRecordSets(); fail("Parent container not found, should throw an exception."); } catch (DnsException e) { // expected } try { - zoneNoId.listDnsRecords(DNS_RECORD_OPTIONS); // check options + zoneNoId.listRecordSets(DNS_RECORD_OPTIONS); // check options fail("Parent container not found, should throw an exception."); } catch (DnsException e) { // expected } try { - zone.listDnsRecords(DNS_RECORD_OPTIONS); // check options + zone.listRecordSets(DNS_RECORD_OPTIONS); // check options fail("Parent container not found, should throw an exception."); } catch (DnsException e) { // expected @@ -173,8 +169,7 @@ public void listDnsRecordsByNameAndNotFound() { @Test public void reloadByNameAndFound() { - expect(dns.getZone(ZONE_NAME)).andReturn(zone); - expect(dns.getZone(ZONE_NAME)).andReturn(zone); + expect(dns.getZone(ZONE_NAME)).andReturn(zone).times(2); // again for options expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(zoneNoId); expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(zone); @@ -191,11 +186,9 @@ public void reloadByNameAndFound() { @Test public void reloadByNameAndNotFound() { - expect(dns.getZone(ZONE_NAME)).andReturn(null); - expect(dns.getZone(ZONE_NAME)).andReturn(null); + expect(dns.getZone(ZONE_NAME)).andReturn(null).times(2); // again for options - expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(null); - expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(null); + expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(null).times(2); replay(dns); Zone result = zoneNoId.reload(); assertNull(result); @@ -208,36 +201,33 @@ public void reloadByNameAndNotFound() { @Test public void applyChangeByNameAndFound() { expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST)) - .andReturn(CHANGE_REQUEST_AFTER); + .andReturn(changeRequestAfter); expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST)) - .andReturn(CHANGE_REQUEST_AFTER); + .andReturn(changeRequestAfter); // again for options expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(CHANGE_REQUEST_AFTER); + .andReturn(changeRequestAfter); expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(CHANGE_REQUEST_AFTER); + .andReturn(changeRequestAfter); replay(dns); ChangeRequest result = zoneNoId.applyChangeRequest(CHANGE_REQUEST); - assertEquals(CHANGE_REQUEST_AFTER, result); + assertEquals(changeRequestAfter, result); result = zone.applyChangeRequest(CHANGE_REQUEST); - assertEquals(CHANGE_REQUEST_AFTER, result); + assertEquals(changeRequestAfter, result); // check options result = zoneNoId.applyChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); - assertEquals(CHANGE_REQUEST_AFTER, result); + assertEquals(changeRequestAfter, result); result = zone.applyChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); - assertEquals(CHANGE_REQUEST_AFTER, result); + assertEquals(changeRequestAfter, result); } @Test public void applyChangeByNameAndNotFound() { // ID is not set - expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST)).andThrow(EXCEPTION); - expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST)).andThrow(EXCEPTION); + expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST)).andThrow(EXCEPTION).times(2); // again for options expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) - .andThrow(EXCEPTION); - expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) - .andThrow(EXCEPTION); + .andThrow(EXCEPTION).times(2); replay(dns); try { zoneNoId.applyChangeRequest(CHANGE_REQUEST); @@ -297,58 +287,52 @@ public void applyNullChangeRequest() { @Test public void getChangeAndZoneFoundByName() { - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())) - .andReturn(CHANGE_REQUEST_AFTER); - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())) - .andReturn(CHANGE_REQUEST_AFTER); + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.generatedId())) + .andReturn(changeRequestAfter).times(2); // again for options - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(CHANGE_REQUEST_AFTER); - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(CHANGE_REQUEST_AFTER); + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.generatedId(), + CHANGE_REQUEST_FIELD_OPTIONS)).andReturn(changeRequestAfter).times(2); replay(dns); - ChangeRequest result = zoneNoId.getChangeRequest(CHANGE_REQUEST.id()); - assertEquals(CHANGE_REQUEST_AFTER, result); - result = zone.getChangeRequest(CHANGE_REQUEST.id()); - assertEquals(CHANGE_REQUEST_AFTER, result); + ChangeRequest result = zoneNoId.getChangeRequest(CHANGE_REQUEST.generatedId()); + assertEquals(changeRequestAfter, result); + result = zone.getChangeRequest(CHANGE_REQUEST.generatedId()); + assertEquals(changeRequestAfter, result); // check options - result = zoneNoId.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS); - assertEquals(CHANGE_REQUEST_AFTER, result); - result = zone.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS); - assertEquals(CHANGE_REQUEST_AFTER, result); + result = zoneNoId.getChangeRequest(CHANGE_REQUEST.generatedId(), CHANGE_REQUEST_FIELD_OPTIONS); + assertEquals(changeRequestAfter, result); + result = zone.getChangeRequest(CHANGE_REQUEST.generatedId(), CHANGE_REQUEST_FIELD_OPTIONS); + assertEquals(changeRequestAfter, result); } @Test public void getChangeAndZoneNotFoundByName() { - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())).andThrow(EXCEPTION); - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())).andThrow(EXCEPTION); + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.generatedId())).andThrow(EXCEPTION) + .times(2); // again for options - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) - .andThrow(EXCEPTION); - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) - .andThrow(EXCEPTION); + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.generatedId(), + CHANGE_REQUEST_FIELD_OPTIONS)).andThrow(EXCEPTION).times(2); replay(dns); try { - zoneNoId.getChangeRequest(CHANGE_REQUEST.id()); + zoneNoId.getChangeRequest(CHANGE_REQUEST.generatedId()); fail("Parent container not found, should throw an exception."); } catch (DnsException e) { // expected } try { - zone.getChangeRequest(CHANGE_REQUEST.id()); + zone.getChangeRequest(CHANGE_REQUEST.generatedId()); fail("Parent container not found, should throw an exception."); } catch (DnsException e) { // expected } // check options try { - zoneNoId.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS); + zoneNoId.getChangeRequest(CHANGE_REQUEST.generatedId(), CHANGE_REQUEST_FIELD_OPTIONS); fail("Parent container not found, should throw an exception."); } catch (DnsException e) { // expected } try { - zone.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS); + zone.getChangeRequest(CHANGE_REQUEST.generatedId(), CHANGE_REQUEST_FIELD_OPTIONS); fail("Parent container not found, should throw an exception."); } catch (DnsException e) { // expected @@ -357,18 +341,16 @@ public void getChangeAndZoneNotFoundByName() { @Test public void getChangedWhichDoesNotExistZoneFound() { - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())).andReturn(null); - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())).andReturn(null); + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.generatedId())).andReturn(null).times(2); // again for options - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(null); - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(null); + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.generatedId(), + CHANGE_REQUEST_FIELD_OPTIONS)).andReturn(null).times(2); replay(dns); - assertNull(zoneNoId.getChangeRequest(CHANGE_REQUEST.id())); - assertNull(zone.getChangeRequest(CHANGE_REQUEST.id())); - assertNull(zoneNoId.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)); - assertNull(zone.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)); + assertNull(zoneNoId.getChangeRequest(CHANGE_REQUEST.generatedId())); + assertNull(zone.getChangeRequest(CHANGE_REQUEST.generatedId())); + assertNull( + zoneNoId.getChangeRequest(CHANGE_REQUEST.generatedId(), CHANGE_REQUEST_FIELD_OPTIONS)); + assertNull(zone.getChangeRequest(CHANGE_REQUEST.generatedId(), CHANGE_REQUEST_FIELD_OPTIONS)); } @Test @@ -404,25 +386,25 @@ public void getNullChangeRequest() { public void getChangeRequestWithNoId() { replay(dns); // no calls expected try { - zone.getChangeRequest(CHANGE_REQUEST_NO_ID.id()); + zone.getChangeRequest(CHANGE_REQUEST_NO_ID.generatedId()); fail("Cannot get ChangeRequest by null id."); } catch (NullPointerException e) { // expected } try { - zone.getChangeRequest(CHANGE_REQUEST_NO_ID.id(), CHANGE_REQUEST_FIELD_OPTIONS); + zone.getChangeRequest(CHANGE_REQUEST_NO_ID.generatedId(), CHANGE_REQUEST_FIELD_OPTIONS); fail("Cannot get ChangeRequest by null id."); } catch (NullPointerException e) { // expected } try { - zoneNoId.getChangeRequest(CHANGE_REQUEST_NO_ID.id()); + zoneNoId.getChangeRequest(CHANGE_REQUEST_NO_ID.generatedId()); fail("Cannot get ChangeRequest by null id."); } catch (NullPointerException e) { // expected } try { - zoneNoId.getChangeRequest(CHANGE_REQUEST_NO_ID.id(), CHANGE_REQUEST_FIELD_OPTIONS); + zoneNoId.getChangeRequest(CHANGE_REQUEST_NO_ID.generatedId(), CHANGE_REQUEST_FIELD_OPTIONS); fail("Cannot get ChangeRequest by null id."); } catch (NullPointerException e) { // expected @@ -434,13 +416,10 @@ public void listChangeRequestsAndZoneFound() { @SuppressWarnings("unchecked") Page pageMock = createStrictMock(Page.class); replay(pageMock); - expect(dns.listChangeRequests(ZONE_NAME)).andReturn(pageMock); - expect(dns.listChangeRequests(ZONE_NAME)).andReturn(pageMock); + expect(dns.listChangeRequests(ZONE_NAME)).andReturn(pageMock).times(2); // again for options expect(dns.listChangeRequests(ZONE_NAME, CHANGE_REQUEST_LIST_OPTIONS)) - .andReturn(pageMock); - expect(dns.listChangeRequests(ZONE_NAME, CHANGE_REQUEST_LIST_OPTIONS)) - .andReturn(pageMock); + .andReturn(pageMock).times(2); replay(dns); Page result = zoneNoId.listChangeRequests(); assertSame(pageMock, result); @@ -453,11 +432,10 @@ public void listChangeRequestsAndZoneFound() { @Test public void listChangeRequestsAndZoneNotFound() { - expect(dns.listChangeRequests(ZONE_NAME)).andThrow(EXCEPTION); - expect(dns.listChangeRequests(ZONE_NAME)).andThrow(EXCEPTION); + expect(dns.listChangeRequests(ZONE_NAME)).andThrow(EXCEPTION).times(2); // again for options - expect(dns.listChangeRequests(ZONE_NAME, CHANGE_REQUEST_LIST_OPTIONS)).andThrow(EXCEPTION); - expect(dns.listChangeRequests(ZONE_NAME, CHANGE_REQUEST_LIST_OPTIONS)).andThrow(EXCEPTION); + expect(dns.listChangeRequests(ZONE_NAME, CHANGE_REQUEST_LIST_OPTIONS)).andThrow(EXCEPTION) + .times(2); replay(dns); try { zoneNoId.listChangeRequests(); @@ -494,8 +472,7 @@ public void testFromPb() { @Test public void testEqualsAndToBuilder() { - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS).times(2); replay(dns); assertEquals(zone, zone.toBuilder().build()); assertEquals(zone.hashCode(), zone.toBuilder().build().hashCode()); @@ -504,17 +481,10 @@ public void testEqualsAndToBuilder() { @Test public void testBuilder() { // one for each build() call because it invokes a constructor - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS).times(8); replay(dns); assertNotEquals(zone, zone.toBuilder() - .id((new BigInteger(zone.id())).add(BigInteger.ONE).toString()) + .generatedId(new BigInteger(zone.generatedId()).add(BigInteger.ONE).toString()) .build()); assertNotEquals(zone, zone.toBuilder().dnsName(zone.name() + "aaaa").build()); assertNotEquals(zone, zone.toBuilder().nameServerSet(zone.nameServerSet() + "aaaa").build()); @@ -523,7 +493,7 @@ public void testBuilder() { assertNotEquals(zone, zone.toBuilder().creationTimeMillis(zone.creationTimeMillis() + 1) .build()); Zone.Builder builder = zone.toBuilder(); - builder.id(ZONE_ID) + builder.generatedId(ZONE_ID) .dnsName("example.com") .creationTimeMillis(123478946464L) .build(); diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java index bfea46dfe039..e6513451e7f6 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java @@ -26,11 +26,12 @@ import com.google.common.collect.ImmutableList; import com.google.gcloud.Page; import com.google.gcloud.dns.ChangeRequest; +import com.google.gcloud.dns.ChangeRequestInfo; import com.google.gcloud.dns.Dns; import com.google.gcloud.dns.DnsException; import com.google.gcloud.dns.DnsOptions; -import com.google.gcloud.dns.DnsRecord; import com.google.gcloud.dns.ProjectInfo; +import com.google.gcloud.dns.RecordSet; import com.google.gcloud.dns.Zone; import com.google.gcloud.dns.ZoneInfo; @@ -66,26 +67,29 @@ public class ITDnsTest { ZoneInfo.of(ZONE_NAME_TOO_LONG, ZONE_DNS_NAME1, ZONE_DESCRIPTION1); private static final ZoneInfo ZONE_DNS_NO_PERIOD = ZoneInfo.of(ZONE_NAME1, ZONE_DNS_NAME_NO_PERIOD, ZONE_DESCRIPTION1); - private static final DnsRecord A_RECORD_ZONE1 = - DnsRecord.builder("www." + ZONE1.dnsName(), DnsRecord.Type.A) + private static final RecordSet A_RECORD_ZONE1 = + RecordSet.builder("www." + ZONE1.dnsName(), RecordSet.Type.A) .records(ImmutableList.of("123.123.55.1")) .ttl(25, TimeUnit.SECONDS) .build(); - private static final DnsRecord AAAA_RECORD_ZONE1 = - DnsRecord.builder("www." + ZONE1.dnsName(), DnsRecord.Type.AAAA) + private static final RecordSet AAAA_RECORD_ZONE1 = + RecordSet.builder("www." + ZONE1.dnsName(), RecordSet.Type.AAAA) .records(ImmutableList.of("ed:ed:12:aa:36:3:3:105")) .ttl(25, TimeUnit.SECONDS) .build(); - private static final ChangeRequest CHANGE_ADD_ZONE1 = ChangeRequest.builder() + private static final ChangeRequestInfo CHANGE_ADD_ZONE1 = ChangeRequest.builder() .add(A_RECORD_ZONE1) .add(AAAA_RECORD_ZONE1) .build(); - private static final ChangeRequest CHANGE_DELETE_ZONE1 = ChangeRequest.builder() + private static final ChangeRequestInfo CHANGE_DELETE_ZONE1 = ChangeRequest.builder() .delete(A_RECORD_ZONE1) .delete(AAAA_RECORD_ZONE1) .build(); private static final List ZONE_NAMES = ImmutableList.of(ZONE_NAME1, ZONE_NAME_EMPTY_DESCRIPTION); + + @Rule + public Timeout globalTimeout = Timeout.seconds(300); private static void clear() { for (String zoneName : ZONE_NAMES) { @@ -96,20 +100,21 @@ private static void clear() { when the list has been retrieved and executing the subsequent delete operation. */ Iterator iterator = zone.listChangeRequests().iterateAll(); while (iterator.hasNext()) { - waitForChangeToComplete(zoneName, iterator.next().id()); + waitForChangeToComplete(zoneName, iterator.next().generatedId()); } - Iterator recordIterator = zone.listDnsRecords().iterateAll(); - List toDelete = new LinkedList<>(); - while (recordIterator.hasNext()) { - DnsRecord record = recordIterator.next(); - if (!ImmutableList.of(DnsRecord.Type.NS, DnsRecord.Type.SOA).contains(record.type())) { - toDelete.add(record); + Iterator recordSetIterator = zone.listRecordSets().iterateAll(); + List toDelete = new LinkedList<>(); + while (recordSetIterator.hasNext()) { + RecordSet recordSet = recordSetIterator.next(); + if (!ImmutableList.of(RecordSet.Type.NS, RecordSet.Type.SOA) + .contains(recordSet.type())) { + toDelete.add(recordSet); } } if (!toDelete.isEmpty()) { ChangeRequest deletion = zone.applyChangeRequest(ChangeRequest.builder().deletions(toDelete).build()); - waitForChangeToComplete(zone.name(), deletion.id()); + waitForChangeToComplete(zone.name(), deletion.generatedId()); } zone.delete(); } @@ -140,17 +145,18 @@ public static void after() { private static void assertEqChangesIgnoreStatus(ChangeRequest expected, ChangeRequest actual) { assertEquals(expected.additions(), actual.additions()); assertEquals(expected.deletions(), actual.deletions()); - assertEquals(expected.id(), actual.id()); + assertEquals(expected.generatedId(), actual.generatedId()); assertEquals(expected.startTimeMillis(), actual.startTimeMillis()); } private static void waitForChangeToComplete(String zoneName, String changeId) { - while (true) { - ChangeRequest changeRequest = DNS.getChangeRequest(zoneName, changeId, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); - if (ChangeRequest.Status.DONE.equals(changeRequest.status())) { - return; - } + ChangeRequest changeRequest = DNS.getChangeRequest(zoneName, changeId, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); + waitForChangeToComplete(changeRequest); + } + + private static void waitForChangeToComplete(ChangeRequest changeRequest) { + while (!changeRequest.isDone()) { try { Thread.sleep(500); } catch (InterruptedException e) { @@ -159,9 +165,6 @@ private static void waitForChangeToComplete(String zoneName, String changeId) { } } - @Rule - public Timeout globalTimeout = Timeout.seconds(300); - @Test public void testCreateValidZone() { try { @@ -172,7 +175,7 @@ public void testCreateValidZone() { assertNotNull(created.creationTimeMillis()); assertNotNull(created.nameServers()); assertNull(created.nameServerSet()); - assertNotNull(created.id()); + assertNotNull(created.generatedId()); Zone retrieved = DNS.getZone(ZONE1.name()); assertEquals(created, retrieved); created = DNS.create(ZONE_EMPTY_DESCRIPTION); @@ -182,7 +185,7 @@ public void testCreateValidZone() { assertNotNull(created.creationTimeMillis()); assertNotNull(created.nameServers()); assertNull(created.nameServerSet()); - assertNotNull(created.id()); + assertNotNull(created.generatedId()); retrieved = DNS.getZone(ZONE_EMPTY_DESCRIPTION.name()); assertEquals(created, retrieved); } finally { @@ -224,7 +227,7 @@ public void testCreateZoneWithOptions() { assertNull(created.dnsName()); assertTrue(created.nameServers().isEmpty()); // never returns null assertNull(created.nameServerSet()); - assertNull(created.id()); + assertNull(created.generatedId()); created.delete(); created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.DESCRIPTION)); assertEquals(ZONE1.name(), created.name()); // always returned @@ -233,7 +236,7 @@ public void testCreateZoneWithOptions() { assertNull(created.dnsName()); assertTrue(created.nameServers().isEmpty()); // never returns null assertNull(created.nameServerSet()); - assertNull(created.id()); + assertNull(created.generatedId()); created.delete(); created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.DNS_NAME)); assertEquals(ZONE1.name(), created.name()); // always returned @@ -242,7 +245,7 @@ public void testCreateZoneWithOptions() { assertNull(created.description()); assertTrue(created.nameServers().isEmpty()); // never returns null assertNull(created.nameServerSet()); - assertNull(created.id()); + assertNull(created.generatedId()); created.delete(); created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME)); assertEquals(ZONE1.name(), created.name()); // always returned @@ -251,7 +254,7 @@ public void testCreateZoneWithOptions() { assertNull(created.description()); assertTrue(created.nameServers().isEmpty()); // never returns null assertNull(created.nameServerSet()); - assertNull(created.id()); + assertNull(created.generatedId()); created.delete(); created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME_SERVER_SET)); assertEquals(ZONE1.name(), created.name()); // always returned @@ -260,7 +263,7 @@ public void testCreateZoneWithOptions() { assertNull(created.description()); assertTrue(created.nameServers().isEmpty()); // never returns null assertNull(created.nameServerSet()); // we did not set it - assertNull(created.id()); + assertNull(created.generatedId()); created.delete(); created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME_SERVERS)); assertEquals(ZONE1.name(), created.name()); // always returned @@ -269,7 +272,7 @@ public void testCreateZoneWithOptions() { assertNull(created.description()); assertFalse(created.nameServers().isEmpty()); assertNull(created.nameServerSet()); - assertNull(created.id()); + assertNull(created.generatedId()); created.delete(); created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.ZONE_ID)); assertEquals(ZONE1.name(), created.name()); // always returned @@ -278,7 +281,7 @@ public void testCreateZoneWithOptions() { assertNull(created.description()); assertNotNull(created.nameServers()); assertTrue(created.nameServers().isEmpty()); // never returns null - assertNotNull(created.id()); + assertNotNull(created.generatedId()); created.delete(); // combination of multiple things created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.ZONE_ID, @@ -289,7 +292,7 @@ public void testCreateZoneWithOptions() { assertEquals(ZONE1.description(), created.description()); assertFalse(created.nameServers().isEmpty()); assertNull(created.nameServerSet()); // we did not set it - assertNotNull(created.id()); + assertNotNull(created.generatedId()); } finally { DNS.delete(ZONE1.name()); } @@ -306,7 +309,7 @@ public void testGetZone() { assertNull(created.dnsName()); assertTrue(created.nameServers().isEmpty()); // never returns null assertNull(created.nameServerSet()); - assertNull(created.id()); + assertNull(created.generatedId()); created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.DESCRIPTION)); assertEquals(ZONE1.name(), created.name()); // always returned assertNull(created.creationTimeMillis()); @@ -314,7 +317,7 @@ public void testGetZone() { assertNull(created.dnsName()); assertTrue(created.nameServers().isEmpty()); // never returns null assertNull(created.nameServerSet()); - assertNull(created.id()); + assertNull(created.generatedId()); created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.DNS_NAME)); assertEquals(ZONE1.name(), created.name()); // always returned assertNull(created.creationTimeMillis()); @@ -322,7 +325,7 @@ public void testGetZone() { assertNull(created.description()); assertTrue(created.nameServers().isEmpty()); // never returns null assertNull(created.nameServerSet()); - assertNull(created.id()); + assertNull(created.generatedId()); created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.NAME)); assertEquals(ZONE1.name(), created.name()); // always returned assertNull(created.creationTimeMillis()); @@ -330,7 +333,7 @@ public void testGetZone() { assertNull(created.description()); assertTrue(created.nameServers().isEmpty()); // never returns null assertNull(created.nameServerSet()); - assertNull(created.id()); + assertNull(created.generatedId()); created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.NAME_SERVER_SET)); assertEquals(ZONE1.name(), created.name()); // always returned assertNull(created.creationTimeMillis()); @@ -338,7 +341,7 @@ public void testGetZone() { assertNull(created.description()); assertTrue(created.nameServers().isEmpty()); // never returns null assertNull(created.nameServerSet()); // we did not set it - assertNull(created.id()); + assertNull(created.generatedId()); created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.NAME_SERVERS)); assertEquals(ZONE1.name(), created.name()); // always returned assertNull(created.creationTimeMillis()); @@ -346,7 +349,7 @@ public void testGetZone() { assertNull(created.description()); assertFalse(created.nameServers().isEmpty()); assertNull(created.nameServerSet()); - assertNull(created.id()); + assertNull(created.generatedId()); created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.ZONE_ID)); assertEquals(ZONE1.name(), created.name()); // always returned assertNull(created.creationTimeMillis()); @@ -354,7 +357,7 @@ public void testGetZone() { assertNull(created.description()); assertNotNull(created.nameServers()); assertTrue(created.nameServers().isEmpty()); // never returns null - assertNotNull(created.id()); + assertNotNull(created.generatedId()); // combination of multiple things created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.ZONE_ID, Dns.ZoneField.NAME_SERVERS, Dns.ZoneField.NAME_SERVER_SET, Dns.ZoneField.DESCRIPTION)); @@ -364,7 +367,7 @@ public void testGetZone() { assertEquals(ZONE1.description(), created.description()); assertFalse(created.nameServers().isEmpty()); assertNull(created.nameServerSet()); // we did not set it - assertNotNull(created.id()); + assertNotNull(created.generatedId()); } finally { DNS.delete(ZONE1.name()); } @@ -426,7 +429,7 @@ public void testListZones() { assertNull(zone.description()); assertNull(zone.nameServerSet()); assertTrue(zone.nameServers().isEmpty()); - assertNotNull(zone.id()); + assertNotNull(zone.generatedId()); assertFalse(zoneIterator.hasNext()); zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), Dns.ZoneListOption.fields(Dns.ZoneField.CREATION_TIME)).iterateAll(); @@ -437,7 +440,7 @@ public void testListZones() { assertNull(zone.description()); assertNull(zone.nameServerSet()); assertTrue(zone.nameServers().isEmpty()); - assertNull(zone.id()); + assertNull(zone.generatedId()); assertFalse(zoneIterator.hasNext()); zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), Dns.ZoneListOption.fields(Dns.ZoneField.DNS_NAME)).iterateAll(); @@ -448,7 +451,7 @@ public void testListZones() { assertNull(zone.description()); assertNull(zone.nameServerSet()); assertTrue(zone.nameServers().isEmpty()); - assertNull(zone.id()); + assertNull(zone.generatedId()); assertFalse(zoneIterator.hasNext()); zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), Dns.ZoneListOption.fields(Dns.ZoneField.DESCRIPTION)).iterateAll(); @@ -459,7 +462,7 @@ public void testListZones() { assertNotNull(zone.description()); assertNull(zone.nameServerSet()); assertTrue(zone.nameServers().isEmpty()); - assertNull(zone.id()); + assertNull(zone.generatedId()); assertFalse(zoneIterator.hasNext()); zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), Dns.ZoneListOption.fields(Dns.ZoneField.NAME_SERVERS)).iterateAll(); @@ -469,8 +472,8 @@ public void testListZones() { assertNull(zone.dnsName()); assertNull(zone.description()); assertNull(zone.nameServerSet()); - assertTrue(!zone.nameServers().isEmpty()); - assertNull(zone.id()); + assertFalse(zone.nameServers().isEmpty()); + assertNull(zone.generatedId()); assertFalse(zoneIterator.hasNext()); zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), Dns.ZoneListOption.fields(Dns.ZoneField.NAME_SERVER_SET)).iterateAll(); @@ -481,7 +484,7 @@ public void testListZones() { assertNull(zone.description()); assertNull(zone.nameServerSet()); // we cannot set it using gcloud java assertTrue(zone.nameServers().isEmpty()); - assertNull(zone.id()); + assertNull(zone.generatedId()); assertFalse(zoneIterator.hasNext()); // several combined zones = filter(DNS.listZones(Dns.ZoneListOption.fields(Dns.ZoneField.ZONE_ID, @@ -495,7 +498,7 @@ public void testListZones() { assertNotNull(current.description()); assertNull(current.nameServerSet()); assertTrue(zone.nameServers().isEmpty()); - assertNotNull(current.id()); + assertNotNull(current.generatedId()); } } finally { DNS.delete(ZONE1.name()); @@ -523,62 +526,62 @@ public void testCreateChange() { assertEquals(CHANGE_ADD_ZONE1.additions(), created.additions()); assertNotNull(created.startTimeMillis()); assertTrue(created.deletions().isEmpty()); - assertEquals("1", created.id()); + assertEquals("1", created.generatedId()); assertTrue(ImmutableList.of(ChangeRequest.Status.PENDING, ChangeRequest.Status.DONE) .contains(created.status())); assertEqChangesIgnoreStatus(created, DNS.getChangeRequest(ZONE1.name(), "1")); - waitForChangeToComplete(ZONE1.name(), "1"); - DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - waitForChangeToComplete(ZONE1.name(), "2"); + waitForChangeToComplete(created); + created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + waitForChangeToComplete(created); // with options created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); assertTrue(created.additions().isEmpty()); assertNull(created.startTimeMillis()); assertTrue(created.deletions().isEmpty()); - assertEquals("3", created.id()); + assertEquals("3", created.generatedId()); assertNull(created.status()); - waitForChangeToComplete(ZONE1.name(), "3"); - DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - waitForChangeToComplete(ZONE1.name(), "4"); + waitForChangeToComplete(created); + created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + waitForChangeToComplete(created); created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); assertTrue(created.additions().isEmpty()); assertNull(created.startTimeMillis()); assertTrue(created.deletions().isEmpty()); - assertEquals("5", created.id()); + assertEquals("5", created.generatedId()); assertNotNull(created.status()); - waitForChangeToComplete(ZONE1.name(), "5"); - DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - waitForChangeToComplete(ZONE1.name(), "6"); + waitForChangeToComplete(created); + created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + waitForChangeToComplete(created); created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); assertTrue(created.additions().isEmpty()); assertNotNull(created.startTimeMillis()); assertTrue(created.deletions().isEmpty()); - assertEquals("7", created.id()); + assertEquals("7", created.generatedId()); assertNull(created.status()); - waitForChangeToComplete(ZONE1.name(), "7"); - DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - waitForChangeToComplete(ZONE1.name(), "8"); + waitForChangeToComplete(created); + created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + waitForChangeToComplete(created); created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); assertEquals(CHANGE_ADD_ZONE1.additions(), created.additions()); assertNull(created.startTimeMillis()); assertTrue(created.deletions().isEmpty()); - assertEquals("9", created.id()); + assertEquals("9", created.generatedId()); assertNull(created.status()); // finishes with delete otherwise we cannot delete the zone - waitForChangeToComplete(ZONE1.name(), "9"); + waitForChangeToComplete(created); created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); - waitForChangeToComplete(ZONE1.name(), "10"); + waitForChangeToComplete(created); assertEquals(CHANGE_DELETE_ZONE1.deletions(), created.deletions()); assertNull(created.startTimeMillis()); assertTrue(created.additions().isEmpty()); - assertEquals("10", created.id()); + assertEquals("10", created.generatedId()); assertNull(created.status()); - waitForChangeToComplete(ZONE1.name(), "10"); + waitForChangeToComplete(created); } finally { clear(); } @@ -587,47 +590,50 @@ public void testCreateChange() { @Test public void testInvalidChangeRequest() { Zone zone = DNS.create(ZONE1); - DnsRecord validA = DnsRecord.builder("subdomain." + zone.dnsName(), DnsRecord.Type.A) - .records(ImmutableList.of("0.255.1.5")) - .build(); + RecordSet validA = + RecordSet.builder("subdomain." + zone.dnsName(), RecordSet.Type.A) + .records(ImmutableList.of("0.255.1.5")) + .build(); + boolean recordAdded = false; try { - ChangeRequest validChange = ChangeRequest.builder().add(validA).build(); + ChangeRequestInfo validChange = ChangeRequest.builder().add(validA).build(); zone.applyChangeRequest(validChange); + recordAdded = true; try { zone.applyChangeRequest(validChange); - fail("Created a record which already exists."); + fail("Created a record set which already exists."); } catch (DnsException ex) { // expected assertFalse(ex.retryable()); assertEquals(409, ex.code()); } // delete with field mismatch - DnsRecord mismatch = validA.toBuilder().ttl(20, TimeUnit.SECONDS).build(); - ChangeRequest deletion = ChangeRequest.builder().delete(mismatch).build(); + RecordSet mismatch = validA.toBuilder().ttl(20, TimeUnit.SECONDS).build(); + ChangeRequestInfo deletion = ChangeRequest.builder().delete(mismatch).build(); try { zone.applyChangeRequest(deletion); - fail("Deleted a record without a complete match."); + fail("Deleted a record set without a complete match."); } catch (DnsException ex) { // expected assertEquals(412, ex.code()); assertFalse(ex.retryable()); } // delete and add SOA - Iterator recordIterator = zone.listDnsRecords().iterateAll(); - LinkedList deletions = new LinkedList<>(); - LinkedList additions = new LinkedList<>(); - while (recordIterator.hasNext()) { - DnsRecord record = recordIterator.next(); - if (record.type() == DnsRecord.Type.SOA) { - deletions.add(record); + Iterator recordSetIterator = zone.listRecordSets().iterateAll(); + LinkedList deletions = new LinkedList<>(); + LinkedList additions = new LinkedList<>(); + while (recordSetIterator.hasNext()) { + RecordSet recordSet = recordSetIterator.next(); + if (recordSet.type() == RecordSet.Type.SOA) { + deletions.add(recordSet); // the subdomain is necessary to get 400 instead of 412 - DnsRecord copy = record.toBuilder().name("x." + record.name()).build(); + RecordSet copy = recordSet.toBuilder().name("x." + recordSet.name()).build(); additions.add(copy); break; } } deletion = deletion.toBuilder().deletions(deletions).build(); - ChangeRequest addition = ChangeRequest.builder().additions(additions).build(); + ChangeRequestInfo addition = ChangeRequest.builder().additions(additions).build(); try { zone.applyChangeRequest(deletion); fail("Deleted SOA."); @@ -645,9 +651,11 @@ public void testInvalidChangeRequest() { assertEquals(400, ex.code()); } } finally { - ChangeRequest deletion = ChangeRequest.builder().delete(validA).build(); - ChangeRequest request = zone.applyChangeRequest(deletion); - waitForChangeToComplete(zone.name(), request.id()); + if (recordAdded) { + ChangeRequestInfo deletion = ChangeRequest.builder().delete(validA).build(); + ChangeRequest request = zone.applyChangeRequest(deletion); + waitForChangeToComplete(zone.name(), request.generatedId()); + } zone.delete(); } } @@ -671,13 +679,13 @@ public void testListChanges() { assertEquals(1, changes.size()); // default change creating SOA and NS // zone has changes ChangeRequest change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); - waitForChangeToComplete(ZONE1.name(), change.id()); + waitForChangeToComplete(ZONE1.name(), change.generatedId()); change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - waitForChangeToComplete(ZONE1.name(), change.id()); + waitForChangeToComplete(ZONE1.name(), change.generatedId()); change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); - waitForChangeToComplete(ZONE1.name(), change.id()); + waitForChangeToComplete(ZONE1.name(), change.generatedId()); change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - waitForChangeToComplete(ZONE1.name(), change.id()); + waitForChangeToComplete(ZONE1.name(), change.generatedId()); changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name()).iterateAll()); assertEquals(5, changes.size()); // error in options @@ -717,7 +725,7 @@ public void testListChanges() { change = changes.get(1); assertEquals(CHANGE_ADD_ZONE1.additions(), change.additions()); assertTrue(change.deletions().isEmpty()); - assertEquals("1", change.id()); + assertEquals("1", change.generatedId()); assertNull(change.startTimeMillis()); assertNull(change.status()); changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), @@ -726,7 +734,7 @@ public void testListChanges() { change = changes.get(2); assertTrue(change.additions().isEmpty()); assertNotNull(change.deletions()); - assertEquals("2", change.id()); + assertEquals("2", change.generatedId()); assertNull(change.startTimeMillis()); assertNull(change.status()); changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), @@ -735,7 +743,7 @@ public void testListChanges() { change = changes.get(1); assertTrue(change.additions().isEmpty()); assertTrue(change.deletions().isEmpty()); - assertEquals("1", change.id()); + assertEquals("1", change.generatedId()); assertNull(change.startTimeMillis()); assertNull(change.status()); changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), @@ -744,7 +752,7 @@ public void testListChanges() { change = changes.get(1); assertTrue(change.additions().isEmpty()); assertTrue(change.deletions().isEmpty()); - assertEquals("1", change.id()); + assertEquals("1", change.generatedId()); assertNotNull(change.startTimeMillis()); assertNull(change.status()); changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), @@ -753,7 +761,7 @@ public void testListChanges() { change = changes.get(1); assertTrue(change.additions().isEmpty()); assertTrue(change.deletions().isEmpty()); - assertEquals("1", change.id()); + assertEquals("1", change.generatedId()); assertNull(change.startTimeMillis()); assertEquals(ChangeRequest.Status.DONE, change.status()); } finally { @@ -766,45 +774,45 @@ public void testGetChange() { try { Zone zone = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME)); ChangeRequest created = zone.applyChangeRequest(CHANGE_ADD_ZONE1); - ChangeRequest retrieved = DNS.getChangeRequest(zone.name(), created.id()); + ChangeRequest retrieved = DNS.getChangeRequest(zone.name(), created.generatedId()); assertEqChangesIgnoreStatus(created, retrieved); - waitForChangeToComplete(zone.name(), created.id()); + waitForChangeToComplete(zone.name(), created.generatedId()); zone.applyChangeRequest(CHANGE_DELETE_ZONE1); // with options created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); - retrieved = DNS.getChangeRequest(zone.name(), created.id(), + retrieved = DNS.getChangeRequest(zone.name(), created.generatedId(), Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); assertEqChangesIgnoreStatus(created, retrieved); - waitForChangeToComplete(zone.name(), created.id()); + waitForChangeToComplete(zone.name(), created.generatedId()); zone.applyChangeRequest(CHANGE_DELETE_ZONE1); created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); - retrieved = DNS.getChangeRequest(zone.name(), created.id(), + retrieved = DNS.getChangeRequest(zone.name(), created.generatedId(), Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); assertEqChangesIgnoreStatus(created, retrieved); - waitForChangeToComplete(zone.name(), created.id()); + waitForChangeToComplete(zone.name(), created.generatedId()); zone.applyChangeRequest(CHANGE_DELETE_ZONE1); created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); - retrieved = DNS.getChangeRequest(zone.name(), created.id(), + retrieved = DNS.getChangeRequest(zone.name(), created.generatedId(), Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); assertEqChangesIgnoreStatus(created, retrieved); - waitForChangeToComplete(zone.name(), created.id()); + waitForChangeToComplete(zone.name(), created.generatedId()); zone.applyChangeRequest(CHANGE_DELETE_ZONE1); created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); - retrieved = DNS.getChangeRequest(zone.name(), created.id(), + retrieved = DNS.getChangeRequest(zone.name(), created.generatedId(), Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); assertEqChangesIgnoreStatus(created, retrieved); - waitForChangeToComplete(zone.name(), created.id()); + waitForChangeToComplete(zone.name(), created.generatedId()); // finishes with delete otherwise we cannot delete the zone created = zone.applyChangeRequest(CHANGE_DELETE_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); - retrieved = DNS.getChangeRequest(zone.name(), created.id(), + retrieved = DNS.getChangeRequest(zone.name(), created.generatedId(), Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); assertEqChangesIgnoreStatus(created, retrieved); - waitForChangeToComplete(zone.name(), created.id()); + waitForChangeToComplete(zone.name(), created.generatedId()); } finally { clear(); } @@ -831,92 +839,93 @@ public void testGetProject() { public void testListDnsRecords() { try { Zone zone = DNS.create(ZONE1); - ImmutableList dnsRecords = ImmutableList.copyOf( - DNS.listDnsRecords(zone.name()).iterateAll()); - assertEquals(2, dnsRecords.size()); - ImmutableList defaultRecords = - ImmutableList.of(DnsRecord.Type.NS, DnsRecord.Type.SOA); - for (DnsRecord record : dnsRecords) { - assertTrue(defaultRecords.contains(record.type())); + ImmutableList recordSets = ImmutableList.copyOf( + DNS.listRecordSets(zone.name()).iterateAll()); + assertEquals(2, recordSets.size()); + ImmutableList defaultRecords = + ImmutableList.of(RecordSet.Type.NS, RecordSet.Type.SOA); + for (RecordSet recordSet : recordSets) { + assertTrue(defaultRecords.contains(recordSet.type())); } // field options - Iterator dnsRecordIterator = DNS.listDnsRecords(zone.name(), - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TTL)).iterateAll(); + Iterator recordSetIterator = DNS.listRecordSets(zone.name(), + Dns.RecordSetListOption.fields(Dns.RecordSetField.TTL)).iterateAll(); int counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertEquals(dnsRecords.get(counter).ttl(), record.ttl()); - assertEquals(dnsRecords.get(counter).name(), record.name()); - assertEquals(dnsRecords.get(counter).type(), record.type()); - assertTrue(record.records().isEmpty()); + while (recordSetIterator.hasNext()) { + RecordSet recordSet = recordSetIterator.next(); + assertEquals(recordSets.get(counter).ttl(), recordSet.ttl()); + assertEquals(recordSets.get(counter).name(), recordSet.name()); + assertEquals(recordSets.get(counter).type(), recordSet.type()); + assertTrue(recordSet.records().isEmpty()); counter++; } assertEquals(2, counter); - dnsRecordIterator = DNS.listDnsRecords(zone.name(), - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.NAME)).iterateAll(); + recordSetIterator = DNS.listRecordSets(zone.name(), + Dns.RecordSetListOption.fields(Dns.RecordSetField.NAME)).iterateAll(); counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertEquals(dnsRecords.get(counter).name(), record.name()); - assertEquals(dnsRecords.get(counter).type(), record.type()); - assertTrue(record.records().isEmpty()); - assertNull(record.ttl()); + while (recordSetIterator.hasNext()) { + RecordSet recordSet = recordSetIterator.next(); + assertEquals(recordSets.get(counter).name(), recordSet.name()); + assertEquals(recordSets.get(counter).type(), recordSet.type()); + assertTrue(recordSet.records().isEmpty()); + assertNull(recordSet.ttl()); counter++; } assertEquals(2, counter); - dnsRecordIterator = DNS.listDnsRecords(zone.name(), - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.DNS_RECORDS)).iterateAll(); + recordSetIterator = DNS.listRecordSets(zone.name(), + Dns.RecordSetListOption.fields(Dns.RecordSetField.DNS_RECORDS)) + .iterateAll(); counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertEquals(dnsRecords.get(counter).records(), record.records()); - assertEquals(dnsRecords.get(counter).name(), record.name()); - assertEquals(dnsRecords.get(counter).type(), record.type()); - assertNull(record.ttl()); + while (recordSetIterator.hasNext()) { + RecordSet recordSet = recordSetIterator.next(); + assertEquals(recordSets.get(counter).records(), recordSet.records()); + assertEquals(recordSets.get(counter).name(), recordSet.name()); + assertEquals(recordSets.get(counter).type(), recordSet.type()); + assertNull(recordSet.ttl()); counter++; } assertEquals(2, counter); - dnsRecordIterator = DNS.listDnsRecords(zone.name(), - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TYPE), - Dns.DnsRecordListOption.pageSize(1)).iterateAll(); // also test paging + recordSetIterator = DNS.listRecordSets(zone.name(), + Dns.RecordSetListOption.fields(Dns.RecordSetField.TYPE), + Dns.RecordSetListOption.pageSize(1)).iterateAll(); // also test paging counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertEquals(dnsRecords.get(counter).type(), record.type()); - assertEquals(dnsRecords.get(counter).name(), record.name()); - assertTrue(record.records().isEmpty()); - assertNull(record.ttl()); + while (recordSetIterator.hasNext()) { + RecordSet recordSet = recordSetIterator.next(); + assertEquals(recordSets.get(counter).type(), recordSet.type()); + assertEquals(recordSets.get(counter).name(), recordSet.name()); + assertTrue(recordSet.records().isEmpty()); + assertNull(recordSet.ttl()); counter++; } assertEquals(2, counter); // test page size - Page dnsRecordPage = DNS.listDnsRecords(zone.name(), - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TYPE), - Dns.DnsRecordListOption.pageSize(1)); - assertEquals(1, ImmutableList.copyOf(dnsRecordPage.values().iterator()).size()); + Page recordSetPage = DNS.listRecordSets(zone.name(), + Dns.RecordSetListOption.fields(Dns.RecordSetField.TYPE), + Dns.RecordSetListOption.pageSize(1)); + assertEquals(1, ImmutableList.copyOf(recordSetPage.values().iterator()).size()); // test name filter ChangeRequest change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); - waitForChangeToComplete(ZONE1.name(), change.id()); - dnsRecordIterator = DNS.listDnsRecords(ZONE1.name(), - Dns.DnsRecordListOption.dnsName(A_RECORD_ZONE1.name())).iterateAll(); + waitForChangeToComplete(ZONE1.name(), change.generatedId()); + recordSetIterator = DNS.listRecordSets(ZONE1.name(), + Dns.RecordSetListOption.dnsName(A_RECORD_ZONE1.name())).iterateAll(); counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); + while (recordSetIterator.hasNext()) { + RecordSet recordSet = recordSetIterator.next(); assertTrue(ImmutableList.of(A_RECORD_ZONE1.type(), AAAA_RECORD_ZONE1.type()) - .contains(record.type())); + .contains(recordSet.type())); counter++; } assertEquals(2, counter); // test type filter - waitForChangeToComplete(ZONE1.name(), change.id()); - dnsRecordIterator = DNS.listDnsRecords(ZONE1.name(), - Dns.DnsRecordListOption.dnsName(A_RECORD_ZONE1.name()), - Dns.DnsRecordListOption.type(A_RECORD_ZONE1.type())) + waitForChangeToComplete(ZONE1.name(), change.generatedId()); + recordSetIterator = DNS.listRecordSets(ZONE1.name(), + Dns.RecordSetListOption.dnsName(A_RECORD_ZONE1.name()), + Dns.RecordSetListOption.type(A_RECORD_ZONE1.type())) .iterateAll(); counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertEquals(A_RECORD_ZONE1, record); + while (recordSetIterator.hasNext()) { + RecordSet recordSet = recordSetIterator.next(); + assertEquals(A_RECORD_ZONE1, recordSet); counter++; } assertEquals(1, counter); @@ -924,7 +933,8 @@ public void testListDnsRecords() { // check wrong arguments try { // name is not set - DNS.listDnsRecords(ZONE1.name(), Dns.DnsRecordListOption.type(A_RECORD_ZONE1.type())); + DNS.listRecordSets(ZONE1.name(), + Dns.RecordSetListOption.type(A_RECORD_ZONE1.type())); fail(); } catch (DnsException ex) { // expected @@ -932,7 +942,7 @@ public void testListDnsRecords() { assertFalse(ex.retryable()); } try { - DNS.listDnsRecords(ZONE1.name(), Dns.DnsRecordListOption.pageSize(0)); + DNS.listRecordSets(ZONE1.name(), Dns.RecordSetListOption.pageSize(0)); fail(); } catch (DnsException ex) { // expected @@ -940,14 +950,14 @@ public void testListDnsRecords() { assertFalse(ex.retryable()); } try { - DNS.listDnsRecords(ZONE1.name(), Dns.DnsRecordListOption.pageSize(-1)); + DNS.listRecordSets(ZONE1.name(), Dns.RecordSetListOption.pageSize(-1)); fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.code()); assertFalse(ex.retryable()); } - waitForChangeToComplete(ZONE1.name(), change.id()); + waitForChangeToComplete(ZONE1.name(), change.generatedId()); } finally { clear(); } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/testing/LocalDnsHelperTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/testing/LocalDnsHelperTest.java index 59002131cc9d..315a47c5bb7c 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/testing/LocalDnsHelperTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/testing/LocalDnsHelperTest.java @@ -119,19 +119,12 @@ private static void resetProjects() { } } - private static void assertEqChangesIgnoreStatus(Change expected, Change actual) { - assertEquals(expected.getAdditions(), actual.getAdditions()); - assertEquals(expected.getDeletions(), actual.getDeletions()); - assertEquals(expected.getId(), actual.getId()); - assertEquals(expected.getStartTime(), actual.getStartTime()); - } - @Test public void testCreateZone() { ManagedZone created = RPC.create(ZONE1, EMPTY_RPC_OPTIONS); // check that default records were created DnsRpc.ListResult listResult - = RPC.listDnsRecords(ZONE1.getName(), EMPTY_RPC_OPTIONS); + = RPC.listRecordSets(ZONE1.getName(), EMPTY_RPC_OPTIONS); ImmutableList defaultTypes = ImmutableList.of("SOA", "NS"); Iterator iterator = listResult.results().iterator(); assertTrue(defaultTypes.contains(iterator.next().getType())); @@ -395,7 +388,7 @@ private static void executeCreateAndApplyChangeTest(DnsRpc rpc) { rpc.applyChangeRequest(ZONE1.getName(), CHANGE_KEEP, EMPTY_RPC_OPTIONS); waitForChangeToComplete(rpc, ZONE1.getName(), "3"); Iterable results = - rpc.listDnsRecords(ZONE1.getName(), EMPTY_RPC_OPTIONS).results(); + rpc.listRecordSets(ZONE1.getName(), EMPTY_RPC_OPTIONS).results(); List defaults = ImmutableList.of("SOA", "NS"); boolean rrsetKeep = false; boolean rrset1 = false; @@ -692,7 +685,7 @@ public void testListZones() { public void testListDnsRecords() { // no zone exists try { - RPC.listDnsRecords(ZONE_NAME1, EMPTY_RPC_OPTIONS); + RPC.listRecordSets(ZONE_NAME1, EMPTY_RPC_OPTIONS); fail(); } catch (DnsException ex) { // expected @@ -702,19 +695,19 @@ public void testListDnsRecords() { // zone exists but has no records RPC.create(ZONE1, EMPTY_RPC_OPTIONS); Iterable results = - RPC.listDnsRecords(ZONE_NAME1, EMPTY_RPC_OPTIONS).results(); + RPC.listRecordSets(ZONE_NAME1, EMPTY_RPC_OPTIONS).results(); ImmutableList records = ImmutableList.copyOf(results); assertEquals(2, records.size()); // contains default NS and SOA // zone has records RPC.applyChangeRequest(ZONE_NAME1, CHANGE_KEEP, EMPTY_RPC_OPTIONS); - results = RPC.listDnsRecords(ZONE_NAME1, EMPTY_RPC_OPTIONS).results(); + results = RPC.listRecordSets(ZONE_NAME1, EMPTY_RPC_OPTIONS).results(); records = ImmutableList.copyOf(results); assertEquals(3, records.size()); // error in options Map options = new HashMap<>(); options.put(DnsRpc.Option.PAGE_SIZE, 0); try { - RPC.listDnsRecords(ZONE1.getName(), options); + RPC.listRecordSets(ZONE1.getName(), options); fail(); } catch (DnsException ex) { // expected @@ -723,7 +716,7 @@ public void testListDnsRecords() { } options.put(DnsRpc.Option.PAGE_SIZE, -1); try { - RPC.listDnsRecords(ZONE1.getName(), options); + RPC.listRecordSets(ZONE1.getName(), options); fail(); } catch (DnsException ex) { // expected @@ -731,14 +724,14 @@ public void testListDnsRecords() { assertTrue(ex.getMessage().contains("parameters.maxResults")); } options.put(DnsRpc.Option.PAGE_SIZE, 15); - results = RPC.listDnsRecords(ZONE1.getName(), options).results(); + results = RPC.listRecordSets(ZONE1.getName(), options).results(); records = ImmutableList.copyOf(results); assertEquals(3, records.size()); // dnsName filter options = new HashMap<>(); options.put(DnsRpc.Option.NAME, "aaa"); try { - RPC.listDnsRecords(ZONE1.getName(), options); + RPC.listRecordSets(ZONE1.getName(), options); fail(); } catch (DnsException ex) { // expected @@ -746,13 +739,13 @@ public void testListDnsRecords() { assertTrue(ex.getMessage().contains("parameters.name")); } options.put(DnsRpc.Option.NAME, "aaa."); - results = RPC.listDnsRecords(ZONE1.getName(), options).results(); + results = RPC.listRecordSets(ZONE1.getName(), options).results(); records = ImmutableList.copyOf(results); assertEquals(0, records.size()); options.put(DnsRpc.Option.NAME, null); options.put(DnsRpc.Option.DNS_TYPE, "A"); try { - RPC.listDnsRecords(ZONE1.getName(), options); + RPC.listRecordSets(ZONE1.getName(), options); fail(); } catch (DnsException ex) { // expected @@ -762,7 +755,7 @@ public void testListDnsRecords() { options.put(DnsRpc.Option.NAME, "aaa."); options.put(DnsRpc.Option.DNS_TYPE, "a"); try { - RPC.listDnsRecords(ZONE1.getName(), options); + RPC.listRecordSets(ZONE1.getName(), options); fail(); } catch (DnsException ex) { // expected @@ -771,14 +764,14 @@ public void testListDnsRecords() { } options.put(DnsRpc.Option.NAME, DNS_NAME); options.put(DnsRpc.Option.DNS_TYPE, "SOA"); - results = RPC.listDnsRecords(ZONE1.getName(), options).results(); + results = RPC.listRecordSets(ZONE1.getName(), options).results(); records = ImmutableList.copyOf(results); assertEquals(1, records.size()); // field options options = new HashMap<>(); options.put(DnsRpc.Option.FIELDS, "rrsets(name)"); DnsRpc.ListResult listResult = - RPC.listDnsRecords(ZONE1.getName(), options); + RPC.listRecordSets(ZONE1.getName(), options); records = ImmutableList.copyOf(listResult.results()); ResourceRecordSet record = records.get(0); assertNotNull(record.getName()); @@ -787,7 +780,7 @@ public void testListDnsRecords() { assertNull(record.getTtl()); assertNull(listResult.pageToken()); options.put(DnsRpc.Option.FIELDS, "rrsets(rrdatas)"); - listResult = RPC.listDnsRecords(ZONE1.getName(), options); + listResult = RPC.listRecordSets(ZONE1.getName(), options); records = ImmutableList.copyOf(listResult.results()); record = records.get(0); assertNull(record.getName()); @@ -796,7 +789,7 @@ record = records.get(0); assertNull(record.getTtl()); assertNull(listResult.pageToken()); options.put(DnsRpc.Option.FIELDS, "rrsets(ttl)"); - listResult = RPC.listDnsRecords(ZONE1.getName(), options); + listResult = RPC.listRecordSets(ZONE1.getName(), options); records = ImmutableList.copyOf(listResult.results()); record = records.get(0); assertNull(record.getName()); @@ -805,7 +798,7 @@ record = records.get(0); assertNotNull(record.getTtl()); assertNull(listResult.pageToken()); options.put(DnsRpc.Option.FIELDS, "rrsets(type)"); - listResult = RPC.listDnsRecords(ZONE1.getName(), options); + listResult = RPC.listRecordSets(ZONE1.getName(), options); records = ImmutableList.copyOf(listResult.results()); record = records.get(0); assertNull(record.getName()); @@ -814,7 +807,7 @@ record = records.get(0); assertNull(record.getTtl()); assertNull(listResult.pageToken()); options.put(DnsRpc.Option.FIELDS, "nextPageToken"); - listResult = RPC.listDnsRecords(ZONE1.getName(), options); + listResult = RPC.listRecordSets(ZONE1.getName(), options); records = ImmutableList.copyOf(listResult.results()); record = records.get(0); assertNull(record.getName()); @@ -824,7 +817,7 @@ record = records.get(0); assertNull(listResult.pageToken()); options.put(DnsRpc.Option.FIELDS, "nextPageToken,rrsets(name,rrdatas)"); options.put(DnsRpc.Option.PAGE_SIZE, 1); - listResult = RPC.listDnsRecords(ZONE1.getName(), options); + listResult = RPC.listRecordSets(ZONE1.getName(), options); records = ImmutableList.copyOf(listResult.results()); assertEquals(1, records.size()); record = records.get(0); @@ -973,15 +966,15 @@ public void testListChanges() { public void testDnsRecordPaging() { RPC.create(ZONE1, EMPTY_RPC_OPTIONS); List complete = ImmutableList.copyOf( - RPC.listDnsRecords(ZONE1.getName(), EMPTY_RPC_OPTIONS).results()); + RPC.listRecordSets(ZONE1.getName(), EMPTY_RPC_OPTIONS).results()); Map options = new HashMap<>(); options.put(DnsRpc.Option.PAGE_SIZE, 1); - DnsRpc.ListResult listResult = RPC.listDnsRecords(ZONE1.getName(), options); + DnsRpc.ListResult listResult = RPC.listRecordSets(ZONE1.getName(), options); ImmutableList records = ImmutableList.copyOf(listResult.results()); assertEquals(1, records.size()); assertEquals(complete.get(0), records.get(0)); options.put(DnsRpc.Option.PAGE_TOKEN, listResult.pageToken()); - listResult = RPC.listDnsRecords(ZONE1.getName(), options); + listResult = RPC.listRecordSets(ZONE1.getName(), options); records = ImmutableList.copyOf(listResult.results()); assertEquals(1, records.size()); assertEquals(complete.get(1), records.get(0)); diff --git a/gcloud-java-examples/README.md b/gcloud-java-examples/README.md index fc9ce9ef653d..fc6b7c28f636 100644 --- a/gcloud-java-examples/README.md +++ b/gcloud-java-examples/README.md @@ -19,16 +19,16 @@ If you are using Maven, add this to your pom.xml file com.google.gcloud gcloud-java-examples - 0.1.5 + 0.1.7 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.gcloud:gcloud-java-examples:0.1.5' +compile 'com.google.gcloud:gcloud-java-examples:0.1.7' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.gcloud" % "gcloud-java-examples" % "0.1.5" +libraryDependencies += "com.google.gcloud" % "gcloud-java-examples" % "0.1.7" ``` To run examples from your command line: @@ -75,7 +75,7 @@ To run examples from your command line: Note that you have to enable the Google Cloud DNS API on the [Google Developers Console][developers-console] before running the following commands. You will need to replace the domain name `elaborateexample.com` with your own domain name with [verified ownership] (https://www.google.com/webmasters/verification/home). - Also, note that the example creates and deletes DNS records of type A only. Operations with other record types are not implemented in the example. + Also, note that the example creates and deletes record sets of type A only. Operations with other record types are not implemented in the example. ``` mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.dns.DnsExample" -Dexec.args="create some-sample-zone elaborateexample.com. description" mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.dns.DnsExample" -Dexec.args="list" @@ -98,7 +98,7 @@ To run examples from your command line: * Here's an example run of `StorageExample`. - Before running the example, go to the [Google Developers Console][developers-console] to ensure that Google Cloud Storage API is enabled and that you have a bucket. Also ensure that you have a test file (`test.txt` is chosen here) to upload to Cloud Storage stored locally on your machine. + Before running the example, go to the [Google Developers Console][developers-console] to ensure that "Google Cloud Storage" and "Google Cloud Storage JSON API" are enabled and that you have a bucket. Also ensure that you have a test file (`test.txt` is chosen here) to upload to Cloud Storage stored locally on your machine. ``` mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.storage.StorageExample" -Dexec.args="upload /path/to/test.txt " mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.storage.StorageExample" -Dexec.args="list " diff --git a/gcloud-java-examples/pom.xml b/gcloud-java-examples/pom.xml index 111308658c2e..f5d4cb290118 100644 --- a/gcloud-java-examples/pom.xml +++ b/gcloud-java-examples/pom.xml @@ -10,7 +10,7 @@ com.google.gcloud gcloud-java-pom - 0.1.6-SNAPSHOT + 0.1.8-SNAPSHOT gcloud-java-examples diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/DnsExample.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/DnsExample.java index 1b6ba8f179da..d0cda485e9f5 100644 --- a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/DnsExample.java +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/DnsExample.java @@ -19,17 +19,18 @@ import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.gcloud.dns.ChangeRequest; +import com.google.gcloud.dns.ChangeRequestInfo; import com.google.gcloud.dns.Dns; import com.google.gcloud.dns.DnsOptions; -import com.google.gcloud.dns.DnsRecord; import com.google.gcloud.dns.ProjectInfo; +import com.google.gcloud.dns.RecordSet; import com.google.gcloud.dns.Zone; import com.google.gcloud.dns.ZoneInfo; -import java.text.DateFormat; -import java.text.SimpleDateFormat; +import org.joda.time.format.DateTimeFormat; +import org.joda.time.format.DateTimeFormatter; + import java.util.Arrays; -import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; @@ -38,8 +39,8 @@ /** * An example of using Google Cloud DNS. * - *

This example creates, deletes, gets, and lists zones. It also creates and deletes DNS records - * of type A, and lists DNS records. + *

This example creates, deletes, gets, and lists zones. It also creates and deletes + * record sets of type A, and lists record sets. * *

Steps needed for running the example: *

    @@ -66,7 +67,8 @@ public class DnsExample { private static final Map ACTIONS = new HashMap<>(); - private static final DateFormat FORMATTER = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss"); + private static final DateTimeFormatter FORMATTER = + DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss"); private interface DnsAction { void run(Dns dns, String... args); @@ -89,7 +91,7 @@ public void run(Dns dns, String... args) { ZoneInfo zoneInfo = ZoneInfo.of(zoneName, dnsName, description); Zone zone = dns.create(zoneInfo); System.out.printf("Successfully created zone with name %s which was assigned ID %s.%n", - zone.name(), zone.id()); + zone.name(), zone.generatedId()); } @Override @@ -203,16 +205,16 @@ public void run(Dns dns, String... args) { if (args.length > 3) { ttl = Integer.parseInt(args[3]); } - DnsRecord record = DnsRecord.builder(recordName, DnsRecord.Type.A) + RecordSet recordSet = RecordSet.builder(recordName, RecordSet.Type.A) .records(ImmutableList.of(ip)) .ttl(ttl, TimeUnit.SECONDS) .build(); - ChangeRequest changeRequest = ChangeRequest.builder() - .delete(record) + ChangeRequestInfo changeRequest = ChangeRequest.builder() + .delete(recordSet) .build(); changeRequest = dns.applyChangeRequest(zoneName, changeRequest); System.out.printf("The request for deleting A record %s for zone %s was successfully " - + "submitted and assigned ID %s.%n", recordName, zoneName, changeRequest.id()); + + "submitted and assigned ID %s.%n", recordName, zoneName, changeRequest.generatedId()); System.out.print("Waiting for deletion to happen..."); waitForChangeToFinish(dns, zoneName, changeRequest); System.out.printf("%nThe deletion has been completed.%n"); @@ -238,7 +240,7 @@ public boolean check(String... args) { private static class AddDnsRecordAction implements DnsAction { /** - * Adds a DNS record of type A. The last parameter is ttl and is not required. If ttl is not + * Adds a record set of type A. The last parameter is ttl and is not required. If ttl is not * provided, a default value of 0 will be used. */ @Override @@ -250,14 +252,14 @@ public void run(Dns dns, String... args) { if (args.length > 3) { ttl = Integer.parseInt(args[3]); } - DnsRecord record = DnsRecord.builder(recordName, DnsRecord.Type.A) + RecordSet recordSet = RecordSet.builder(recordName, RecordSet.Type.A) .records(ImmutableList.of(ip)) .ttl(ttl, TimeUnit.SECONDS) .build(); - ChangeRequest changeRequest = ChangeRequest.builder().add(record).build(); + ChangeRequestInfo changeRequest = ChangeRequest.builder().add(recordSet).build(); changeRequest = dns.applyChangeRequest(zoneName, changeRequest); System.out.printf("The request for adding A record %s for zone %s was successfully " - + "submitted and assigned ID %s.%n", recordName, zoneName, changeRequest.id()); + + "submitted and assigned ID %s.%n", recordName, zoneName, changeRequest.generatedId()); System.out.print("Waiting for addition to happen..."); waitForChangeToFinish(dns, zoneName, changeRequest); System.out.printf("The addition has been completed.%n"); @@ -283,21 +285,21 @@ public boolean check(String... args) { private static class ListDnsRecordsAction implements DnsAction { /** - * Lists all the DNS records in the given zone. + * Lists all the record sets in the given zone. */ @Override public void run(Dns dns, String... args) { String zoneName = args[0]; - Iterator iterator = dns.listDnsRecords(zoneName).iterateAll(); + Iterator iterator = dns.listRecordSets(zoneName).iterateAll(); if (iterator.hasNext()) { - System.out.printf("DNS records for zone %s:%n", zoneName); + System.out.printf("Record sets for zone %s:%n", zoneName); while (iterator.hasNext()) { - DnsRecord record = iterator.next(); - System.out.printf("%nRecord name: %s%nTTL: %s%nRecords: %s%n", record.name(), - record.ttl(), Joiner.on(", ").join(record.records())); + RecordSet recordSet = iterator.next(); + System.out.printf("%nRecord name: %s%nTTL: %s%nRecords: %s%n", recordSet.name(), + recordSet.ttl(), Joiner.on(", ").join(recordSet.records())); } } else { - System.out.printf("Zone %s has no DNS records.%n", zoneName); + System.out.printf("Zone %s has no record sets records.%n", zoneName); } } @@ -333,9 +335,9 @@ public void run(Dns dns, String... args) { System.out.printf("Change requests for zone %s:%n", zoneName); while (iterator.hasNext()) { ChangeRequest change = iterator.next(); - System.out.printf("%nID: %s%n", change.id()); + System.out.printf("%nID: %s%n", change.generatedId()); System.out.printf("Status: %s%n", change.status()); - System.out.printf("Started: %s%n", FORMATTER.format(change.startTimeMillis())); + System.out.printf("Started: %s%n", FORMATTER.print(change.startTimeMillis())); System.out.printf("Deletions: %s%n", Joiner.on(", ").join(change.deletions())); System.out.printf("Additions: %s%n", Joiner.on(", ").join(change.additions())); } @@ -361,8 +363,8 @@ private static class ListAction implements DnsAction { /** * Invokes a list action. If no parameter is provided, lists all zones. If zone name is the only - * parameter provided, lists both DNS records and changes. Otherwise, invokes listing changes or - * zones based on the parameter provided. + * parameter provided, lists both record sets and changes. Otherwise, invokes listing + * changes or zones based on the parameter provided. */ @Override public void run(Dns dns, String... args) { @@ -406,7 +408,7 @@ public void run(Dns dns, String... args) { ProjectInfo.Quota quota = project.quota(); System.out.printf("Project id: %s%nQuota:%n", dns.options().projectId()); System.out.printf("\tZones: %d%n", quota.zones()); - System.out.printf("\tDNS records per zone: %d%n", quota.rrsetsPerZone()); + System.out.printf("\tRecord sets per zone: %d%n", quota.rrsetsPerZone()); System.out.printf("\tRecord sets per DNS record: %d%n", quota.resourceRecordsPerRrset()); System.out.printf("\tAdditions per change: %d%n", quota.rrsetAdditionsPerChange()); @@ -438,15 +440,15 @@ public boolean check(String... args) { private static void printZone(Zone zone) { System.out.printf("%nName: %s%n", zone.name()); - System.out.printf("ID: %s%n", zone.id()); + System.out.printf("ID: %s%n", zone.generatedId()); System.out.printf("Description: %s%n", zone.description()); - System.out.printf("Created: %s%n", FORMATTER.format(new Date(zone.creationTimeMillis()))); + System.out.printf("Created: %s%n", FORMATTER.print(zone.creationTimeMillis())); System.out.printf("Name servers: %s%n", Joiner.on(", ").join(zone.nameServers())); } - private static ChangeRequest waitForChangeToFinish(Dns dns, String zoneName, - ChangeRequest request) { - ChangeRequest current = request; + private static ChangeRequestInfo waitForChangeToFinish(Dns dns, String zoneName, + ChangeRequestInfo request) { + ChangeRequestInfo current = request; while (current.status().equals(ChangeRequest.Status.PENDING)) { System.out.print("."); try { @@ -454,7 +456,7 @@ private static ChangeRequest waitForChangeToFinish(Dns dns, String zoneName, } catch (InterruptedException e) { System.err.println("Thread was interrupted while waiting."); } - current = dns.getChangeRequest(zoneName, current.id()); + current = dns.getChangeRequest(zoneName, current.generatedId()); } return current; } diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateDnsRecords.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateRecordSets.java similarity index 75% rename from gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateDnsRecords.java rename to gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateRecordSets.java index 71327ba98a96..e3ddbb10fc0f 100644 --- a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateDnsRecords.java +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateRecordSets.java @@ -22,19 +22,19 @@ package com.google.gcloud.examples.dns.snippets; -import com.google.gcloud.dns.ChangeRequest; +import com.google.gcloud.dns.ChangeRequestInfo; import com.google.gcloud.dns.Dns; import com.google.gcloud.dns.DnsOptions; -import com.google.gcloud.dns.DnsRecord; +import com.google.gcloud.dns.RecordSet; import com.google.gcloud.dns.Zone; import java.util.Iterator; import java.util.concurrent.TimeUnit; /** - * A snippet for Google Cloud DNS showing how to create and update a DNS record. + * A snippet for Google Cloud DNS showing how to create and update a resource record set. */ -public class CreateOrUpdateDnsRecords { +public class CreateOrUpdateRecordSets { public static void main(String... args) { // Create a service object. @@ -47,28 +47,28 @@ public static void main(String... args) { // Get zone from the service Zone zone = dns.getZone(zoneName); - // Prepare a www.. type A record with ttl of 24 hours + // Prepare a www.. type A record set with ttl of 24 hours String ip = "12.13.14.15"; - DnsRecord toCreate = DnsRecord.builder("www." + zone.dnsName(), DnsRecord.Type.A) + RecordSet toCreate = RecordSet.builder("www." + zone.dnsName(), RecordSet.Type.A) .ttl(24, TimeUnit.HOURS) .addRecord(ip) .build(); // Make a change - ChangeRequest.Builder changeBuilder = ChangeRequest.builder().add(toCreate); + ChangeRequestInfo.Builder changeBuilder = ChangeRequestInfo.builder().add(toCreate); // Verify a www.. type A record does not exist yet. // If it does exist, we will overwrite it with our prepared record. - Iterator recordIterator = zone.listDnsRecords().iterateAll(); - while (recordIterator.hasNext()) { - DnsRecord current = recordIterator.next(); + Iterator recordSetIterator = zone.listRecordSets().iterateAll(); + while (recordSetIterator.hasNext()) { + RecordSet current = recordSetIterator.next(); if (toCreate.name().equals(current.name()) && toCreate.type().equals(current.type())) { changeBuilder.delete(current); } } // Build and apply the change request to our zone - ChangeRequest changeRequest = changeBuilder.build(); + ChangeRequestInfo changeRequest = changeBuilder.build(); zone.applyChangeRequest(changeRequest); } } diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateZone.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateZone.java index 2c2ba211bd86..dcf8019319c3 100644 --- a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateZone.java +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateZone.java @@ -46,6 +46,6 @@ public static void main(String... args) { // Create zone in Google Cloud DNS Zone zone = dns.create(zoneInfo); - System.out.printf("Zone was created and assigned ID %s.%n", zone.id()); + System.out.printf("Zone was created and assigned ID %s.%n", zone.generatedId()); } } diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/DeleteZone.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/DeleteZone.java index e841a4cd54ed..c791ea8c0992 100644 --- a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/DeleteZone.java +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/DeleteZone.java @@ -23,9 +23,10 @@ package com.google.gcloud.examples.dns.snippets; import com.google.gcloud.dns.ChangeRequest; +import com.google.gcloud.dns.ChangeRequestInfo; import com.google.gcloud.dns.Dns; import com.google.gcloud.dns.DnsOptions; -import com.google.gcloud.dns.DnsRecord; +import com.google.gcloud.dns.RecordSet; import java.util.Iterator; @@ -43,28 +44,26 @@ public static void main(String... args) { // Change this to a zone name that exists within your project and that you want to delete. String zoneName = "my-unique-zone"; - // Get iterator for the existing records which have to be deleted before deleting the zone - Iterator recordIterator = dns.listDnsRecords(zoneName).iterateAll(); + // Get iterator for the existing record sets which have to be deleted before deleting the zone + Iterator recordIterator = dns.listRecordSets(zoneName).iterateAll(); // Make a change for deleting the records - ChangeRequest.Builder changeBuilder = ChangeRequest.builder(); + ChangeRequestInfo.Builder changeBuilder = ChangeRequestInfo.builder(); while (recordIterator.hasNext()) { - DnsRecord current = recordIterator.next(); + RecordSet current = recordIterator.next(); // SOA and NS records cannot be deleted - if (!DnsRecord.Type.SOA.equals(current.type()) && !DnsRecord.Type.NS.equals(current.type())) { + if (!RecordSet.Type.SOA.equals(current.type()) && !RecordSet.Type.NS.equals(current.type())) { changeBuilder.delete(current); } } // Build and apply the change request to our zone if it contains records to delete - ChangeRequest changeRequest = changeBuilder.build(); + ChangeRequestInfo changeRequest = changeBuilder.build(); if (!changeRequest.deletions().isEmpty()) { - changeRequest = dns.applyChangeRequest(zoneName, changeRequest); + ChangeRequest pendingRequest = dns.applyChangeRequest(zoneName, changeRequest); - // Wait for change to finish, but save data traffic by transferring only ID and status - Dns.ChangeRequestOption option = - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS); - while (ChangeRequest.Status.PENDING.equals(changeRequest.status())) { + // Wait for the change request to complete + while (!pendingRequest.isDone()) { System.out.println("Waiting for change to complete. Going to sleep for 500ms..."); try { Thread.sleep(500); @@ -72,8 +71,6 @@ public static void main(String... args) { System.err.println("The thread was interrupted while waiting for change request to be " + "processed."); } - // Update the change, but fetch only change ID and status - changeRequest = dns.getChangeRequest(zoneName, changeRequest.id(), option); } } diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecords.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecordSets.java similarity index 72% rename from gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecords.java rename to gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecordSets.java index 4de262386d53..c96c93191c10 100644 --- a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecords.java +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecordSets.java @@ -23,9 +23,10 @@ package com.google.gcloud.examples.dns.snippets; import com.google.gcloud.dns.ChangeRequest; +import com.google.gcloud.dns.ChangeRequestInfo; import com.google.gcloud.dns.Dns; import com.google.gcloud.dns.DnsOptions; -import com.google.gcloud.dns.DnsRecord; +import com.google.gcloud.dns.RecordSet; import com.google.gcloud.dns.Zone; import com.google.gcloud.dns.ZoneInfo; @@ -35,9 +36,9 @@ /** * A complete snippet for Google Cloud DNS showing how to create and delete a zone. It also shows - * how to create, list and delete DNS records, and how to list changes. + * how to create, list and delete record sets, and how to list changes. */ -public class ManipulateZonesAndRecords { +public class ManipulateZonesAndRecordSets { public static void main(String... args) { Dns dns = DnsOptions.defaultInstance().service(); @@ -50,7 +51,7 @@ public static void main(String... args) { // Create zone in Google Cloud DNS Zone zone = dns.create(zoneInfo); - System.out.printf("Zone was created and assigned ID %s.%n", zone.id()); + System.out.printf("Zone was created and assigned ID %s.%n", zone.generatedId()); // Print assigned name servers List nameServers = zone.nameServers(); @@ -60,35 +61,35 @@ public static void main(String... args) { // Prepare a www.someexampledomain.com. type A record with ttl of 24 hours String ip = "12.13.14.15"; - DnsRecord toCreate = DnsRecord.builder("www.someexampledomain.com.", DnsRecord.Type.A) + RecordSet toCreate = RecordSet.builder("www.someexampledomain.com.", RecordSet.Type.A) .ttl(24, TimeUnit.HOURS) .addRecord(ip) .build(); // Make a change - ChangeRequest.Builder changeBuilder = ChangeRequest.builder().add(toCreate); + ChangeRequestInfo.Builder changeBuilder = ChangeRequestInfo.builder().add(toCreate); // Verify the type A record does not exist yet. // If it does exist, we will overwrite it with our prepared record. - Iterator recordIterator = zone.listDnsRecords().iterateAll(); - while (recordIterator.hasNext()) { - DnsRecord current = recordIterator.next(); + Iterator recordSetIterator = zone.listRecordSets().iterateAll(); + while (recordSetIterator.hasNext()) { + RecordSet current = recordSetIterator.next(); if (toCreate.name().equals(current.name()) && toCreate.type().equals(current.type())) { changeBuilder.delete(current); } } // Build and apply the change request to our zone - ChangeRequest changeRequest = changeBuilder.build(); + ChangeRequestInfo changeRequest = changeBuilder.build(); zone.applyChangeRequest(changeRequest); - while (ChangeRequest.Status.PENDING.equals(changeRequest.status())) { + while (ChangeRequestInfo.Status.PENDING.equals(changeRequest.status())) { try { Thread.sleep(500L); } catch (InterruptedException e) { System.err.println("The thread was interrupted while waiting..."); } - changeRequest = dns.getChangeRequest(zone.name(), changeRequest.id()); + changeRequest = dns.getChangeRequest(zone.name(), changeRequest.generatedId()); } System.out.println("The change request has been applied."); @@ -100,11 +101,11 @@ public static void main(String... args) { counter++; } - // List the DNS records in a particular zone - recordIterator = zone.listDnsRecords().iterateAll(); - System.out.println(String.format("DNS records inside %s:", zone.name())); - while (recordIterator.hasNext()) { - System.out.println(recordIterator.next()); + // List the record sets in a particular zone + recordSetIterator = zone.listRecordSets().iterateAll(); + System.out.println(String.format("Record sets inside %s:", zone.name())); + while (recordSetIterator.hasNext()) { + System.out.println(recordSetIterator.next()); } // List the change requests applied to a particular zone @@ -114,12 +115,12 @@ public static void main(String... args) { System.out.println(changeIterator.next()); } - // Make a change for deleting the records - changeBuilder = ChangeRequest.builder(); - while (recordIterator.hasNext()) { - DnsRecord current = recordIterator.next(); + // Make a change for deleting the record sets + changeBuilder = ChangeRequestInfo.builder(); + while (recordSetIterator.hasNext()) { + RecordSet current = recordSetIterator.next(); // SOA and NS records cannot be deleted - if (!DnsRecord.Type.SOA.equals(current.type()) && !DnsRecord.Type.NS.equals(current.type())) { + if (!RecordSet.Type.SOA.equals(current.type()) && !RecordSet.Type.NS.equals(current.type())) { changeBuilder.delete(current); } } @@ -127,12 +128,10 @@ public static void main(String... args) { // Build and apply the change request to our zone if it contains records to delete changeRequest = changeBuilder.build(); if (!changeRequest.deletions().isEmpty()) { - changeRequest = dns.applyChangeRequest(zoneName, changeRequest); + ChangeRequest pendingRequest = dns.applyChangeRequest(zoneName, changeRequest); - // Wait for change to finish, but save data traffic by transferring only ID and status - Dns.ChangeRequestOption option = - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS); - while (ChangeRequest.Status.PENDING.equals(changeRequest.status())) { + // Wait for the change request to complete + while (!pendingRequest.isDone()) { System.out.println("Waiting for change to complete. Going to sleep for 500ms..."); try { Thread.sleep(500); @@ -140,9 +139,6 @@ public static void main(String... args) { System.err.println("The thread was interrupted while waiting for change request to be " + "processed."); } - - // Update the change, but fetch only change ID and status - changeRequest = dns.getChangeRequest(zoneName, changeRequest.id(), option); } } diff --git a/gcloud-java-resourcemanager/README.md b/gcloud-java-resourcemanager/README.md index a2539df7adab..667e9222a402 100644 --- a/gcloud-java-resourcemanager/README.md +++ b/gcloud-java-resourcemanager/README.md @@ -22,16 +22,16 @@ If you are using Maven, add this to your pom.xml file com.google.gcloud gcloud-java-resourcemanager - 0.1.5 + 0.1.7 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.gcloud:gcloud-java-resourcemanager:0.1.5' +compile 'com.google.gcloud:gcloud-java-resourcemanager:0.1.7' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.gcloud" % "gcloud-java-resourcemanager" % "0.1.5" +libraryDependencies += "com.google.gcloud" % "gcloud-java-resourcemanager" % "0.1.7" ``` Example Application diff --git a/gcloud-java-resourcemanager/pom.xml b/gcloud-java-resourcemanager/pom.xml index c0c48af48f1e..d970bdf883da 100644 --- a/gcloud-java-resourcemanager/pom.xml +++ b/gcloud-java-resourcemanager/pom.xml @@ -10,7 +10,7 @@ com.google.gcloud gcloud-java-pom - 0.1.6-SNAPSHOT + 0.1.8-SNAPSHOT gcloud-java-resourcemanager diff --git a/gcloud-java-resourcemanager/src/main/java/com/google/gcloud/resourcemanager/Option.java b/gcloud-java-resourcemanager/src/main/java/com/google/gcloud/resourcemanager/Option.java index 72d62d7fc224..3df68468f69f 100644 --- a/gcloud-java-resourcemanager/src/main/java/com/google/gcloud/resourcemanager/Option.java +++ b/gcloud-java-resourcemanager/src/main/java/com/google/gcloud/resourcemanager/Option.java @@ -27,7 +27,7 @@ /** * Base class for Resource Manager operation options. */ -class Option implements Serializable { +abstract class Option implements Serializable { private static final long serialVersionUID = 2655177550880762967L; diff --git a/gcloud-java-resourcemanager/src/main/java/com/google/gcloud/resourcemanager/ResourceManager.java b/gcloud-java-resourcemanager/src/main/java/com/google/gcloud/resourcemanager/ResourceManager.java index 70eeb9c8eb50..92494a5152fe 100644 --- a/gcloud-java-resourcemanager/src/main/java/com/google/gcloud/resourcemanager/ResourceManager.java +++ b/gcloud-java-resourcemanager/src/main/java/com/google/gcloud/resourcemanager/ResourceManager.java @@ -16,15 +16,15 @@ package com.google.gcloud.resourcemanager; -import com.google.common.base.Joiner; -import com.google.common.collect.Sets; +import com.google.common.collect.ImmutableList; +import com.google.gcloud.FieldSelector; +import com.google.gcloud.FieldSelector.Helper; import com.google.gcloud.IamPolicy; import com.google.gcloud.Page; import com.google.gcloud.Service; import com.google.gcloud.resourcemanager.spi.ResourceManagerRpc; import java.util.List; -import java.util.Set; /** * An interface for Google Cloud Resource Manager. @@ -42,7 +42,7 @@ public interface ResourceManager extends Service { * {@link ResourceManager#get} or {@link ResourceManager#list}. Project ID is always returned, * even if not specified. */ - enum ProjectField { + enum ProjectField implements FieldSelector { PROJECT_ID("projectId"), NAME("name"), LABELS("labels"), @@ -50,24 +50,18 @@ enum ProjectField { STATE("lifecycleState"), CREATE_TIME("createTime"); + static final List REQUIRED_FIELDS = ImmutableList.of(PROJECT_ID); + private final String selector; ProjectField(String selector) { this.selector = selector; } + @Override public String selector() { return selector; } - - static String selector(ProjectField... fields) { - Set fieldStrings = Sets.newHashSetWithExpectedSize(fields.length + 1); - fieldStrings.add(PROJECT_ID.selector()); - for (ProjectField field : fields) { - fieldStrings.add(field.selector()); - } - return Joiner.on(',').join(fieldStrings); - } } /** @@ -90,7 +84,8 @@ private ProjectGetOption(ResourceManagerRpc.Option option, Object value) { * that can be used. */ public static ProjectGetOption fields(ProjectField... fields) { - return new ProjectGetOption(ResourceManagerRpc.Option.FIELDS, ProjectField.selector(fields)); + return new ProjectGetOption(ResourceManagerRpc.Option.FIELDS, + Helper.selector(ProjectField.REQUIRED_FIELDS, fields)); } } @@ -163,9 +158,8 @@ public static ProjectListOption pageSize(int pageSize) { * that can be used. */ public static ProjectListOption fields(ProjectField... fields) { - StringBuilder builder = new StringBuilder(); - builder.append("projects(").append(ProjectField.selector(fields)).append("),nextPageToken"); - return new ProjectListOption(ResourceManagerRpc.Option.FIELDS, builder.toString()); + return new ProjectListOption(ResourceManagerRpc.Option.FIELDS, + Helper.listSelector("projects", ProjectField.REQUIRED_FIELDS, fields)); } } diff --git a/gcloud-java-resourcemanager/src/main/java/com/google/gcloud/resourcemanager/testing/package-info.java b/gcloud-java-resourcemanager/src/main/java/com/google/gcloud/resourcemanager/testing/package-info.java index 7e5519f7d085..b0165c1ddd9d 100644 --- a/gcloud-java-resourcemanager/src/main/java/com/google/gcloud/resourcemanager/testing/package-info.java +++ b/gcloud-java-resourcemanager/src/main/java/com/google/gcloud/resourcemanager/testing/package-info.java @@ -22,11 +22,12 @@ *
     {@code
      * LocalResourceManagerHelper resourceManagerHelper = LocalResourceManagerHelper.create();
      * ResourceManager resourceManager = resourceManagerHelper.options().service();
    - * } 
    + * resourceManagerHelper.start(); + * } * *

    After the test: *

     {@code
      * resourceManagerHelper.stop();
    - * } 
    + * } */ package com.google.gcloud.resourcemanager.testing; diff --git a/gcloud-java-resourcemanager/src/test/java/com/google/gcloud/resourcemanager/OptionTest.java b/gcloud-java-resourcemanager/src/test/java/com/google/gcloud/resourcemanager/OptionTest.java new file mode 100644 index 000000000000..729c7a4b8911 --- /dev/null +++ b/gcloud-java-resourcemanager/src/test/java/com/google/gcloud/resourcemanager/OptionTest.java @@ -0,0 +1,66 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.gcloud.resourcemanager; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; + +import com.google.gcloud.resourcemanager.spi.ResourceManagerRpc; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +public class OptionTest { + + private static final ResourceManagerRpc.Option RPC_OPTION = ResourceManagerRpc.Option.FILTER; + private static final ResourceManagerRpc.Option ANOTHER_RPC_OPTION = + ResourceManagerRpc.Option.FIELDS; + private static final String VALUE = "some value"; + private static final String OTHER_VALUE = "another value"; + private static final Option OPTION = new Option(RPC_OPTION, VALUE) {}; + private static final Option OPTION_EQUALS = new Option(RPC_OPTION, VALUE) {}; + private static final Option OPTION_NOT_EQUALS1 = new Option(RPC_OPTION, OTHER_VALUE) {}; + private static final Option OPTION_NOT_EQUALS2 = new Option(ANOTHER_RPC_OPTION, VALUE) {}; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void testEquals() { + assertEquals(OPTION, OPTION_EQUALS); + assertNotEquals(OPTION, OPTION_NOT_EQUALS1); + assertNotEquals(OPTION, OPTION_NOT_EQUALS2); + } + + @Test + public void testHashCode() { + assertEquals(OPTION.hashCode(), OPTION_EQUALS.hashCode()); + } + + @Test + public void testConstructor() { + assertEquals(RPC_OPTION, OPTION.rpcOption()); + assertEquals(VALUE, OPTION.value()); + Option option = new Option(RPC_OPTION, null) {}; + assertEquals(RPC_OPTION, option.rpcOption()); + assertNull(option.value()); + thrown.expect(NullPointerException.class); + new Option(null, VALUE) {}; + } +} diff --git a/gcloud-java-storage/README.md b/gcloud-java-storage/README.md index 0ee05b31c10c..5a8897356db8 100644 --- a/gcloud-java-storage/README.md +++ b/gcloud-java-storage/README.md @@ -22,16 +22,16 @@ If you are using Maven, add this to your pom.xml file com.google.gcloud gcloud-java-storage - 0.1.5 + 0.1.7 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.gcloud:gcloud-java-storage:0.1.5' +compile 'com.google.gcloud:gcloud-java-storage:0.1.7' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.gcloud" % "gcloud-java-storage" % "0.1.5" +libraryDependencies += "com.google.gcloud" % "gcloud-java-storage" % "0.1.7" ``` Example Application @@ -61,7 +61,7 @@ with the Cloud Storage using this Client Library. Getting Started --------------- #### Prerequisites -For this tutorial, you will need a [Google Developers Console](https://console.developers.google.com/) project with the Storage JSON API enabled. You will need to [enable billing](https://support.google.com/cloud/answer/6158867?hl=en) to use Google Cloud Storage. [Follow these instructions](https://cloud.google.com/docs/authentication#preparation) to get your project set up. You will also need to set up the local development environment by [installing the Google Cloud SDK](https://cloud.google.com/sdk/) and running the following commands in command line: `gcloud auth login` and `gcloud config set project [YOUR PROJECT ID]`. +For this tutorial, you will need a [Google Developers Console](https://console.developers.google.com/) project with "Google Cloud Storage" and "Google Cloud Storage JSON API" enabled via the console's API Manager. You will need to [enable billing](https://support.google.com/cloud/answer/6158867?hl=en) to use Google Cloud Storage. [Follow these instructions](https://cloud.google.com/docs/authentication#preparation) to get your project set up. You will also need to set up the local development environment by [installing the Google Cloud SDK](https://cloud.google.com/sdk/) and running the following commands in command line: `gcloud auth login` and `gcloud config set project [YOUR PROJECT ID]`. #### Installation and setup You'll need to obtain the `gcloud-java-storage` library. See the [Quickstart](#quickstart) section to add `gcloud-java-storage` as a dependency in your code. diff --git a/gcloud-java-storage/pom.xml b/gcloud-java-storage/pom.xml index 16427d50de3a..2316706850d3 100644 --- a/gcloud-java-storage/pom.xml +++ b/gcloud-java-storage/pom.xml @@ -10,7 +10,7 @@ com.google.gcloud gcloud-java-pom - 0.1.6-SNAPSHOT + 0.1.8-SNAPSHOT gcloud-java-storage diff --git a/gcloud-java-storage/src/main/java/com/google/gcloud/storage/Blob.java b/gcloud-java-storage/src/main/java/com/google/gcloud/storage/Blob.java index b6f668dada82..9bd9902fee56 100644 --- a/gcloud-java-storage/src/main/java/com/google/gcloud/storage/Blob.java +++ b/gcloud-java-storage/src/main/java/com/google/gcloud/storage/Blob.java @@ -178,8 +178,8 @@ public Builder blobId(BlobId blobId) { } @Override - Builder id(String id) { - infoBuilder.id(id); + Builder generatedId(String generatedId) { + infoBuilder.generatedId(generatedId); return this; } diff --git a/gcloud-java-storage/src/main/java/com/google/gcloud/storage/BlobInfo.java b/gcloud-java-storage/src/main/java/com/google/gcloud/storage/BlobInfo.java index cf509c8f0961..42a2e282b002 100644 --- a/gcloud-java-storage/src/main/java/com/google/gcloud/storage/BlobInfo.java +++ b/gcloud-java-storage/src/main/java/com/google/gcloud/storage/BlobInfo.java @@ -57,9 +57,9 @@ public StorageObject apply(BlobInfo blobInfo) { } }; - private static final long serialVersionUID = 2228487739943277159L; + private static final long serialVersionUID = -5625857076205028976L; private final BlobId blobId; - private final String id; + private final String generatedId; private final String selfLink; private final String cacheControl; private final List acl; @@ -101,7 +101,7 @@ public abstract static class Builder { */ public abstract Builder blobId(BlobId blobId); - abstract Builder id(String id); + abstract Builder generatedId(String generatedId); /** * Sets the blob's data content type. @@ -199,7 +199,7 @@ public abstract static class Builder { static final class BuilderImpl extends Builder { private BlobId blobId; - private String id; + private String generatedId; private String contentType; private String contentEncoding; private String contentDisposition; @@ -226,7 +226,7 @@ static final class BuilderImpl extends Builder { BuilderImpl(BlobInfo blobInfo) { blobId = blobInfo.blobId; - id = blobInfo.id; + generatedId = blobInfo.generatedId; cacheControl = blobInfo.cacheControl; contentEncoding = blobInfo.contentEncoding; contentType = blobInfo.contentType; @@ -255,8 +255,8 @@ public Builder blobId(BlobId blobId) { } @Override - Builder id(String id) { - this.id = id; + Builder generatedId(String generatedId) { + this.generatedId = generatedId; return this; } @@ -384,7 +384,7 @@ public BlobInfo build() { BlobInfo(BuilderImpl builder) { blobId = builder.blobId; - id = builder.id; + generatedId = builder.generatedId; cacheControl = builder.cacheControl; contentEncoding = builder.contentEncoding; contentType = builder.contentType; @@ -421,10 +421,10 @@ public String bucket() { } /** - * Returns the blob's id. + * Returns the service-generated for the blob. */ - public String id() { - return id; + public String generatedId() { + return generatedId; } /** @@ -684,7 +684,7 @@ public ObjectAccessControl apply(Acl acl) { storageObject.setComponentCount(componentCount); storageObject.setContentLanguage(contentLanguage); storageObject.setEtag(etag); - storageObject.setId(id); + storageObject.setId(generatedId); storageObject.setSelfLink(selfLink); return storageObject; } @@ -757,7 +757,7 @@ static BlobInfo fromPb(StorageObject storageObject) { builder.etag(storageObject.getEtag()); } if (storageObject.getId() != null) { - builder.id(storageObject.getId()); + builder.generatedId(storageObject.getId()); } if (storageObject.getSelfLink() != null) { builder.selfLink(storageObject.getSelfLink()); diff --git a/gcloud-java-storage/src/main/java/com/google/gcloud/storage/Bucket.java b/gcloud-java-storage/src/main/java/com/google/gcloud/storage/Bucket.java index e44bd60d785c..cb2058a9e7ab 100644 --- a/gcloud-java-storage/src/main/java/com/google/gcloud/storage/Bucket.java +++ b/gcloud-java-storage/src/main/java/com/google/gcloud/storage/Bucket.java @@ -427,8 +427,8 @@ public Builder name(String name) { } @Override - Builder id(String id) { - infoBuilder.id(id); + Builder generatedId(String generatedId) { + infoBuilder.generatedId(generatedId); return this; } diff --git a/gcloud-java-storage/src/main/java/com/google/gcloud/storage/BucketInfo.java b/gcloud-java-storage/src/main/java/com/google/gcloud/storage/BucketInfo.java index a1de1a07e03e..a893e45c5c86 100644 --- a/gcloud-java-storage/src/main/java/com/google/gcloud/storage/BucketInfo.java +++ b/gcloud-java-storage/src/main/java/com/google/gcloud/storage/BucketInfo.java @@ -64,8 +64,8 @@ public com.google.api.services.storage.model.Bucket apply(BucketInfo bucketInfo) return bucketInfo.toPb(); } }; - private static final long serialVersionUID = -3946094202176916586L; - private final String id; + private static final long serialVersionUID = -4712013629621638459L; + private final String generatedId; private final String name; private final Acl.Entity owner; private final String selfLink; @@ -326,7 +326,7 @@ public abstract static class Builder { */ public abstract Builder name(String name); - abstract Builder id(String id); + abstract Builder generatedId(String generatedId); abstract Builder owner(Acl.Entity owner); @@ -411,7 +411,7 @@ public abstract static class Builder { static final class BuilderImpl extends Builder { - private String id; + private String generatedId; private String name; private Acl.Entity owner; private String selfLink; @@ -433,7 +433,7 @@ static final class BuilderImpl extends Builder { } BuilderImpl(BucketInfo bucketInfo) { - id = bucketInfo.id; + generatedId = bucketInfo.generatedId; name = bucketInfo.name; etag = bucketInfo.etag; createTime = bucketInfo.createTime; @@ -458,8 +458,8 @@ public Builder name(String name) { } @Override - Builder id(String id) { - this.id = id; + Builder generatedId(String generatedId) { + this.generatedId = generatedId; return this; } @@ -555,7 +555,7 @@ public BucketInfo build() { } BucketInfo(BuilderImpl builder) { - id = builder.id; + generatedId = builder.generatedId; name = builder.name; etag = builder.etag; createTime = builder.createTime; @@ -574,10 +574,10 @@ public BucketInfo build() { } /** - * Returns the bucket's id. + * Returns the service-generated id for the bucket. */ - public String id() { - return id; + public String generatedId() { + return generatedId; } /** @@ -733,7 +733,7 @@ public String toString() { com.google.api.services.storage.model.Bucket toPb() { com.google.api.services.storage.model.Bucket bucketPb = new com.google.api.services.storage.model.Bucket(); - bucketPb.setId(id); + bucketPb.setId(generatedId); bucketPb.setName(name); bucketPb.setEtag(etag); if (createTime != null) { @@ -810,7 +810,7 @@ public static Builder builder(String name) { static BucketInfo fromPb(com.google.api.services.storage.model.Bucket bucketPb) { Builder builder = new BuilderImpl(bucketPb.getName()); if (bucketPb.getId() != null) { - builder.id(bucketPb.getId()); + builder.generatedId(bucketPb.getId()); } if (bucketPb.getEtag() != null) { builder.etag(bucketPb.getEtag()); diff --git a/gcloud-java-storage/src/main/java/com/google/gcloud/storage/Option.java b/gcloud-java-storage/src/main/java/com/google/gcloud/storage/Option.java index 65c55da7efc8..774023eff78b 100644 --- a/gcloud-java-storage/src/main/java/com/google/gcloud/storage/Option.java +++ b/gcloud-java-storage/src/main/java/com/google/gcloud/storage/Option.java @@ -27,7 +27,7 @@ /** * Base class for Storage operation option. */ -class Option implements Serializable { +abstract class Option implements Serializable { private static final long serialVersionUID = -73199088766477208L; diff --git a/gcloud-java-storage/src/main/java/com/google/gcloud/storage/Storage.java b/gcloud-java-storage/src/main/java/com/google/gcloud/storage/Storage.java index 78f421e94e52..72d89348f5fa 100644 --- a/gcloud-java-storage/src/main/java/com/google/gcloud/storage/Storage.java +++ b/gcloud-java-storage/src/main/java/com/google/gcloud/storage/Storage.java @@ -19,13 +19,13 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; -import com.google.common.collect.Sets; import com.google.gcloud.AuthCredentials; import com.google.gcloud.AuthCredentials.ServiceAccountAuthCredentials; +import com.google.gcloud.FieldSelector; +import com.google.gcloud.FieldSelector.Helper; import com.google.gcloud.Page; import com.google.gcloud.ReadChannel; import com.google.gcloud.Service; @@ -38,7 +38,6 @@ import java.net.URL; import java.util.Arrays; import java.util.Collections; -import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; @@ -74,7 +73,7 @@ String entry() { } } - enum BucketField { + enum BucketField implements FieldSelector { ID("id"), SELF_LINK("selfLink"), NAME("name"), @@ -90,27 +89,21 @@ enum BucketField { STORAGE_CLASS("storageClass"), ETAG("etag"); + static final List REQUIRED_FIELDS = ImmutableList.of(NAME); + private final String selector; BucketField(String selector) { this.selector = selector; } + @Override public String selector() { return selector; } - - static String selector(BucketField... fields) { - HashSet fieldStrings = Sets.newHashSetWithExpectedSize(fields.length + 1); - fieldStrings.add(NAME.selector()); - for (BucketField field : fields) { - fieldStrings.add(field.selector()); - } - return Joiner.on(',').join(fieldStrings); - } } - enum BlobField { + enum BlobField implements FieldSelector { ACL("acl"), BUCKET("bucket"), CACHE_CONTROL("cacheControl"), @@ -136,25 +129,18 @@ enum BlobField { TIME_DELETED("timeDeleted"), UPDATED("updated"); + static final List REQUIRED_FIELDS = ImmutableList.of(BUCKET, NAME); + private final String selector; BlobField(String selector) { this.selector = selector; } + @Override public String selector() { return selector; } - - static String selector(BlobField... fields) { - HashSet fieldStrings = Sets.newHashSetWithExpectedSize(fields.length + 2); - fieldStrings.add(BUCKET.selector()); - fieldStrings.add(NAME.selector()); - for (BlobField field : fields) { - fieldStrings.add(field.selector()); - } - return Joiner.on(',').join(fieldStrings); - } } /** @@ -269,7 +255,8 @@ public static BucketGetOption metagenerationNotMatch(long metageneration) { * specified. */ public static BucketGetOption fields(BucketField... fields) { - return new BucketGetOption(StorageRpc.Option.FIELDS, BucketField.selector(fields)); + return new BucketGetOption(StorageRpc.Option.FIELDS, + Helper.selector(BucketField.REQUIRED_FIELDS, fields)); } } @@ -609,7 +596,8 @@ public static BlobGetOption metagenerationNotMatch(long metageneration) { * specified. */ public static BlobGetOption fields(BlobField... fields) { - return new BlobGetOption(StorageRpc.Option.FIELDS, BlobField.selector(fields)); + return new BlobGetOption(StorageRpc.Option.FIELDS, + Helper.selector(BlobField.REQUIRED_FIELDS, fields)); } } @@ -653,9 +641,8 @@ public static BucketListOption prefix(String prefix) { * specified. */ public static BucketListOption fields(BucketField... fields) { - StringBuilder builder = new StringBuilder(); - builder.append("items(").append(BucketField.selector(fields)).append("),nextPageToken"); - return new BucketListOption(StorageRpc.Option.FIELDS, builder.toString()); + return new BucketListOption(StorageRpc.Option.FIELDS, + Helper.listSelector("items", BucketField.REQUIRED_FIELDS, fields)); } } @@ -722,9 +709,8 @@ public static BlobListOption versions(boolean versions) { * specified. */ public static BlobListOption fields(BlobField... fields) { - StringBuilder builder = new StringBuilder(); - builder.append("items(").append(BlobField.selector(fields)).append("),nextPageToken"); - return new BlobListOption(StorageRpc.Option.FIELDS, builder.toString()); + return new BlobListOption(StorageRpc.Option.FIELDS, + Helper.listSelector("items", BlobField.REQUIRED_FIELDS, fields)); } } @@ -1542,7 +1528,7 @@ public static Builder builder() { * are merged with metadata in the provided {@code BlobInfo} objects. To replace metadata instead * you first have to unset them. Unsetting metadata can be done by setting the provided * {@code BlobInfo} objects metadata to {@code null}. See - * {@link #update(com.google.gcloud.storage.BlobInfo)} for a code example. + * {@link #update(BlobInfo)} for a code example. * * @param blobInfos blobs to update * @return an immutable list of {@code Blob} objects. If a blob does not exist or access to it diff --git a/gcloud-java-storage/src/test/java/com/google/gcloud/storage/BlobInfoTest.java b/gcloud-java-storage/src/test/java/com/google/gcloud/storage/BlobInfoTest.java index 029181c6c07b..db9dddaa864e 100644 --- a/gcloud-java-storage/src/test/java/com/google/gcloud/storage/BlobInfoTest.java +++ b/gcloud-java-storage/src/test/java/com/google/gcloud/storage/BlobInfoTest.java @@ -51,7 +51,7 @@ public class BlobInfoTest { private static final Long DELETE_TIME = System.currentTimeMillis(); private static final String ETAG = "0xFF00"; private static final Long GENERATION = 1L; - private static final String ID = "B/N:1"; + private static final String GENERATED_ID = "B/N:1"; private static final String MD5 = "0xFF00"; private static final String MEDIA_LINK = "http://media/b/n"; private static final Map METADATA = ImmutableMap.of("n1", "v1", "n2", "v2"); @@ -71,7 +71,7 @@ public class BlobInfoTest { .crc32c(CRC32) .deleteTime(DELETE_TIME) .etag(ETAG) - .id(ID) + .generatedId(GENERATED_ID) .md5(MD5) .mediaLink(MEDIA_LINK) .metadata(METADATA) @@ -118,7 +118,7 @@ public void testBuilder() { assertEquals(DELETE_TIME, BLOB_INFO.deleteTime()); assertEquals(ETAG, BLOB_INFO.etag()); assertEquals(GENERATION, BLOB_INFO.generation()); - assertEquals(ID, BLOB_INFO.id()); + assertEquals(GENERATED_ID, BLOB_INFO.generatedId()); assertEquals(MD5, BLOB_INFO.md5()); assertEquals(MEDIA_LINK, BLOB_INFO.mediaLink()); assertEquals(METADATA, BLOB_INFO.metadata()); @@ -141,7 +141,7 @@ public void testBuilder() { assertNull(DIRECTORY_INFO.deleteTime()); assertNull(DIRECTORY_INFO.etag()); assertNull(DIRECTORY_INFO.generation()); - assertNull(DIRECTORY_INFO.id()); + assertNull(DIRECTORY_INFO.generatedId()); assertNull(DIRECTORY_INFO.md5()); assertNull(DIRECTORY_INFO.mediaLink()); assertNull(DIRECTORY_INFO.metadata()); @@ -168,7 +168,7 @@ private void compareBlobs(BlobInfo expected, BlobInfo value) { assertEquals(expected.deleteTime(), value.deleteTime()); assertEquals(expected.etag(), value.etag()); assertEquals(expected.generation(), value.generation()); - assertEquals(expected.id(), value.id()); + assertEquals(expected.generatedId(), value.generatedId()); assertEquals(expected.md5(), value.md5()); assertEquals(expected.mediaLink(), value.mediaLink()); assertEquals(expected.metadata(), value.metadata()); @@ -203,7 +203,7 @@ public void testToPbAndFromPb() { assertNull(blobInfo.deleteTime()); assertNull(blobInfo.etag()); assertNull(blobInfo.generation()); - assertNull(blobInfo.id()); + assertNull(blobInfo.generatedId()); assertNull(blobInfo.md5()); assertNull(blobInfo.mediaLink()); assertNull(blobInfo.metadata()); diff --git a/gcloud-java-storage/src/test/java/com/google/gcloud/storage/BlobTest.java b/gcloud-java-storage/src/test/java/com/google/gcloud/storage/BlobTest.java index d6c97ca9ca03..c8c5fb5d763c 100644 --- a/gcloud-java-storage/src/test/java/com/google/gcloud/storage/BlobTest.java +++ b/gcloud-java-storage/src/test/java/com/google/gcloud/storage/BlobTest.java @@ -64,7 +64,7 @@ public class BlobTest { private static final Long DELETE_TIME = System.currentTimeMillis(); private static final String ETAG = "0xFF00"; private static final Long GENERATION = 1L; - private static final String ID = "B/N:1"; + private static final String GENERATED_ID = "B/N:1"; private static final String MD5 = "0xFF00"; private static final String MEDIA_LINK = "http://media/b/n"; private static final Map METADATA = ImmutableMap.of("n1", "v1", "n2", "v2"); @@ -84,7 +84,7 @@ public class BlobTest { .crc32c(CRC32) .deleteTime(DELETE_TIME) .etag(ETAG) - .id(ID) + .generatedId(GENERATED_ID) .md5(MD5) .mediaLink(MEDIA_LINK) .metadata(METADATA) @@ -338,7 +338,7 @@ public void testBuilder() { .crc32c(CRC32) .deleteTime(DELETE_TIME) .etag(ETAG) - .id(ID) + .generatedId(GENERATED_ID) .md5(MD5) .mediaLink(MEDIA_LINK) .metadata(METADATA) @@ -360,7 +360,7 @@ public void testBuilder() { assertEquals(CRC32, blob.crc32c()); assertEquals(DELETE_TIME, blob.deleteTime()); assertEquals(ETAG, blob.etag()); - assertEquals(ID, blob.id()); + assertEquals(GENERATED_ID, blob.generatedId()); assertEquals(MD5, blob.md5()); assertEquals(MEDIA_LINK, blob.mediaLink()); assertEquals(METADATA, blob.metadata()); @@ -387,7 +387,7 @@ public void testBuilder() { assertNull(blob.crc32c()); assertNull(blob.deleteTime()); assertNull(blob.etag()); - assertNull(blob.id()); + assertNull(blob.generatedId()); assertNull(blob.md5()); assertNull(blob.mediaLink()); assertNull(blob.metadata()); diff --git a/gcloud-java-storage/src/test/java/com/google/gcloud/storage/BucketInfoTest.java b/gcloud-java-storage/src/test/java/com/google/gcloud/storage/BucketInfoTest.java index bd6bcdbbcff2..6f9fadfdf7cd 100644 --- a/gcloud-java-storage/src/test/java/com/google/gcloud/storage/BucketInfoTest.java +++ b/gcloud-java-storage/src/test/java/com/google/gcloud/storage/BucketInfoTest.java @@ -44,7 +44,7 @@ public class BucketInfoTest { Acl.of(User.ofAllAuthenticatedUsers(), Role.READER), Acl.of(new Project(VIEWERS, "p1"), Role.WRITER)); private static final String ETAG = "0xFF00"; - private static final String ID = "B/N:1"; + private static final String GENERATED_ID = "B/N:1"; private static final Long META_GENERATION = 10L; private static final User OWNER = new User("user@gmail.com"); private static final String SELF_LINK = "http://storage/b/n"; @@ -62,7 +62,7 @@ public class BucketInfoTest { private static final BucketInfo BUCKET_INFO = BucketInfo.builder("b") .acl(ACL) .etag(ETAG) - .id(ID) + .generatedId(GENERATED_ID) .metageneration(META_GENERATION) .owner(OWNER) .selfLink(SELF_LINK) @@ -80,10 +80,10 @@ public class BucketInfoTest { @Test public void testToBuilder() { compareBuckets(BUCKET_INFO, BUCKET_INFO.toBuilder().build()); - BucketInfo bucketInfo = BUCKET_INFO.toBuilder().name("B").id("id").build(); + BucketInfo bucketInfo = BUCKET_INFO.toBuilder().name("B").generatedId("id").build(); assertEquals("B", bucketInfo.name()); - assertEquals("id", bucketInfo.id()); - bucketInfo = bucketInfo.toBuilder().name("b").id(ID).build(); + assertEquals("id", bucketInfo.generatedId()); + bucketInfo = bucketInfo.toBuilder().name("b").generatedId(GENERATED_ID).build(); compareBuckets(BUCKET_INFO, bucketInfo); } @@ -104,7 +104,7 @@ public void testBuilder() { assertEquals("b", BUCKET_INFO.name()); assertEquals(ACL, BUCKET_INFO.acl()); assertEquals(ETAG, BUCKET_INFO.etag()); - assertEquals(ID, BUCKET_INFO.id()); + assertEquals(GENERATED_ID, BUCKET_INFO.generatedId()); assertEquals(META_GENERATION, BUCKET_INFO.metageneration()); assertEquals(OWNER, BUCKET_INFO.owner()); assertEquals(SELF_LINK, BUCKET_INFO.selfLink()); @@ -131,7 +131,7 @@ private void compareBuckets(BucketInfo expected, BucketInfo value) { assertEquals(expected.name(), value.name()); assertEquals(expected.acl(), value.acl()); assertEquals(expected.etag(), value.etag()); - assertEquals(expected.id(), value.id()); + assertEquals(expected.generatedId(), value.generatedId()); assertEquals(expected.metageneration(), value.metageneration()); assertEquals(expected.owner(), value.owner()); assertEquals(expected.selfLink(), value.selfLink()); diff --git a/gcloud-java-storage/src/test/java/com/google/gcloud/storage/BucketTest.java b/gcloud-java-storage/src/test/java/com/google/gcloud/storage/BucketTest.java index 53056c39c0dc..30b7416531f3 100644 --- a/gcloud-java-storage/src/test/java/com/google/gcloud/storage/BucketTest.java +++ b/gcloud-java-storage/src/test/java/com/google/gcloud/storage/BucketTest.java @@ -59,7 +59,7 @@ public class BucketTest { private static final List ACL = ImmutableList.of( Acl.of(User.ofAllAuthenticatedUsers(), READER), Acl.of(new Project(VIEWERS, "p1"), WRITER)); private static final String ETAG = "0xFF00"; - private static final String ID = "B/N:1"; + private static final String GENERATED_ID = "B/N:1"; private static final Long META_GENERATION = 10L; private static final User OWNER = new User("user@gmail.com"); private static final String SELF_LINK = "http://storage/b/n"; @@ -77,7 +77,7 @@ public class BucketTest { private static final BucketInfo FULL_BUCKET_INFO = BucketInfo.builder("b") .acl(ACL) .etag(ETAG) - .id(ID) + .generatedId(GENERATED_ID) .metageneration(META_GENERATION) .owner(OWNER) .selfLink(SELF_LINK) @@ -495,7 +495,7 @@ public void testBuilder() { new Bucket.Builder(new Bucket(storage, new BucketInfo.BuilderImpl(BUCKET_INFO))); Bucket bucket = builder.acl(ACL) .etag(ETAG) - .id(ID) + .generatedId(GENERATED_ID) .metageneration(META_GENERATION) .owner(OWNER) .selfLink(SELF_LINK) @@ -512,7 +512,7 @@ public void testBuilder() { assertEquals("b", bucket.name()); assertEquals(ACL, bucket.acl()); assertEquals(ETAG, bucket.etag()); - assertEquals(ID, bucket.id()); + assertEquals(GENERATED_ID, bucket.generatedId()); assertEquals(META_GENERATION, bucket.metageneration()); assertEquals(OWNER, bucket.owner()); assertEquals(SELF_LINK, bucket.selfLink()); diff --git a/gcloud-java-storage/src/test/java/com/google/gcloud/storage/OptionTest.java b/gcloud-java-storage/src/test/java/com/google/gcloud/storage/OptionTest.java index 5924174ab138..08a8e79b2c3b 100644 --- a/gcloud-java-storage/src/test/java/com/google/gcloud/storage/OptionTest.java +++ b/gcloud-java-storage/src/test/java/com/google/gcloud/storage/OptionTest.java @@ -17,22 +17,49 @@ package com.google.gcloud.storage; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; import com.google.gcloud.storage.spi.StorageRpc; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; public class OptionTest { + private static final StorageRpc.Option RPC_OPTION = StorageRpc.Option.DELIMITER; + private static final StorageRpc.Option ANOTHER_RPC_OPTION = StorageRpc.Option.FIELDS; + private static final String VALUE = "some value"; + private static final String OTHER_VALUE = "another value"; + private static final Option OPTION = new Option(RPC_OPTION, VALUE) {}; + private static final Option OPTION_EQUALS = new Option(RPC_OPTION, VALUE) {}; + private static final Option OPTION_NOT_EQUALS1 = new Option(RPC_OPTION, OTHER_VALUE) {}; + private static final Option OPTION_NOT_EQUALS2 = new Option(ANOTHER_RPC_OPTION, VALUE) {}; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void testEquals() { + assertEquals(OPTION, OPTION_EQUALS); + assertNotEquals(OPTION, OPTION_NOT_EQUALS1); + assertNotEquals(OPTION, OPTION_NOT_EQUALS2); + } + @Test - public void testOption() { - Option option = new Option(StorageRpc.Option.DELIMITER, "/"); - assertEquals(StorageRpc.Option.DELIMITER, option.rpcOption()); - assertEquals("/", option.value()); + public void testHashCode() { + assertEquals(OPTION.hashCode(), OPTION_EQUALS.hashCode()); } - @Test(expected = NullPointerException.class) - public void testIndexOutOfBoundsException() { - new Option(null, "/"); + @Test + public void testConstructor() { + assertEquals(RPC_OPTION, OPTION.rpcOption()); + assertEquals(VALUE, OPTION.value()); + Option option = new Option(RPC_OPTION, null) {}; + assertEquals(RPC_OPTION, option.rpcOption()); + assertNull(option.value()); + thrown.expect(NullPointerException.class); + new Option(null, VALUE) {}; } } diff --git a/gcloud-java-storage/src/test/java/com/google/gcloud/storage/it/ITStorageTest.java b/gcloud-java-storage/src/test/java/com/google/gcloud/storage/it/ITStorageTest.java index 13d768442c34..542cf966d269 100644 --- a/gcloud-java-storage/src/test/java/com/google/gcloud/storage/it/ITStorageTest.java +++ b/gcloud-java-storage/src/test/java/com/google/gcloud/storage/it/ITStorageTest.java @@ -122,7 +122,7 @@ public void testGetBucketSelectedFields() { Bucket remoteBucket = storage.get(BUCKET, Storage.BucketGetOption.fields(BucketField.ID)); assertEquals(BUCKET, remoteBucket.name()); assertNull(remoteBucket.createTime()); - assertNotNull(remoteBucket.id()); + assertNotNull(remoteBucket.generatedId()); } @Test @@ -256,7 +256,7 @@ public void testGetBlobAllSelectedFields() { assertEquals(blob.bucket(), remoteBlob.bucket()); assertEquals(blob.name(), remoteBlob.name()); assertEquals(ImmutableMap.of("k", "v"), remoteBlob.metadata()); - assertNotNull(remoteBlob.id()); + assertNotNull(remoteBlob.generatedId()); assertNotNull(remoteBlob.selfLink()); assertTrue(remoteBlob.delete()); } diff --git a/gcloud-java/README.md b/gcloud-java/README.md index e296d0c0c565..36e82fb23a74 100644 --- a/gcloud-java/README.md +++ b/gcloud-java/README.md @@ -27,16 +27,16 @@ If you are using Maven, add this to your pom.xml file com.google.gcloud gcloud-java - 0.1.5 + 0.1.7 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.gcloud:gcloud-java:0.1.5' +compile 'com.google.gcloud:gcloud-java:0.1.7' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.gcloud" % "gcloud-java" % "0.1.5" +libraryDependencies += "com.google.gcloud" % "gcloud-java" % "0.1.7" ``` Troubleshooting diff --git a/gcloud-java/pom.xml b/gcloud-java/pom.xml index 654b34f92056..9b765db419d7 100644 --- a/gcloud-java/pom.xml +++ b/gcloud-java/pom.xml @@ -10,7 +10,7 @@ com.google.gcloud gcloud-java-pom - 0.1.6-SNAPSHOT + 0.1.8-SNAPSHOT diff --git a/pom.xml b/pom.xml index d73956f506ee..42f9bd73cdfb 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.google.gcloud gcloud-java-pom pom - 0.1.6-SNAPSHOT + 0.1.8-SNAPSHOT GCloud Java https://github.com/GoogleCloudPlatform/gcloud-java @@ -404,7 +404,7 @@ Test helpers packages - com.google.gcloud.bigquery.testing:com.google.gcloud.datastore.testing:com.google.gcloud.resourcemanager.testing:com.google.gcloud.storage.testing + com.google.gcloud.bigquery.testing:com.google.gcloud.datastore.testing:com.google.gcloud.dns.testing:com.google.gcloud.resourcemanager.testing:com.google.gcloud.storage.testing Example packages @@ -412,7 +412,7 @@ SPI packages - com.google.gcloud.spi:com.google.gcloud.bigquery.spi:com.google.gcloud.datastore.spi:com.google.gcloud.resourcemanager.spi:com.google.gcloud.storage.spi + com.google.gcloud.spi:com.google.gcloud.bigquery.spi:com.google.gcloud.datastore.spi:com.google.gcloud.dns.spi:com.google.gcloud.resourcemanager.spi:com.google.gcloud.storage.spi diff --git a/src/site/resources/img/icon-lang-ruby.svg b/src/site/resources/img/icon-lang-ruby.svg index acfaab8d6ea5..5f4e5a25d893 100644 --- a/src/site/resources/img/icon-lang-ruby.svg +++ b/src/site/resources/img/icon-lang-ruby.svg @@ -1,23 +1,15 @@ - - - - - - - - - - - - - - - - - - - - + + + + + +