From c091e365ed247db91478ebeabf40bc1f3e0f03eb Mon Sep 17 00:00:00 2001 From: Alex O'Ree Date: Sat, 24 Sep 2022 22:14:55 -0400 Subject: [PATCH] JUDDI-1024 a possible solution, by removing hibernate support --- docs/.gitignore | 6 - docs/asciidoc/.gitignore | 6 - docs/asciidoc/ClientGuide/.gitignore | 6 - docs/asciidoc/Guide/.gitignore | 6 - docs/dist/.gitignore | 6 - docs/examples/auth/pom.xml | 2 +- juddi-client-cli/.gitignore | 6 - juddi-client.net/.gitignore | 6 - juddi-client/.gitignore | 6 - juddi-core-openjpa/.gitignore | 6 - juddi-core-openjpa/pom.xml | 38 +- juddi-core-openjpa/src/.gitignore | 1 - .../main/java/org/apache/juddi/ClassUtil.java | 0 .../main/java/org/apache/juddi/Registry.java | 0 .../juddi/api/impl/AuthenticatedService.java | 506 +- .../apache/juddi/api/impl/InquiryHelper.java | 1300 ++--- .../apache/juddi/api/impl/JUDDIApiImpl.java | 3366 +++++------ .../juddi/api/impl/PublicationHelper.java | 124 +- .../impl/ServiceCounterLifecycleResource.java | 0 .../api/impl/UDDICustodyTransferImpl.java | 942 +-- .../juddi/api/impl/UDDIInquiryImpl.java | 1260 ++-- .../juddi/api/impl/UDDIPublicationImpl.java | 3206 +++++------ .../juddi/api/impl/UDDIReplicationImpl.java | 2752 ++++----- .../juddi/api/impl/UDDISecurityImpl.java | 350 +- .../juddi/api/impl/UDDIServiceCounter.java | 0 .../api/impl/UDDIServiceCounterMBean.java | 0 .../juddi/api/impl/UDDISubscriptionImpl.java | 2092 +++---- .../impl/UDDISubscriptionListenerImpl.java | 230 +- .../api/impl/UDDIValueSetCachingImpl.java | 194 +- .../api/impl/UDDIValueSetValidationImpl.java | 736 +-- .../juddi/api/impl/UDDIv2InquiryImpl.java | 0 .../juddi/api/impl/UDDIv2PublishImpl.java | 0 .../juddi/api/impl/XRegisterHelper.java | 354 +- .../apache/juddi/api/impl/package-info.java | 0 .../juddi/api/util/CustodyTransferQuery.java | 0 .../apache/juddi/api/util/InquiryQuery.java | 0 .../org/apache/juddi/api/util/JUDDIQuery.java | 0 .../juddi/api/util/PublicationQuery.java | 0 .../apache/juddi/api/util/QueryStatus.java | 0 .../juddi/api/util/ReplicationQuery.java | 0 .../apache/juddi/api/util/SecurityQuery.java | 0 .../api/util/SubscriptionListenerQuery.java | 0 .../juddi/api/util/SubscriptionQuery.java | 0 .../org/apache/juddi/api/util/UDDIQuery.java | 0 .../juddi/api/util/ValueSetCachingQuery.java | 0 .../api/util/ValueSetValidationQuery.java | 0 .../apache/juddi/api/util/package-info.java | 0 .../org/apache/juddi/config/AppConfig.java | 0 .../org/apache/juddi/config/Constants.java | 60 +- .../java/org/apache/juddi/config/Install.java | 1676 +++--- .../juddi/config/PersistenceManager.java | 0 .../org/apache/juddi/config/Property.java | 0 .../juddi/config/PublisherFileFilter.java | 0 .../java/org/apache/juddi/config/Release.java | 0 .../apache/juddi/config/ResourceConfig.java | 104 +- .../org/apache/juddi/config/package-info.java | 0 .../apache/juddi/cryptor/CryptorFactory.java | 212 +- .../apache/juddi/cryptor/package-info.java | 0 .../juddi/keygen/DefaultKeyGenerator.java | 164 +- .../org/apache/juddi/keygen/KeyGenerator.java | 68 +- .../juddi/keygen/KeyGeneratorFactory.java | 212 +- .../org/apache/juddi/keygen/package-info.java | 0 .../juddi/mapping/MappingApiToModel.java | 3384 +++++------ .../juddi/mapping/MappingModelToApi.java | 2728 ++++----- .../apache/juddi/mapping/package-info.java | 0 .../java/org/apache/juddi/model/Address.java | 1 + .../org/apache/juddi/model/AddressLine.java | 0 .../org/apache/juddi/model/AuthToken.java | 0 .../juddi/model/BindingCategoryBag.java | 0 .../org/apache/juddi/model/BindingDescr.java | 0 .../apache/juddi/model/BindingTemplate.java | 0 .../juddi/model/BusinessCategoryBag.java | 0 .../org/apache/juddi/model/BusinessDescr.java | 0 .../apache/juddi/model/BusinessEntity.java | 0 .../juddi/model/BusinessIdentifier.java | 0 .../org/apache/juddi/model/BusinessName.java | 0 .../apache/juddi/model/BusinessService.java | 0 .../juddi/model/CanonicalizationMethod.java | 0 .../org/apache/juddi/model/CategoryBag.java | 0 .../org/apache/juddi/model/ChangeRecord.java | 0 .../java/org/apache/juddi/model/Clerk.java | 0 .../juddi/model/ClientSubscriptionInfo.java | 0 .../java/org/apache/juddi/model/Contact.java | 0 .../org/apache/juddi/model/ContactDescr.java | 0 .../apache/juddi/model/ControlMessage.java | 0 .../org/apache/juddi/model/DiscoveryUrl.java | 0 .../java/org/apache/juddi/model/Edge.java | 0 .../juddi/model/EdgeReceiverAlternate.java | 0 .../java/org/apache/juddi/model/Email.java | 0 .../juddi/model/InstanceDetailsDescr.java | 0 .../juddi/model/InstanceDetailsDocDescr.java | 0 .../org/apache/juddi/model/KeyDataValue.java | 0 .../java/org/apache/juddi/model/KeyInfo.java | 0 .../apache/juddi/model/KeyedReference.java | 0 .../juddi/model/KeyedReferenceGroup.java | 0 .../java/org/apache/juddi/model/Node.java | 0 .../org/apache/juddi/model/ObjectType.java | 0 .../apache/juddi/model/ObjectTypeContent.java | 0 .../java/org/apache/juddi/model/Operator.java | 0 .../juddi/model/OperatorStatusType.java | 0 .../org/apache/juddi/model/OverviewDoc.java | 0 .../apache/juddi/model/OverviewDocDescr.java | 0 .../org/apache/juddi/model/PersonName.java | 0 .../java/org/apache/juddi/model/Phone.java | 0 .../org/apache/juddi/model/Publisher.java | 0 .../juddi/model/PublisherAssertion.java | 0 .../juddi/model/PublisherAssertionId.java | 0 .../org/apache/juddi/model/Reference.java | 0 .../juddi/model/ReplicationConfiguration.java | 0 .../model/ReplicationConfigurationNode.java | 0 .../juddi/model/ServiceCategoryBag.java | 0 .../org/apache/juddi/model/ServiceDescr.java | 0 .../org/apache/juddi/model/ServiceName.java | 0 .../apache/juddi/model/ServiceProjection.java | 154 +- .../juddi/model/ServiceProjectionId.java | 146 +- .../org/apache/juddi/model/Signature.java | 0 .../apache/juddi/model/SignatureMethod.java | 0 .../juddi/model/SignatureTransform.java | 0 .../model/SignatureTransformDataValue.java | 0 .../apache/juddi/model/SignatureValue.java | 0 .../org/apache/juddi/model/SignedInfo.java | 0 .../org/apache/juddi/model/Subscription.java | 0 .../juddi/model/SubscriptionChunkToken.java | 208 +- .../apache/juddi/model/SubscriptionMatch.java | 154 +- .../java/org/apache/juddi/model/TempKey.java | 6 +- .../org/apache/juddi/model/TempKeyPK.java | 158 +- .../java/org/apache/juddi/model/Tmodel.java | 0 .../apache/juddi/model/TmodelCategoryBag.java | 0 .../org/apache/juddi/model/TmodelDescr.java | 0 .../apache/juddi/model/TmodelIdentifier.java | 0 .../juddi/model/TmodelInstanceInfo.java | 0 .../juddi/model/TmodelInstanceInfoDescr.java | 0 .../org/apache/juddi/model/TransferToken.java | 4 +- .../apache/juddi/model/TransferTokenKey.java | 0 .../org/apache/juddi/model/UddiEntity.java | 258 +- .../juddi/model/UddiEntityPublisher.java | 442 +- .../apache/juddi/model/ValueSetValues.java | 0 .../org/apache/juddi/model/package-info.java | 0 .../juddi/query/BindingTemplateQuery.java | 92 +- .../juddi/query/BusinessEntityQuery.java | 86 +- .../juddi/query/BusinessServiceQuery.java | 90 +- ...letePublisherAssertionByBusinessQuery.java | 138 +- .../org/apache/juddi/query/EntityQuery.java | 372 +- .../query/FetchBindingTemplatesQuery.java | 250 +- .../query/FetchBusinessEntitiesQuery.java | 300 +- .../query/FetchBusinessServicesQuery.java | 296 +- .../apache/juddi/query/FetchTModelsQuery.java | 292 +- .../FindBindingByCategoryGroupQuery.java | 138 +- .../query/FindBindingByCategoryQuery.java | 126 +- .../query/FindBindingByTModelKeyQuery.java | 320 +- .../FindBusinessByCategoryGroupQuery.java | 126 +- .../query/FindBusinessByCategoryQuery.java | 114 +- .../FindBusinessByCombinedCategoryQuery.java | 0 .../FindBusinessByDiscoveryURLQuery.java | 240 +- .../query/FindBusinessByIdentifierQuery.java | 114 +- .../juddi/query/FindBusinessByNameQuery.java | 130 +- .../query/FindBusinessByPublisherQuery.java | 102 +- .../query/FindBusinessByTModelKeyQuery.java | 328 +- .../query/FindEntityByCategoryGroupQuery.java | 650 +-- .../query/FindEntityByCategoryQuery.java | 616 +- .../FindEntityByCombinedCategoryQuery.java | 0 .../query/FindEntityByIdentifierQuery.java | 576 +- .../juddi/query/FindEntityByNamesQuery.java | 356 +- .../query/FindEntityByPublisherQuery.java | 216 +- ...FindPublisherAssertionByBusinessQuery.java | 204 +- .../FindServiceByCategoryGroupQuery.java | 136 +- .../query/FindServiceByCategoryQuery.java | 126 +- .../FindServiceByCombinedCategoryQuery.java | 0 .../juddi/query/FindServiceByNameQuery.java | 142 +- .../query/FindServiceByTModelKeyQuery.java | 334 +- .../FindSubscriptionByPublisherQuery.java | 80 +- .../query/FindTModelByCategoryGroupQuery.java | 130 +- .../query/FindTModelByCategoryQuery.java | 118 +- .../query/FindTModelByIdentifierQuery.java | 116 +- .../juddi/query/FindTModelByNameQuery.java | 210 +- .../query/FindTModelByPublisherQuery.java | 102 +- .../juddi/query/PublisherAssertionQuery.java | 98 +- .../apache/juddi/query/SubscriptionQuery.java | 80 +- .../org/apache/juddi/query/TModelQuery.java | 84 +- .../org/apache/juddi/query/package-info.java | 0 .../apache/juddi/query/util/DynamicQuery.java | 506 +- .../juddi/query/util/FindQualifiers.java | 740 +-- .../util/KeyedRefGroupTModelComparator.java | 96 +- .../query/util/KeyedRefTModelComparator.java | 96 +- .../replication/ReplicationNotifier.java | 0 .../juddi/subscription/NotificationList.java | 0 .../subscription/SubscriptionNotifier.java | 0 .../juddi/subscription/TypeConvertor.java | 0 .../subscription/notify/HTTPNotifier.java | 0 .../juddi/subscription/notify/Notifier.java | 0 .../subscription/notify/NotifierFactory.java | 0 .../subscription/notify/SMTPNotifier.java | 0 .../notify/TemporaryMailContainer.java | 0 .../notify/USERFRIENDLYSMTPNotifier.java | 0 .../subscription/notify/package-info.java | 0 .../juddi/subscription/package-info.java | 0 .../apache/juddi/v3/auth/Authenticator.java | 122 +- .../juddi/v3/auth/AuthenticatorFactory.java | 198 +- .../v3/auth/CryptedXMLDocAuthenticator.java | 402 +- .../v3/auth/HTTPContainerAuthenticator.java | 0 .../v3/auth/HTTPHeaderAuthenticator.java | 0 .../juddi/v3/auth/JUDDIAuthenticator.java | 254 +- .../org/apache/juddi/v3/auth/JuddiUsers.java | 0 .../v3/auth/LdapExpandedAuthenticator.java | 0 .../v3/auth/LdapSimpleAuthenticator.java | 0 .../juddi/v3/auth/MD5XMLDocAuthenticator.java | 348 +- .../java/org/apache/juddi/v3/auth/User.java | 0 .../juddi/v3/auth/XMLDocAuthenticator.java | 464 +- .../apache/juddi/v3/auth/package-info.java | 0 .../v3/error/AssertionNotFoundException.java | 72 +- .../v3/error/AuthTokenExpiredException.java | 72 +- .../v3/error/AuthTokenRequiredException.java | 72 +- .../v3/error/AuthenticationException.java | 72 +- .../apache/juddi/v3/error/ErrorMessage.java | 122 +- .../juddi/v3/error/FatalErrorException.java | 72 +- .../v3/error/InvalidCombinationException.java | 74 +- .../v3/error/InvalidKeyPassedException.java | 74 +- .../v3/error/InvalidProjectionException.java | 74 +- .../juddi/v3/error/InvalidTimeException.java | 74 +- .../juddi/v3/error/InvalidValueException.java | 80 +- .../v3/error/KeyUnavailableException.java | 72 +- .../error/MaxEntitiesExceededException.java | 74 +- .../juddi/v3/error/RegistryException.java | 72 +- .../v3/error/TokenAlreadyExistsException.java | 74 +- .../v3/error/TransferNotAllowedException.java | 74 +- .../juddi/v3/error/UDDIErrorHelper.java | 422 +- .../juddi/v3/error/UnknownUserException.java | 72 +- .../juddi/v3/error/UnsupportedException.java | 72 +- .../juddi/v3/error/UserMismatchException.java | 64 +- .../v3/error/ValueNotAllowedException.java | 74 +- .../apache/juddi/v3/error/package-info.java | 0 .../juddi/validation/ValidateClerk.java | 198 +- .../ValidateClientSubscriptionInfo.java | 280 +- .../validation/ValidateCustodyTransfer.java | 0 .../juddi/validation/ValidateInquiry.java | 1604 +++--- .../apache/juddi/validation/ValidateNode.java | 246 +- .../juddi/validation/ValidatePublish.java | 5102 ++++++++--------- .../juddi/validation/ValidatePublisher.java | 288 +- .../juddi/validation/ValidateReplication.java | 0 .../juddi/validation/ValidateSecurity.java | 0 .../validation/ValidateSubscription.java | 0 .../ValidateSubscriptionListener.java | 80 +- .../juddi/validation/ValidateUDDIApi.java | 172 +- .../juddi/validation/ValidateUDDIKey.java | 320 +- .../validation/ValidateUDDIv2Inquiry.java | 0 .../validation/ValidateValueSetCaching.java | 0 .../ValidateValueSetValidation.java | 0 .../ValidateValuesFromWebService.java | 0 .../juddi/validation/ValidationConstants.java | 0 .../apache/juddi/validation/package-info.java | 0 .../vsv/AbstractSimpleValidator.java | 0 .../Uddiuddiorgcategorizationderivedfrom.java | 0 ...iuddiorgcategorizationentitykeyvalues.java | 0 .../vsv/Uddiuddiorgcategorizationnodes.java | 0 ...diuddiorgcategorizationowningbusiness.java | 0 .../vsv/Uddiuddiorgcategorizationtypes.java | 0 .../Uddiuddiorgcategorizationvalidatedby.java | 0 .../Uddiuddiorgidentifierisreplacedby.java | 0 .../vsv/Uddiuddiorgrelationships.java | 0 .../Uuid25b22e3e3dfa3024b02a3438b9050b59.java | 0 .../Uuid327a56f032994461bc235cd513e95c55.java | 0 .../Uuid4064c0646d144f3589539652106476a9.java | 0 .../Uuid5678dd4ff95d35f99ea6f79a7dd64656.java | 0 .../Uuid807a2c6aee22470dadc7e0424a337c03.java | 0 .../Uuid916b87bf075639198eae97dfa325e5a4.java | 0 .../Uuidc1acf26d967244049d7039b756e62ab4.java | 0 .../Uuide59ae32077a511d5b8980004ac49cc1e.java | 0 .../validation/vsv/ValueSetValidator.java | 0 .../juddi_install_data/UDDI_Publisher.xml | 44 +- .../juddi_install_data/UDDI_tModels.xml | 4850 ++++++++-------- .../root_BusinessEntity.xml | 1336 ++--- .../juddi_install_data/root_Publisher.xml | 42 +- .../root_replicationConfiguration.xml | 0 .../juddi_install_data/root_tModelKeyGen.xml | 80 +- .../src/main/resources/messages.properties | 622 +- juddi-core-openjpa/src/test/.gitignore | 1 - .../juddi/api/impl/API_010_PublisherTest.java | 690 +-- .../juddi/api/impl/API_020_TmodelTest.java | 250 +- .../api/impl/API_030_BusinessEntityTest.java | 320 +- .../impl/API_040_BusinessServiceLoadTest.java | 344 +- .../api/impl/API_040_BusinessServiceTest.java | 362 +- .../api/impl/API_050_BindingTemplateTest.java | 618 +- .../impl/API_051_BindingTemplateWSDLTest.java | 288 +- .../impl/API_060_PublisherAssertionTest.java | 1014 ++-- .../api/impl/API_070_FindEntityTest.java | 628 +- .../api/impl/API_080_SubscriptionTest.java | 322 +- ...0_SubscriptionListenerIntegrationTest.java | 0 .../juddi/api/impl/API_099_LoadTest.java | 0 .../API_100_ClientSubscriptionInfoTest.java | 406 +- .../api/impl/API_110_FindBusinessTest.java | 0 ...20_CombineCategoryBagsFindServiceTest.java | 0 ...0_CombineCategoryBagsFindBusinessTest.java | 0 .../impl/API_140_NegativePublicationTest.java | 4888 ++++++++-------- .../juddi/api/impl/API_141_JIRATest.java | 2838 ++++----- .../impl/API_150_ValueSetValidationTest.java | 0 .../api/impl/API_160_ReplicationTest.java | 0 .../api/impl/API_170_CustodyTransferTest.java | 0 .../org/apache/juddi/api/impl/TokenTest.java | 0 .../api/impl/UDDIPublicationImplExt.java | 0 .../juddi/api/impl/UDDISecurityImplExt.java | 0 .../org/apache/juddi/api/impl/package.html | 0 .../juddi/api/runtime/CLIServerTest.java | 0 .../juddi/api/runtime/JuddiTestimpl.java | 0 .../juddi/api/runtime/ReplicantImpl.java | 0 .../apache/juddi/auth/AuthenticatorTest.java | 0 .../juddi/auth/MockHttpServletRequest.java | 0 .../apache/juddi/auth/MockMessageContext.java | 0 .../juddi/auth/MockWebServiceContext.java | 0 .../config/ApplicationConfigurationTest.java | 0 .../org/apache/juddi/config/InstallTest.java | 0 .../juddi/config/ReleaseVersionTest.java | 0 .../apache/juddi/keygen/KeyGeneratorTest.java | 0 .../replication/ReplicationNotifierTest.java | 0 .../SubscriptionNotifierTest.java | 0 .../subscription/notify/NotifierTest.java | 0 .../java/org/apache/juddi/util/JPAUtil.java | 314 +- .../src/test/resources/META-INF/uddi.xml | 160 +- .../src/test/resources/juddi-users-hashed.xml | 1 + .../src/test/resources/juddiv3-enc-3des.xml | 30 +- .../src/test/resources/juddiv3-enc-aes128.xml | 31 +- .../src/test/resources/juddiv3-enc-aes256.xml | 26 +- .../test/resources/juddiv3-enc-default.xml | 20 +- .../src/test/resources/juddiv3.xml | 25 +- .../resources/juddiv3DisabledTModelKeybag.xml | 18 +- juddi-core/.gitignore | 6 - juddi-core/pom.xml | 189 - .../src/test/resources/META-INF/orm.xml | 241 - .../test/resources/META-INF/persistence.xml | 118 - .../src/test/resources/META-INF/uddi.xml | 114 - .../test/resources/juddi-users-encrypted.xml | 22 - .../src/test/resources/juddi-users-hashed.xml | 23 - juddi-core/src/test/resources/juddi-users.xml | 22 - .../src/test/resources/juddiv3-enc-3des.xml | 222 - .../src/test/resources/juddiv3-enc-aes128.xml | 218 - .../src/test/resources/juddiv3-enc-aes256.xml | 225 - .../test/resources/juddiv3-enc-default.xml | 222 - juddi-core/src/test/resources/juddiv3.xml | 225 - .../resources/juddiv3DisabledTModelKeybag.xml | 230 - juddi-core/src/test/resources/keystore.jks | Bin 2253 -> 0 bytes juddi-core/src/test/resources/log4j.xml | 36 - juddi-core/src/test/resources/truststore.jks | Bin 965 -> 0 bytes .../src/test/resources/wsdl/sample.wsdl | 70 - juddi-ddl-generator/pom.xml | 4 +- juddi-dist/.gitignore | 6 - juddi-dist/pom.xml | 6 +- juddi-examples/.gitignore | 6 - juddi-examples/ValueSetValidator/pom.xml | 2 +- .../hello-world-embedded/.gitignore | 6 - juddi-examples/hello-world-embedded/pom.xml | 2 +- juddi-examples/hello-world/.gitignore | 6 - juddi-examples/juddi-embedded/pom.xml | 2 +- juddi-examples/more-uddi-samples/.gitignore | 6 - juddi-examples/service-version/.gitignore | 6 - juddi-examples/simple-browse/.gitignore | 6 - .../simple-publish-clerk/.gitignore | 6 - .../simple-publish-portable/.gitignore | 6 - .../subscription-notification-amqp/pom.xml | 2 +- juddi-examples/uddi-annotations/.gitignore | 6 - .../uddiv2-api-bridge-example/.gitignore | 6 - juddi-examples/wsdl2uddi-lifecyle/.gitignore | 6 - juddi-examples/wsdl2uddi/.gitignore | 6 - juddi-extras/.gitignore | 6 - juddi-gui/.gitignore | 6 - juddi-rest-cxf/.gitignore | 6 - juddi-rest-cxf/pom.xml | 3 +- juddi-tomcat/.gitignore | 6 - juddiv3-war-repl/.gitignore | 6 - juddiv3-war-repl/pom.xml | 376 +- juddiv3-war/.gitignore | 6 - juddiv3-war/pom.xml | 375 +- pom.xml | 21 +- uddi-client-dist/.gitignore | 6 - uddi-migration-tool/.gitignore | 6 - uddi-tck-base/.gitignore | 6 - uddi-tck-runner/.gitignore | 6 - uddi-tck/.gitignore | 6 - uddi-ws/.gitignore | 6 - 377 files changed, 34881 insertions(+), 37931 deletions(-) delete mode 100644 docs/.gitignore delete mode 100644 docs/asciidoc/.gitignore delete mode 100644 docs/asciidoc/ClientGuide/.gitignore delete mode 100644 docs/asciidoc/Guide/.gitignore delete mode 100644 docs/dist/.gitignore delete mode 100644 juddi-client-cli/.gitignore delete mode 100644 juddi-client.net/.gitignore delete mode 100644 juddi-client/.gitignore delete mode 100644 juddi-core-openjpa/.gitignore delete mode 100644 juddi-core-openjpa/src/.gitignore rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/ClassUtil.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/Registry.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/impl/AuthenticatedService.java (98%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/impl/InquiryHelper.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/impl/JUDDIApiImpl.java (98%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/impl/PublicationHelper.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/impl/ServiceCounterLifecycleResource.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/impl/UDDICustodyTransferImpl.java (98%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/impl/UDDIInquiryImpl.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/impl/UDDIPublicationImpl.java (98%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/impl/UDDIReplicationImpl.java (98%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/impl/UDDISecurityImpl.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/impl/UDDIServiceCounter.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/impl/UDDIServiceCounterMBean.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/impl/UDDISubscriptionImpl.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/impl/UDDISubscriptionListenerImpl.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/impl/UDDIValueSetCachingImpl.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/impl/UDDIValueSetValidationImpl.java (98%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/impl/UDDIv2InquiryImpl.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/impl/UDDIv2PublishImpl.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/impl/XRegisterHelper.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/impl/package-info.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/util/CustodyTransferQuery.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/util/InquiryQuery.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/util/JUDDIQuery.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/util/PublicationQuery.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/util/QueryStatus.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/util/ReplicationQuery.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/util/SecurityQuery.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/util/SubscriptionListenerQuery.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/util/SubscriptionQuery.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/util/UDDIQuery.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/util/ValueSetCachingQuery.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/util/ValueSetValidationQuery.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/api/util/package-info.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/config/AppConfig.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/config/Constants.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/config/Install.java (98%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/config/PersistenceManager.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/config/Property.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/config/PublisherFileFilter.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/config/Release.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/config/ResourceConfig.java (96%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/config/package-info.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/cryptor/CryptorFactory.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/cryptor/package-info.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/keygen/DefaultKeyGenerator.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/keygen/KeyGenerator.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/keygen/KeyGeneratorFactory.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/keygen/package-info.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/mapping/MappingApiToModel.java (98%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/mapping/MappingModelToApi.java (98%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/mapping/package-info.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/Address.java (99%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/AddressLine.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/AuthToken.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/BindingCategoryBag.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/BindingDescr.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/BindingTemplate.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/BusinessCategoryBag.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/BusinessDescr.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/BusinessEntity.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/BusinessIdentifier.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/BusinessName.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/BusinessService.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/CanonicalizationMethod.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/CategoryBag.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/ChangeRecord.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/Clerk.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/ClientSubscriptionInfo.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/Contact.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/ContactDescr.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/ControlMessage.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/DiscoveryUrl.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/Edge.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/EdgeReceiverAlternate.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/Email.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/InstanceDetailsDescr.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/InstanceDetailsDocDescr.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/KeyDataValue.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/KeyInfo.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/KeyedReference.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/KeyedReferenceGroup.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/Node.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/ObjectType.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/ObjectTypeContent.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/Operator.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/OperatorStatusType.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/OverviewDoc.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/OverviewDocDescr.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/PersonName.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/Phone.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/Publisher.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/PublisherAssertion.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/PublisherAssertionId.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/Reference.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/ReplicationConfiguration.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/ReplicationConfigurationNode.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/ServiceCategoryBag.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/ServiceDescr.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/ServiceName.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/ServiceProjection.java (96%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/ServiceProjectionId.java (96%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/Signature.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/SignatureMethod.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/SignatureTransform.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/SignatureTransformDataValue.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/SignatureValue.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/SignedInfo.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/Subscription.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/SubscriptionChunkToken.java (96%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/SubscriptionMatch.java (96%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/TempKey.java (99%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/TempKeyPK.java (96%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/Tmodel.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/TmodelCategoryBag.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/TmodelDescr.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/TmodelIdentifier.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/TmodelInstanceInfo.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/TmodelInstanceInfoDescr.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/TransferToken.java (99%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/TransferTokenKey.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/UddiEntity.java (96%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/UddiEntityPublisher.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/ValueSetValues.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/model/package-info.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/BindingTemplateQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/BusinessEntityQuery.java (96%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/BusinessServiceQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/DeletePublisherAssertionByBusinessQuery.java (96%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/EntityQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FetchBindingTemplatesQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FetchBusinessEntitiesQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FetchBusinessServicesQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FetchTModelsQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindBindingByCategoryGroupQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindBindingByCategoryQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindBindingByTModelKeyQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindBusinessByCategoryGroupQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindBusinessByCategoryQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindBusinessByCombinedCategoryQuery.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindBusinessByDiscoveryURLQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindBusinessByIdentifierQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindBusinessByNameQuery.java (98%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindBusinessByPublisherQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindBusinessByTModelKeyQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindEntityByCategoryGroupQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindEntityByCategoryQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindEntityByCombinedCategoryQuery.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindEntityByIdentifierQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindEntityByNamesQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindEntityByPublisherQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindPublisherAssertionByBusinessQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindServiceByCategoryGroupQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindServiceByCategoryQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindServiceByCombinedCategoryQuery.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindServiceByNameQuery.java (98%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindServiceByTModelKeyQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindSubscriptionByPublisherQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindTModelByCategoryGroupQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindTModelByCategoryQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindTModelByIdentifierQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindTModelByNameQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/FindTModelByPublisherQuery.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/PublisherAssertionQuery.java (96%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/SubscriptionQuery.java (96%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/TModelQuery.java (96%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/package-info.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/util/DynamicQuery.java (95%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/util/FindQualifiers.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/util/KeyedRefGroupTModelComparator.java (96%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/query/util/KeyedRefTModelComparator.java (96%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/replication/ReplicationNotifier.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/subscription/NotificationList.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/subscription/SubscriptionNotifier.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/subscription/TypeConvertor.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/subscription/notify/HTTPNotifier.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/subscription/notify/Notifier.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/subscription/notify/NotifierFactory.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/subscription/notify/SMTPNotifier.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/subscription/notify/TemporaryMailContainer.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/subscription/notify/USERFRIENDLYSMTPNotifier.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/subscription/notify/package-info.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/subscription/package-info.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/auth/Authenticator.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/auth/AuthenticatorFactory.java (96%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/auth/CryptedXMLDocAuthenticator.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/auth/HTTPContainerAuthenticator.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/auth/HTTPHeaderAuthenticator.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/auth/JUDDIAuthenticator.java (98%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/auth/JuddiUsers.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/auth/LdapExpandedAuthenticator.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/auth/LdapSimpleAuthenticator.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/auth/MD5XMLDocAuthenticator.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/auth/User.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/auth/XMLDocAuthenticator.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/auth/package-info.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/AssertionNotFoundException.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/AuthTokenExpiredException.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/AuthTokenRequiredException.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/AuthenticationException.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/ErrorMessage.java (95%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/FatalErrorException.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/InvalidCombinationException.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/InvalidKeyPassedException.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/InvalidProjectionException.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/InvalidTimeException.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/InvalidValueException.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/KeyUnavailableException.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/MaxEntitiesExceededException.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/RegistryException.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/TokenAlreadyExistsException.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/TransferNotAllowedException.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/UDDIErrorHelper.java (98%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/UnknownUserException.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/UnsupportedException.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/UserMismatchException.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/ValueNotAllowedException.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/v3/error/package-info.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/ValidateClerk.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/ValidateClientSubscriptionInfo.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/ValidateCustodyTransfer.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/ValidateInquiry.java (98%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/ValidateNode.java (98%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/ValidatePublish.java (98%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/ValidatePublisher.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/ValidateReplication.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/ValidateSecurity.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/ValidateSubscription.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/ValidateSubscriptionListener.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/ValidateUDDIApi.java (96%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/ValidateUDDIKey.java (97%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/ValidateUDDIv2Inquiry.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/ValidateValueSetCaching.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/ValidateValueSetValidation.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/ValidateValuesFromWebService.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/ValidationConstants.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/package-info.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/vsv/AbstractSimpleValidator.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationderivedfrom.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationentitykeyvalues.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationnodes.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationowningbusiness.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationtypes.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationvalidatedby.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgidentifierisreplacedby.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgrelationships.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/vsv/Uuid25b22e3e3dfa3024b02a3438b9050b59.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/vsv/Uuid327a56f032994461bc235cd513e95c55.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/vsv/Uuid4064c0646d144f3589539652106476a9.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/vsv/Uuid5678dd4ff95d35f99ea6f79a7dd64656.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/vsv/Uuid807a2c6aee22470dadc7e0424a337c03.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/vsv/Uuid916b87bf075639198eae97dfa325e5a4.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/vsv/Uuidc1acf26d967244049d7039b756e62ab4.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/vsv/Uuide59ae32077a511d5b8980004ac49cc1e.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/java/org/apache/juddi/validation/vsv/ValueSetValidator.java (100%) rename {juddi-core => juddi-core-openjpa}/src/main/resources/juddi_install_data/UDDI_Publisher.xml (97%) rename {juddi-core => juddi-core-openjpa}/src/main/resources/juddi_install_data/UDDI_tModels.xml (97%) rename {juddi-core => juddi-core-openjpa}/src/main/resources/juddi_install_data/root_BusinessEntity.xml (98%) rename {juddi-core => juddi-core-openjpa}/src/main/resources/juddi_install_data/root_Publisher.xml (97%) rename {juddi-core => juddi-core-openjpa}/src/main/resources/juddi_install_data/root_replicationConfiguration.xml (100%) rename {juddi-core => juddi-core-openjpa}/src/main/resources/juddi_install_data/root_tModelKeyGen.xml (97%) rename {juddi-core => juddi-core-openjpa}/src/main/resources/messages.properties (98%) delete mode 100644 juddi-core-openjpa/src/test/.gitignore rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/API_010_PublisherTest.java (97%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/API_020_TmodelTest.java (97%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/API_030_BusinessEntityTest.java (97%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/API_040_BusinessServiceLoadTest.java (98%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/API_040_BusinessServiceTest.java (97%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/API_050_BindingTemplateTest.java (98%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/API_051_BindingTemplateWSDLTest.java (97%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/API_060_PublisherAssertionTest.java (98%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/API_070_FindEntityTest.java (98%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/API_080_SubscriptionTest.java (97%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/API_090_SubscriptionListenerIntegrationTest.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/API_099_LoadTest.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/API_100_ClientSubscriptionInfoTest.java (97%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/API_110_FindBusinessTest.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/API_120_CombineCategoryBagsFindServiceTest.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/API_130_CombineCategoryBagsFindBusinessTest.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/API_140_NegativePublicationTest.java (97%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/API_141_JIRATest.java (97%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/API_150_ValueSetValidationTest.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/API_160_ReplicationTest.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/API_170_CustodyTransferTest.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/TokenTest.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/UDDIPublicationImplExt.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/UDDISecurityImplExt.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/impl/package.html (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/runtime/CLIServerTest.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/runtime/JuddiTestimpl.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/api/runtime/ReplicantImpl.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/auth/AuthenticatorTest.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/auth/MockHttpServletRequest.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/auth/MockMessageContext.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/auth/MockWebServiceContext.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/config/ApplicationConfigurationTest.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/config/InstallTest.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/config/ReleaseVersionTest.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/keygen/KeyGeneratorTest.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/replication/ReplicationNotifierTest.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/subscription/SubscriptionNotifierTest.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/subscription/notify/NotifierTest.java (100%) rename {juddi-core => juddi-core-openjpa}/src/test/java/org/apache/juddi/util/JPAUtil.java (95%) delete mode 100644 juddi-core/.gitignore delete mode 100644 juddi-core/pom.xml delete mode 100644 juddi-core/src/test/resources/META-INF/orm.xml delete mode 100644 juddi-core/src/test/resources/META-INF/persistence.xml delete mode 100644 juddi-core/src/test/resources/META-INF/uddi.xml delete mode 100644 juddi-core/src/test/resources/juddi-users-encrypted.xml delete mode 100644 juddi-core/src/test/resources/juddi-users-hashed.xml delete mode 100644 juddi-core/src/test/resources/juddi-users.xml delete mode 100644 juddi-core/src/test/resources/juddiv3-enc-3des.xml delete mode 100644 juddi-core/src/test/resources/juddiv3-enc-aes128.xml delete mode 100644 juddi-core/src/test/resources/juddiv3-enc-aes256.xml delete mode 100644 juddi-core/src/test/resources/juddiv3-enc-default.xml delete mode 100644 juddi-core/src/test/resources/juddiv3.xml delete mode 100644 juddi-core/src/test/resources/juddiv3DisabledTModelKeybag.xml delete mode 100644 juddi-core/src/test/resources/keystore.jks delete mode 100644 juddi-core/src/test/resources/log4j.xml delete mode 100644 juddi-core/src/test/resources/truststore.jks delete mode 100644 juddi-core/src/test/resources/wsdl/sample.wsdl delete mode 100644 juddi-dist/.gitignore delete mode 100644 juddi-examples/.gitignore delete mode 100644 juddi-examples/hello-world-embedded/.gitignore delete mode 100644 juddi-examples/hello-world/.gitignore delete mode 100644 juddi-examples/more-uddi-samples/.gitignore delete mode 100644 juddi-examples/service-version/.gitignore delete mode 100644 juddi-examples/simple-browse/.gitignore delete mode 100644 juddi-examples/simple-publish-clerk/.gitignore delete mode 100644 juddi-examples/simple-publish-portable/.gitignore delete mode 100644 juddi-examples/uddi-annotations/.gitignore delete mode 100644 juddi-examples/uddiv2-api-bridge-example/.gitignore delete mode 100644 juddi-examples/wsdl2uddi-lifecyle/.gitignore delete mode 100644 juddi-examples/wsdl2uddi/.gitignore delete mode 100644 juddi-extras/.gitignore delete mode 100644 juddi-gui/.gitignore delete mode 100644 juddi-rest-cxf/.gitignore delete mode 100644 juddi-tomcat/.gitignore delete mode 100644 juddiv3-war-repl/.gitignore delete mode 100644 juddiv3-war/.gitignore delete mode 100644 uddi-client-dist/.gitignore delete mode 100644 uddi-migration-tool/.gitignore delete mode 100644 uddi-tck-base/.gitignore delete mode 100644 uddi-tck-runner/.gitignore delete mode 100644 uddi-tck/.gitignore delete mode 100644 uddi-ws/.gitignore diff --git a/docs/.gitignore b/docs/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/docs/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/docs/asciidoc/.gitignore b/docs/asciidoc/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/docs/asciidoc/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/docs/asciidoc/ClientGuide/.gitignore b/docs/asciidoc/ClientGuide/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/docs/asciidoc/ClientGuide/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/docs/asciidoc/Guide/.gitignore b/docs/asciidoc/Guide/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/docs/asciidoc/Guide/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/docs/dist/.gitignore b/docs/dist/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/docs/dist/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/docs/examples/auth/pom.xml b/docs/examples/auth/pom.xml index f42954b4e..eab50cf49 100644 --- a/docs/examples/auth/pom.xml +++ b/docs/examples/auth/pom.xml @@ -44,7 +44,7 @@ org.apache.juddi - juddi-core + juddi-core-openjpa ${project.parent.version} compile diff --git a/juddi-client-cli/.gitignore b/juddi-client-cli/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddi-client-cli/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddi-client.net/.gitignore b/juddi-client.net/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddi-client.net/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddi-client/.gitignore b/juddi-client/.gitignore deleted file mode 100644 index d229ff0f1..000000000 --- a/juddi-client/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/ diff --git a/juddi-core-openjpa/.gitignore b/juddi-core-openjpa/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddi-core-openjpa/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddi-core-openjpa/pom.xml b/juddi-core-openjpa/pom.xml index e2adb03ff..d4df8044d 100644 --- a/juddi-core-openjpa/pom.xml +++ b/juddi-core-openjpa/pom.xml @@ -30,13 +30,7 @@ OpenJPA. - ../juddi-core/src/main/java - ../juddi-core/src/test/java - - - ../juddi-core/src/main/resources - - + org.apache.felix @@ -62,7 +56,7 @@ org.apache.openjpa openjpa-maven-plugin - 3.1.0 + 3.2.2 **/org/apache/juddi/model/*.class true @@ -82,34 +76,12 @@ org.apache.openjpa openjpa - 3.1.0 + 3.2.2 - - maven-clean-plugin - 2.6.1 - - - - src/main/java - - **/* - - false - - - src/test/java - - **/* - - false - - - - - + @@ -140,7 +112,7 @@ org.apache.openjpa openjpa - 2.3.0 + 3.2.2 org.apache.geronimo.specs diff --git a/juddi-core-openjpa/src/.gitignore b/juddi-core-openjpa/src/.gitignore deleted file mode 100644 index 95811e001..000000000 --- a/juddi-core-openjpa/src/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/main diff --git a/juddi-core/src/main/java/org/apache/juddi/ClassUtil.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/ClassUtil.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/ClassUtil.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/ClassUtil.java diff --git a/juddi-core/src/main/java/org/apache/juddi/Registry.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/Registry.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/Registry.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/Registry.java diff --git a/juddi-core/src/main/java/org/apache/juddi/api/impl/AuthenticatedService.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/AuthenticatedService.java similarity index 98% rename from juddi-core/src/main/java/org/apache/juddi/api/impl/AuthenticatedService.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/AuthenticatedService.java index 5886a5faa..631a0e3ac 100644 --- a/juddi-core/src/main/java/org/apache/juddi/api/impl/AuthenticatedService.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/AuthenticatedService.java @@ -1,253 +1,253 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.util.Date; -import javax.annotation.Resource; - -import javax.persistence.EntityManager; -import javax.servlet.http.HttpServletRequest; -import javax.xml.datatype.DatatypeConfigurationException; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.ws.WebServiceContext; -import javax.xml.ws.handler.MessageContext; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.Property; -import org.apache.juddi.model.UddiEntityPublisher; -import org.apache.juddi.v3.auth.Authenticator; -import org.apache.juddi.v3.auth.AuthenticatorFactory; -import org.apache.juddi.v3.error.AuthTokenRequiredException; -import org.apache.juddi.v3.error.AuthTokenExpiredException; -import org.apache.juddi.v3.error.ErrorMessage; -import org.uddi.v3_service.DispositionReportFaultMessage; - -/** - * Although this class is abstract, it provides token validation - * - * @author Jeff Faath - * - * @author Alex O'Ree - modified to - * include token expiration validation - */ -public abstract class AuthenticatedService { - - /** - * @return the node - */ - public String getNode() { - return node; - } - - public static final String UTF8 = "UTF-8"; - public static final int AUTHTOKEN_ACTIVE = 1; - public static final int AUTHTOKEN_RETIRED = 0; - static final Log logger = LogFactory.getLog(AuthenticatedService.class); - /** - * the node id of this server instance, as loaded from the config file - */ - private String node = "UNDEFINED_NODE_NAME"; - protected String baseUrlSSL = "UNDEFINED"; - protected String baseUrl = "UNDEFINED"; - protected DatatypeFactory df = null; - - public AuthenticatedService() { - try { - node = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID, "UNDEFINED_NODE_NAME"); - node = node.trim(); - baseUrlSSL = AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE, Property.DEFAULT_BASE_URL_SECURE); - baseUrlSSL = baseUrlSSL.trim(); - } catch (ConfigurationException ex) { - logger.fatal(null, ex); - } - init(); - } - - /** - * this method can be used to explicitly set a request context. this is useful - * in unit tests, embedded and in-vm scenarios only - * @param ctx - * @since 3.3.8 - */ - public void setContext(WebServiceContext ctx) { - this.ctx = ctx; - } - - private synchronized void init() { - try { - df = DatatypeFactory.newInstance(); - } catch (DatatypeConfigurationException ex) { - logger.fatal(null, ex); - } - } - - @Resource - protected WebServiceContext ctx; - - public UddiEntityPublisher getEntityPublisher(EntityManager em, String authInfo) throws DispositionReportFaultMessage { - boolean useAuthInfo = true; - try { - useAuthInfo = AppConfig.getConfiguration().getBoolean(Property.JUDDI_AUTHENTICATOR_USE_TOKEN, true); - } catch (ConfigurationException ex) { - - } - if (useAuthInfo) { - - if (authInfo == null || authInfo.length() == 0) { - throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthRequired")); - } - - org.apache.juddi.model.AuthToken modelAuthToken = em.find(org.apache.juddi.model.AuthToken.class, authInfo); - if (modelAuthToken == null) { - throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid")); - } - - int allowedMinutesOfInactivity = 0; - try { - allowedMinutesOfInactivity = AppConfig.getConfiguration().getInt(Property.JUDDI_AUTH_TOKEN_TIMEOUT, 0); - } catch (ConfigurationException ce) { - logger.error("Error reading property " + Property.JUDDI_AUTH_TOKEN_EXPIRATION + " from " - + "the application's configuration. No automatic timeout token invalidation will occur. " - + ce.getMessage(), ce); - } - int maxMinutesOfAge = 0; - try { - maxMinutesOfAge = AppConfig.getConfiguration().getInt(Property.JUDDI_AUTH_TOKEN_EXPIRATION, 0); - } catch (ConfigurationException ce) { - logger.error("Error reading property " + Property.JUDDI_AUTH_TOKEN_EXPIRATION + " from " - + "the application's configuration. No automatic timeout token invalidation will occur. " - + ce.getMessage(), ce); - } - Date now = new Date(); - // 0 or negative means token does not expire - if (allowedMinutesOfInactivity > 0) { - // expire tokens after # minutes of inactivity - // compare the time in milli-seconds - if (now.getTime() > modelAuthToken.getLastUsed().getTime() + allowedMinutesOfInactivity * 60000l) { - logger.info("AUDIT: FAILTURE Token " + modelAuthToken.getAuthToken() + " expired due to inactivity " + getRequestorsIPAddress()); - modelAuthToken.setTokenState(AUTHTOKEN_RETIRED); - } - } - if (maxMinutesOfAge > 0) { - // expire tokens when max age is reached - // compare the time in milli-seconds - if (now.getTime() > modelAuthToken.getCreated().getTime() + maxMinutesOfAge * 60000l) { - - logger.info("AUDIT: FAILURE - Token " + modelAuthToken.getAuthorizedName() + " expired due to old age " + getRequestorsIPAddress()); - modelAuthToken.setTokenState(AUTHTOKEN_RETIRED); - } - } - - if (modelAuthToken.getTokenState() == AUTHTOKEN_RETIRED) { - - throw new AuthTokenExpiredException(new ErrorMessage("errors.auth.AuthTokenExpired")); - } - if (ctx != null) { - try { - boolean check = true; - try { - check = AppConfig.getConfiguration().getBoolean(Property.JUDDI_AUTH_TOKEN_ENFORCE_SAME_IP, true); - } catch (ConfigurationException ex) { - logger.warn("Error loading config property " + Property.JUDDI_AUTH_TOKEN_ENFORCE_SAME_IP - + " Enforcing Same IP for Auth Tokens will be enabled by default", ex); - } - if (check) { - MessageContext mc = ctx.getMessageContext(); - HttpServletRequest req = null; - if (mc != null) { - req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST); - } - if (req != null - && req.getRemoteAddr() != null - && modelAuthToken.getIPAddress() != null - && !modelAuthToken.getIPAddress().equalsIgnoreCase(req.getRemoteAddr())) { - modelAuthToken.setTokenState(AUTHTOKEN_RETIRED); - logger.error("AUDIT FAILURE - Security Alert - Attempt to use issued auth token from a different IP address, user " - + modelAuthToken.getAuthorizedName() + ", issued IP " + modelAuthToken.getIPAddress() - + ", attempted use from " + req.getRemoteAddr() + ", forcing reauthentication."); - throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid")); - //invalidate the token, someone's intercepted it or it was reused on another ip - } - } - } catch (Exception ex) { - if (ex instanceof AuthTokenRequiredException) { - throw (AuthTokenRequiredException) ex; - } - logger.error("unexpected error caught looking up requestor's ip address", ex); - } - - } - Authenticator authenticator = AuthenticatorFactory.getAuthenticator(); - UddiEntityPublisher entityPublisher = authenticator.identify(authInfo, modelAuthToken.getAuthorizedName(), ctx); - - // Must make sure the returned publisher has all the necessary fields filled - if (entityPublisher == null) { - logger.warn("AUDIT FAILURE - Auth token invalid, publisher does not exist " + getRequestorsIPAddress()); - throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid")); - } - if (entityPublisher.getAuthorizedName() == null) { - logger.warn("AUDIT FAILURE - Auth token invalid, username does exist" + getRequestorsIPAddress()); - throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid")); - } - // Auth token is being used. Adjust appropriate values so that it's internal 'expiration clock' is reset. - modelAuthToken.setLastUsed(new Date()); - modelAuthToken.setNumberOfUses(modelAuthToken.getNumberOfUses() + 1); - return entityPublisher; - } else { - //use non-token based authentication - Authenticator authenticator = AuthenticatorFactory.getAuthenticator(); - UddiEntityPublisher entityPublisher = authenticator.identify(null, null, ctx); - // Must make sure the returned publisher has all the necessary fields filled - if (entityPublisher == null) { - logger.warn("AUDIT FAILURE - Auth token invalid, publisher does not exist " + getRequestorsIPAddress()); - throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid")); - } - if (entityPublisher.getAuthorizedName() == null) { - logger.warn("AUDIT FAILURE - Auth token invalid, username does exist" + getRequestorsIPAddress()); - throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid")); - } - return entityPublisher; - - } - - } - - /** - * Attempts to get the requestor's ip address from the servlet context, - * defaults to null it it can't be retrieved - * - * @return requestor's ip address or null if it's not available - */ - public String getRequestorsIPAddress() { - try { - MessageContext mc = ctx.getMessageContext(); - HttpServletRequest req = null; - if (mc != null) { - req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST); - } - if (req != null) { - return req.getRemoteAddr(); - } - } catch (Exception ex) { - logger.debug("Error caught looking up the requestor's ip address", ex); - } - return null; - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.util.Date; +import javax.annotation.Resource; + +import javax.persistence.EntityManager; +import javax.servlet.http.HttpServletRequest; +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.ws.WebServiceContext; +import javax.xml.ws.handler.MessageContext; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.Property; +import org.apache.juddi.model.UddiEntityPublisher; +import org.apache.juddi.v3.auth.Authenticator; +import org.apache.juddi.v3.auth.AuthenticatorFactory; +import org.apache.juddi.v3.error.AuthTokenRequiredException; +import org.apache.juddi.v3.error.AuthTokenExpiredException; +import org.apache.juddi.v3.error.ErrorMessage; +import org.uddi.v3_service.DispositionReportFaultMessage; + +/** + * Although this class is abstract, it provides token validation + * + * @author Jeff Faath + * + * @author Alex O'Ree - modified to + * include token expiration validation + */ +public abstract class AuthenticatedService { + + /** + * @return the node + */ + public String getNode() { + return node; + } + + public static final String UTF8 = "UTF-8"; + public static final int AUTHTOKEN_ACTIVE = 1; + public static final int AUTHTOKEN_RETIRED = 0; + static final Log logger = LogFactory.getLog(AuthenticatedService.class); + /** + * the node id of this server instance, as loaded from the config file + */ + private String node = "UNDEFINED_NODE_NAME"; + protected String baseUrlSSL = "UNDEFINED"; + protected String baseUrl = "UNDEFINED"; + protected DatatypeFactory df = null; + + public AuthenticatedService() { + try { + node = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID, "UNDEFINED_NODE_NAME"); + node = node.trim(); + baseUrlSSL = AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE, Property.DEFAULT_BASE_URL_SECURE); + baseUrlSSL = baseUrlSSL.trim(); + } catch (ConfigurationException ex) { + logger.fatal(null, ex); + } + init(); + } + + /** + * this method can be used to explicitly set a request context. this is useful + * in unit tests, embedded and in-vm scenarios only + * @param ctx + * @since 3.3.8 + */ + public void setContext(WebServiceContext ctx) { + this.ctx = ctx; + } + + private synchronized void init() { + try { + df = DatatypeFactory.newInstance(); + } catch (DatatypeConfigurationException ex) { + logger.fatal(null, ex); + } + } + + @Resource + protected WebServiceContext ctx; + + public UddiEntityPublisher getEntityPublisher(EntityManager em, String authInfo) throws DispositionReportFaultMessage { + boolean useAuthInfo = true; + try { + useAuthInfo = AppConfig.getConfiguration().getBoolean(Property.JUDDI_AUTHENTICATOR_USE_TOKEN, true); + } catch (ConfigurationException ex) { + + } + if (useAuthInfo) { + + if (authInfo == null || authInfo.length() == 0) { + throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthRequired")); + } + + org.apache.juddi.model.AuthToken modelAuthToken = em.find(org.apache.juddi.model.AuthToken.class, authInfo); + if (modelAuthToken == null) { + throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid")); + } + + int allowedMinutesOfInactivity = 0; + try { + allowedMinutesOfInactivity = AppConfig.getConfiguration().getInt(Property.JUDDI_AUTH_TOKEN_TIMEOUT, 0); + } catch (ConfigurationException ce) { + logger.error("Error reading property " + Property.JUDDI_AUTH_TOKEN_EXPIRATION + " from " + + "the application's configuration. No automatic timeout token invalidation will occur. " + + ce.getMessage(), ce); + } + int maxMinutesOfAge = 0; + try { + maxMinutesOfAge = AppConfig.getConfiguration().getInt(Property.JUDDI_AUTH_TOKEN_EXPIRATION, 0); + } catch (ConfigurationException ce) { + logger.error("Error reading property " + Property.JUDDI_AUTH_TOKEN_EXPIRATION + " from " + + "the application's configuration. No automatic timeout token invalidation will occur. " + + ce.getMessage(), ce); + } + Date now = new Date(); + // 0 or negative means token does not expire + if (allowedMinutesOfInactivity > 0) { + // expire tokens after # minutes of inactivity + // compare the time in milli-seconds + if (now.getTime() > modelAuthToken.getLastUsed().getTime() + allowedMinutesOfInactivity * 60000l) { + logger.info("AUDIT: FAILTURE Token " + modelAuthToken.getAuthToken() + " expired due to inactivity " + getRequestorsIPAddress()); + modelAuthToken.setTokenState(AUTHTOKEN_RETIRED); + } + } + if (maxMinutesOfAge > 0) { + // expire tokens when max age is reached + // compare the time in milli-seconds + if (now.getTime() > modelAuthToken.getCreated().getTime() + maxMinutesOfAge * 60000l) { + + logger.info("AUDIT: FAILURE - Token " + modelAuthToken.getAuthorizedName() + " expired due to old age " + getRequestorsIPAddress()); + modelAuthToken.setTokenState(AUTHTOKEN_RETIRED); + } + } + + if (modelAuthToken.getTokenState() == AUTHTOKEN_RETIRED) { + + throw new AuthTokenExpiredException(new ErrorMessage("errors.auth.AuthTokenExpired")); + } + if (ctx != null) { + try { + boolean check = true; + try { + check = AppConfig.getConfiguration().getBoolean(Property.JUDDI_AUTH_TOKEN_ENFORCE_SAME_IP, true); + } catch (ConfigurationException ex) { + logger.warn("Error loading config property " + Property.JUDDI_AUTH_TOKEN_ENFORCE_SAME_IP + + " Enforcing Same IP for Auth Tokens will be enabled by default", ex); + } + if (check) { + MessageContext mc = ctx.getMessageContext(); + HttpServletRequest req = null; + if (mc != null) { + req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST); + } + if (req != null + && req.getRemoteAddr() != null + && modelAuthToken.getIPAddress() != null + && !modelAuthToken.getIPAddress().equalsIgnoreCase(req.getRemoteAddr())) { + modelAuthToken.setTokenState(AUTHTOKEN_RETIRED); + logger.error("AUDIT FAILURE - Security Alert - Attempt to use issued auth token from a different IP address, user " + + modelAuthToken.getAuthorizedName() + ", issued IP " + modelAuthToken.getIPAddress() + + ", attempted use from " + req.getRemoteAddr() + ", forcing reauthentication."); + throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid")); + //invalidate the token, someone's intercepted it or it was reused on another ip + } + } + } catch (Exception ex) { + if (ex instanceof AuthTokenRequiredException) { + throw (AuthTokenRequiredException) ex; + } + logger.error("unexpected error caught looking up requestor's ip address", ex); + } + + } + Authenticator authenticator = AuthenticatorFactory.getAuthenticator(); + UddiEntityPublisher entityPublisher = authenticator.identify(authInfo, modelAuthToken.getAuthorizedName(), ctx); + + // Must make sure the returned publisher has all the necessary fields filled + if (entityPublisher == null) { + logger.warn("AUDIT FAILURE - Auth token invalid, publisher does not exist " + getRequestorsIPAddress()); + throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid")); + } + if (entityPublisher.getAuthorizedName() == null) { + logger.warn("AUDIT FAILURE - Auth token invalid, username does exist" + getRequestorsIPAddress()); + throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid")); + } + // Auth token is being used. Adjust appropriate values so that it's internal 'expiration clock' is reset. + modelAuthToken.setLastUsed(new Date()); + modelAuthToken.setNumberOfUses(modelAuthToken.getNumberOfUses() + 1); + return entityPublisher; + } else { + //use non-token based authentication + Authenticator authenticator = AuthenticatorFactory.getAuthenticator(); + UddiEntityPublisher entityPublisher = authenticator.identify(null, null, ctx); + // Must make sure the returned publisher has all the necessary fields filled + if (entityPublisher == null) { + logger.warn("AUDIT FAILURE - Auth token invalid, publisher does not exist " + getRequestorsIPAddress()); + throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid")); + } + if (entityPublisher.getAuthorizedName() == null) { + logger.warn("AUDIT FAILURE - Auth token invalid, username does exist" + getRequestorsIPAddress()); + throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid")); + } + return entityPublisher; + + } + + } + + /** + * Attempts to get the requestor's ip address from the servlet context, + * defaults to null it it can't be retrieved + * + * @return requestor's ip address or null if it's not available + */ + public String getRequestorsIPAddress() { + try { + MessageContext mc = ctx.getMessageContext(); + HttpServletRequest req = null; + if (mc != null) { + req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST); + } + if (req != null) { + return req.getRemoteAddr(); + } + } catch (Exception ex) { + logger.debug("Error caught looking up the requestor's ip address", ex); + } + return null; + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/api/impl/InquiryHelper.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/InquiryHelper.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/api/impl/InquiryHelper.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/InquiryHelper.java index b4b88ed55..691314648 100644 --- a/juddi-core/src/main/java/org/apache/juddi/api/impl/InquiryHelper.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/InquiryHelper.java @@ -1,650 +1,650 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.util.ArrayList; -import java.util.Date; -import java.util.LinkedList; -import java.util.List; - -import javax.persistence.EntityManager; -import javax.xml.ws.Holder; -import org.apache.commons.configuration.ConfigurationException; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.Property; -import org.apache.juddi.mapping.MappingModelToApi; -import org.apache.juddi.model.BindingTemplate; -import org.apache.juddi.query.FetchBindingTemplatesQuery; -import org.apache.juddi.query.FetchBusinessEntitiesQuery; -import org.apache.juddi.query.FetchBusinessServicesQuery; -import org.apache.juddi.query.FetchTModelsQuery; -import org.apache.juddi.query.FindBindingByCategoryGroupQuery; -import org.apache.juddi.query.FindBindingByCategoryQuery; -import org.apache.juddi.query.FindBindingByTModelKeyQuery; -import org.apache.juddi.query.FindBusinessByCategoryGroupQuery; -import org.apache.juddi.query.FindBusinessByCategoryQuery; -import org.apache.juddi.query.FindBusinessByCombinedCategoryQuery; -import org.apache.juddi.query.FindBusinessByDiscoveryURLQuery; -import org.apache.juddi.query.FindBusinessByIdentifierQuery; -import org.apache.juddi.query.FindBusinessByNameQuery; -import org.apache.juddi.query.FindBusinessByTModelKeyQuery; -import org.apache.juddi.query.FindServiceByCategoryGroupQuery; -import org.apache.juddi.query.FindServiceByCategoryQuery; -import org.apache.juddi.query.FindServiceByCombinedCategoryQuery; -import org.apache.juddi.query.FindServiceByNameQuery; -import org.apache.juddi.query.FindServiceByTModelKeyQuery; -import org.apache.juddi.query.FindTModelByCategoryGroupQuery; -import org.apache.juddi.query.FindTModelByCategoryQuery; -import org.apache.juddi.query.FindTModelByIdentifierQuery; -import org.apache.juddi.query.FindTModelByNameQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.InvalidKeyPassedException; -import org.uddi.api_v3.BindingDetail; -import org.uddi.api_v3.BusinessList; -import org.uddi.api_v3.Direction; -import org.uddi.api_v3.FindBinding; -import org.uddi.api_v3.FindBusiness; -import org.uddi.api_v3.FindRelatedBusinesses; -import org.uddi.api_v3.FindService; -import org.uddi.api_v3.FindTModel; -import org.uddi.api_v3.ListDescription; -import org.uddi.api_v3.Name; -import org.uddi.api_v3.RelatedBusinessesList; -import org.uddi.api_v3.ServiceList; -import org.uddi.api_v3.TModelBag; -import org.uddi.api_v3.TModelList; -import org.uddi.v3_service.DispositionReportFaultMessage; - -/**Co - * Used to factor out inquiry functionality as it is used in more than one spot. - * - * @author Jeff Faath - */ -public class InquiryHelper { - - private static Log logger = LogFactory.getLog(InquiryHelper.class); - - public static List findBinding(FindBinding body, FindQualifiers findQualifiers, EntityManager em) throws DispositionReportFaultMessage { - - List keysFound = new LinkedList(); - if (body.getServiceKey()!=null && body.getServiceKey().length() > 0) { - keysFound = findBindingsByServiceKey(em, body.getServiceKey(), keysFound); - } - - if (body.getTModelBag() == null) - body.setTModelBag(new TModelBag()); - // First perform the embedded FindTModel search which will augment the tModel bag with any resulting tModel keys. - doFindTModelEmbeddedSearch(em, body.getFindQualifiers(), body.getFindTModel(), body.getTModelBag()); - keysFound = FindBindingByTModelKeyQuery.select(em, findQualifiers, body.getTModelBag(), body.getServiceKey(), keysFound); - keysFound = FindBindingByCategoryQuery.select(em, findQualifiers, body.getCategoryBag(), body.getServiceKey(), keysFound); - keysFound = FindBindingByCategoryGroupQuery.select(em, findQualifiers, body.getCategoryBag(), body.getServiceKey(), keysFound); - - return keysFound; - } - - public static BindingDetail getBindingDetailFromKeys(FindBinding body, FindQualifiers findQualifiers, EntityManager em, List keysFound) throws DispositionReportFaultMessage { - return getBindingDetailFromKeys(body, findQualifiers, em, keysFound, null, null, null, null); - } - - public static BindingDetail getBindingDetailFromKeys(FindBinding body, FindQualifiers findQualifiers, EntityManager em, List keysFound, - Date modifiedAfter, Date modifiedBefore, Holder subscriptionStartIndex, Integer subscriptionMaxRows) - throws DispositionReportFaultMessage { - - BindingDetail result = new BindingDetail(); - ListDescription listDesc = new ListDescription(); - result.setListDescription(listDesc); - - // Sort and retrieve the final results with paging taken into account - List queryResults = FetchBindingTemplatesQuery.select(em, findQualifiers, keysFound, body.getMaxRows(), body.getListHead(), listDesc); - - // Set the currentIndex to 0 or the value of the subscriptionStartIndex - int currentIndex = 0; - if (subscriptionStartIndex != null && subscriptionStartIndex.value != null) - currentIndex = subscriptionStartIndex.value; - - int returnedRowCount = 0; - - while (currentIndex < queryResults.size()) { - Object item = queryResults.get(currentIndex); - - org.apache.juddi.model.BindingTemplate modelBindingTemplate = (org.apache.juddi.model.BindingTemplate)item; - org.uddi.api_v3.BindingTemplate apiBindingTemplate = new org.uddi.api_v3.BindingTemplate(); - - if (modifiedAfter != null && modifiedAfter.after(modelBindingTemplate.getModifiedIncludingChildren())) { - currentIndex++; - continue; - } - - if (modifiedBefore != null && modifiedBefore.before(modelBindingTemplate.getModifiedIncludingChildren())) { - currentIndex++; - continue; - } - - MappingModelToApi.mapBindingTemplate(modelBindingTemplate, apiBindingTemplate); - - result.getBindingTemplate().add(apiBindingTemplate); - - returnedRowCount++; - // If the returned rows equals the max allowed, we can end the loop (applies to subscription calls only) - if (subscriptionMaxRows != null) { - if (returnedRowCount == subscriptionMaxRows) - break; - } - - currentIndex++; - } - - // If the loop was broken prematurely (max row count hit) we set the subscriptionStartIndex to the next index to start with. - // Otherwise, set it to null so the subscription call won't trigger chunk token generation. - if (currentIndex < (queryResults.size() - 1)) { - if (subscriptionStartIndex != null) - subscriptionStartIndex.value = currentIndex + 1; - result.setTruncated(Boolean.TRUE); - } - else { - if (subscriptionStartIndex != null) - subscriptionStartIndex.value = null; - result.setTruncated(Boolean.FALSE); - } - result.getListDescription().setListHead(currentIndex); - result.getListDescription().setActualCount(result.getBindingTemplate().size()); - result.getListDescription().setIncludeCount(returnedRowCount); - return result; - } - - public static List findBusiness(FindBusiness body, FindQualifiers findQualifiers, EntityManager em) throws DispositionReportFaultMessage { - - List keysFound = null; - - // First perform the embedded FindTModel search which will augment the tModel bag with any resulting tModel keys. - if (body.getTModelBag() == null) - body.setTModelBag(new TModelBag()); - doFindTModelEmbeddedSearch(em, body.getFindQualifiers(), body.getFindTModel(), body.getTModelBag()); - - // The embedded find_relatedBusinesses search is performed first. This is done the same as the actual API call, except the resulting business keys are - // extracted and placed in the keysFound array to restrict future searches to only those keys. - if (body.getFindRelatedBusinesses() != null) { - FindRelatedBusinesses frb = body.getFindRelatedBusinesses(); - - org.uddi.api_v3.RelatedBusinessInfos relatedBusinessInfos = new org.uddi.api_v3.RelatedBusinessInfos(); - if (body.getFindRelatedBusinesses().getBusinessKey() != null ) { - getRelatedBusinesses(em, Direction.FROM_KEY, frb.getBusinessKey(), frb.getKeyedReference(), relatedBusinessInfos); - getRelatedBusinesses(em, Direction.TO_KEY, frb.getBusinessKey(), frb.getKeyedReference(), relatedBusinessInfos); - } - else if (body.getFindRelatedBusinesses().getFromKey() != null) - getRelatedBusinesses(em, Direction.FROM_KEY, frb.getFromKey(), frb.getKeyedReference(), relatedBusinessInfos); - else if (body.getFindRelatedBusinesses().getToKey() != null) - getRelatedBusinesses(em, Direction.TO_KEY, frb.getToKey(), frb.getKeyedReference(), relatedBusinessInfos); - - List relatedBusinessKeys = new ArrayList(0); - for (org.uddi.api_v3.RelatedBusinessInfo rbi : relatedBusinessInfos.getRelatedBusinessInfo()) - relatedBusinessKeys.add(rbi.getBusinessKey()); - - keysFound = relatedBusinessKeys; - } - - keysFound = FindBusinessByTModelKeyQuery.select(em, findQualifiers, body.getTModelBag(), keysFound); - keysFound = FindBusinessByIdentifierQuery.select(em, findQualifiers, body.getIdentifierBag(), keysFound); - keysFound = FindBusinessByDiscoveryURLQuery.select(em, findQualifiers, body.getDiscoveryURLs(), keysFound); - if (findQualifiers.isCombineCategoryBags()) { - keysFound = FindBusinessByCombinedCategoryQuery.select(em, findQualifiers, body.getCategoryBag(), keysFound); - } else { - keysFound = FindBusinessByCategoryQuery.select(em, findQualifiers, body.getCategoryBag(), keysFound); - } - - keysFound = FindBusinessByCategoryGroupQuery.select(em, findQualifiers, body.getCategoryBag(), keysFound); - keysFound = FindBusinessByNameQuery.select(em, findQualifiers, body.getName(), keysFound); - - // If there no keys in the bag then remove the empty TModelBag - if (body.getTModelBag().getTModelKey().size()==0) body.setTModelBag(null); - - return keysFound; - } - - public static BusinessList getBusinessListFromKeys(FindBusiness body, FindQualifiers findQualifiers, EntityManager em, List keysFound) throws DispositionReportFaultMessage { - return getBusinessListFromKeys(body, findQualifiers, em, keysFound, null, null, null, null); - } - - public static BusinessList getBusinessListFromKeys(FindBusiness body, FindQualifiers findQualifiers, EntityManager em, List keysFound, - Date modifiedAfter, Date modifiedBefore, Holder subscriptionStartIndex, Integer subscriptionMaxRows) - throws DispositionReportFaultMessage { - - BusinessList result = new BusinessList(); - ListDescription listDesc = new ListDescription(); - result.setListDescription(listDesc); - - // Sort and retrieve the final results taking paging into account - List queryResults = FetchBusinessEntitiesQuery.select(em, findQualifiers, keysFound, body.getMaxRows(), body.getListHead(), listDesc); - - boolean enabled = true; - try { - //AppConfig.reloadConfig(); - enabled= AppConfig.getConfiguration().getBoolean(Property.JUDDI_ENABLE_FIND_BUSINESS_TMODEL_BAG_FILTERING, true); - } catch (ConfigurationException ex) { - logger.error(ex); - } - if (enabled) { - logger.info("FindBusiness by tModelBag is enabled! Loaded from " + AppConfig.getConfigFileURL()); - List serviceResults = null; - for (int i = 0; i < queryResults.size(); i++) { - org.apache.juddi.model.BusinessEntity be = (org.apache.juddi.model.BusinessEntity) queryResults.get(i); - - List keysIn = new ArrayList(); - List services = be.getBusinessServices(); - for (int j = 0; j < services.size(); j++) { - keysIn.add(services.get(j).getEntityKey()); - } - - serviceResults = FindServiceByTModelKeyQuery.select(em, findQualifiers, body.getTModelBag(), null, keysIn); - if (serviceResults == null) { - be.setBusinessServices(null); - } else { - ListDescription ldesc = new ListDescription(); - result.setListDescription(listDesc); - List srvcs = FetchBusinessServicesQuery.select(em, findQualifiers, serviceResults, body.getMaxRows(), - body.getListHead(), ldesc); - be.setBusinessServices((List) srvcs); - } - } - } - - - if (queryResults != null && queryResults.size() > 0) - result.setBusinessInfos(new org.uddi.api_v3.BusinessInfos()); - - // Set the currentIndex to 0 or the value of the subscriptionStartIndex - int currentIndex = 0; - if (subscriptionStartIndex != null && subscriptionStartIndex.value != null) - currentIndex = subscriptionStartIndex.value; - - int returnedRowCount = 0; - - while (queryResults!=null && currentIndex < queryResults.size()) { - Object item = queryResults.get(currentIndex); - - org.apache.juddi.model.BusinessEntity modelBusinessEntity = (org.apache.juddi.model.BusinessEntity)item; - org.uddi.api_v3.BusinessInfo apiBusinessInfo = new org.uddi.api_v3.BusinessInfo(); - - if (modifiedAfter != null && modifiedAfter.after(modelBusinessEntity.getModifiedIncludingChildren())){ - currentIndex++; - continue; - } - - if (modifiedBefore != null && modifiedBefore.before(modelBusinessEntity.getModifiedIncludingChildren())) { - currentIndex++; - continue; - } - - MappingModelToApi.mapBusinessInfo(modelBusinessEntity, apiBusinessInfo); - - result.getBusinessInfos().getBusinessInfo().add(apiBusinessInfo); - - returnedRowCount++; - // If the returned rows equals the max allowed, we can end the loop (applies to subscription calls only) - if (subscriptionMaxRows != null) { - if (returnedRowCount == subscriptionMaxRows) - break; - } - - currentIndex++; - } - - // If the loop was broken prematurely (max row count hit) we set the subscriptionStartIndex to the next index to start with. - // Otherwise, set it to null so the subscription call won't trigger chunk token generation. - if (queryResults!=null && currentIndex < (queryResults.size() - 1)) { - if (subscriptionStartIndex != null) - subscriptionStartIndex.value = currentIndex + 1; - result.setTruncated(Boolean.TRUE); - } - else { - if (subscriptionStartIndex != null) - subscriptionStartIndex.value = null; - result.setTruncated(Boolean.FALSE); - } - return result; - } - - public static List findService(FindService body, FindQualifiers findQualifiers, EntityManager em) throws DispositionReportFaultMessage { - - List keysFound = null; - - // First perform the embedded FindTModel search which will augment the tModel bag with any resulting tModel keys. - if (body.getTModelBag() == null) - body.setTModelBag(new TModelBag()); - doFindTModelEmbeddedSearch(em, body.getFindQualifiers(), body.getFindTModel(), body.getTModelBag()); - - keysFound = FindServiceByTModelKeyQuery.select(em, findQualifiers, body.getTModelBag(), body.getBusinessKey(), keysFound); - if (findQualifiers.isCombineCategoryBags()) { - keysFound = FindServiceByCombinedCategoryQuery.select(em, findQualifiers, body.getCategoryBag(), body.getBusinessKey(), keysFound); - } else { - keysFound = FindServiceByCategoryQuery.select(em, findQualifiers, body.getCategoryBag(), body.getBusinessKey(), keysFound); - } - keysFound = FindServiceByCategoryGroupQuery.select(em, findQualifiers, body.getCategoryBag(), body.getBusinessKey(), keysFound); - - if (body.getFindTModel()==null && body.getCategoryBag()==null && - ( body.getTModelBag()==null || body.getTModelBag().getTModelKey().size() == 0) - && body.getName().size() == 0 && body.getBusinessKey() != null) { - //support searching for all services for a business - findQualifiers.setApproximateMatch(true); - body.getName().add(new Name("%", null)); - } - keysFound = FindServiceByNameQuery.select(em, findQualifiers, body.getName(), body.getBusinessKey(), keysFound); - - if (body.getTModelBag().getTModelKey().size()==0) body.setTModelBag(null); - return keysFound; - } - - public static ServiceList getServiceListFromKeys(FindService body, FindQualifiers findQualifiers, EntityManager em, List keysFound) throws DispositionReportFaultMessage { - return getServiceListFromKeys(body, findQualifiers, em, keysFound, null, null, null, null); - } - - public static ServiceList getServiceListFromKeys(FindService body, FindQualifiers findQualifiers, EntityManager em, List keysFound, - Date modifiedAfter, Date modifiedBefore, Holder subscriptionStartIndex, Integer subscriptionMaxRows) - throws DispositionReportFaultMessage { - ServiceList result = new ServiceList(); - ListDescription listDesc = new ListDescription(); - result.setListDescription(listDesc); - - // Sort and retrieve the final results taking paging into account - List queryResults = FetchBusinessServicesQuery.select(em, findQualifiers, keysFound, body.getMaxRows(), body.getListHead(), listDesc); - if (queryResults != null && queryResults.size() > 0) - result.setServiceInfos(new org.uddi.api_v3.ServiceInfos()); - - // Set the currentIndex to 0 or the value of the subscriptionStartIndex - int currentIndex = 0; - if (subscriptionStartIndex != null && subscriptionStartIndex.value != null) - currentIndex = subscriptionStartIndex.value; - - int returnedRowCount = 0; - if (logger.isDebugEnabled()) logger.debug("Period = " + modifiedAfter + " ---- " + modifiedBefore); - while (queryResults!=null && currentIndex < queryResults.size()) { - Object item = queryResults.get(currentIndex); - - org.apache.juddi.model.BusinessService modelBusinessService = (org.apache.juddi.model.BusinessService)item; - org.uddi.api_v3.ServiceInfo apiServiceInfo = new org.uddi.api_v3.ServiceInfo(); - - logger.debug(modelBusinessService.getEntityKey() + " is modified " + modelBusinessService.getModifiedIncludingChildren() + " " + modelBusinessService.getModifiedIncludingChildren().getTime() ); - if (modifiedAfter != null && modifiedAfter.after(modelBusinessService.getModifiedIncludingChildren())) { - currentIndex++; - continue; - } - - if (modifiedBefore != null && modifiedBefore.before(modelBusinessService.getModifiedIncludingChildren())) { - currentIndex++; - continue; - } - MappingModelToApi.mapServiceInfo(modelBusinessService, apiServiceInfo); - - result.getServiceInfos().getServiceInfo().add(apiServiceInfo); - - returnedRowCount++; - // If the returned rows equals the max allowed, we can end the loop (applies to subscription calls only) - if (subscriptionMaxRows != null) { - if (returnedRowCount == subscriptionMaxRows) - break; - } - - currentIndex++; - } - - // If the loop was broken prematurely (max row count hit) we set the subscriptionStartIndex to the next index to start with. - // Otherwise, set it to null so the subscription call won't trigger chunk token generation. - if (queryResults!=null && currentIndex < (queryResults.size() - 1)) { - if (subscriptionStartIndex != null) - subscriptionStartIndex.value = currentIndex + 1; - result.setTruncated(Boolean.TRUE); - } - else { - if (subscriptionStartIndex != null) - subscriptionStartIndex.value = null; - result.setTruncated(Boolean.FALSE); - } - - return result; - } - - public static List findTModel(FindTModel body, FindQualifiers findQualifiers, EntityManager em) throws DispositionReportFaultMessage { - List keysFound = null; - - keysFound = FindTModelByIdentifierQuery.select(em, findQualifiers, body.getIdentifierBag(), keysFound); - keysFound = FindTModelByCategoryQuery.select(em, findQualifiers, body.getCategoryBag(), keysFound); - keysFound = FindTModelByCategoryGroupQuery.select(em, findQualifiers, body.getCategoryBag(), keysFound); - keysFound = FindTModelByNameQuery.select(em, findQualifiers, body.getName(), keysFound); - - return keysFound; - } - - public static TModelList getTModelListFromKeys(FindTModel body, FindQualifiers findQualifiers, EntityManager em, List keysFound) throws DispositionReportFaultMessage { - return getTModelListFromKeys(body, findQualifiers, em, keysFound, null, null, null, null); - } - - public static TModelList getTModelListFromKeys(FindTModel body, FindQualifiers findQualifiers, EntityManager em, List keysFound, - Date modifiedAfter, Date modifiedBefore, Holder subscriptionStartIndex, Integer subscriptionMaxRows) - throws DispositionReportFaultMessage { - TModelList result = new TModelList(); - ListDescription listDesc = new ListDescription(); - result.setListDescription(listDesc); - - // Sort and retrieve the final results taking paging into account - List queryResults = FetchTModelsQuery.select(em, findQualifiers, keysFound, body.getMaxRows(), body.getListHead(), listDesc); - if (queryResults != null && queryResults.size() > 0) - result.setTModelInfos(new org.uddi.api_v3.TModelInfos()); - - // Set the currentIndex to 0 or the value of the subscriptionStartIndex - int currentIndex = 0; - if (subscriptionStartIndex != null && subscriptionStartIndex.value != null) - currentIndex = subscriptionStartIndex.value; - - int returnedRowCount = 0; - - while (queryResults!=null && currentIndex < queryResults.size()) { - Object item = queryResults.get(currentIndex); - - org.apache.juddi.model.Tmodel modelTModel = (org.apache.juddi.model.Tmodel)item; - org.uddi.api_v3.TModelInfo apiTModelInfo = new org.uddi.api_v3.TModelInfo(); - - if (modifiedAfter != null && modifiedAfter.after(modelTModel.getModifiedIncludingChildren())) { - currentIndex++; - continue; - } - - if (modifiedBefore != null && modifiedBefore.before(modelTModel.getModifiedIncludingChildren())) { - currentIndex++; - continue; - } - - MappingModelToApi.mapTModelInfo(modelTModel, apiTModelInfo); - - result.getTModelInfos().getTModelInfo().add(apiTModelInfo); - - returnedRowCount++; - // If the returned rows equals the max allowed, we can end the loop (applies to subscription calls only) - if (subscriptionMaxRows != null) { - if (returnedRowCount == subscriptionMaxRows) - break; - } - - currentIndex++; - } - - // If the loop was broken prematurely (max row count hit) we set the subscriptionStartIndex to the next index to start with. - // Otherwise, set it to null so the subscription call won't trigger chunk token generation. - if (queryResults!=null && currentIndex < (queryResults.size() - 1)) { - if (subscriptionStartIndex != null) - subscriptionStartIndex.value = currentIndex + 1; - result.setTruncated(Boolean.TRUE); - } - else { - if (subscriptionStartIndex != null) - subscriptionStartIndex.value = null; - result.setTruncated(Boolean.FALSE); - } - - return result; - } - - - /* - * Retrieves related businesses based on the focal business and the direction (fromKey or toKey). The focal business is retrieved and then the - * appropriate publisher assertion collection is examined for matches. The assertion must be "completed" and if a keyedReference is passed, it must - * match exactly. Successful assertion matches are mapped to a RelationBusinessInfo structure and added to the passed in RelationalBusinessInfos - * structure. - */ - public static void getRelatedBusinesses(EntityManager em, - Direction direction, - String focalKey, - org.uddi.api_v3.KeyedReference keyedRef, - org.uddi.api_v3.RelatedBusinessInfos relatedBusinessInfos) - throws DispositionReportFaultMessage { - getRelatedBusinesses(em, direction, focalKey, keyedRef, relatedBusinessInfos, null, null); - } - - public static void getRelatedBusinesses(EntityManager em, - Direction direction, - String focalKey, - org.uddi.api_v3.KeyedReference keyedRef, - org.uddi.api_v3.RelatedBusinessInfos relatedBusinessInfos, - Date modifiedAfter, - Date modifiedBefore) - throws DispositionReportFaultMessage { - if (relatedBusinessInfos == null) - relatedBusinessInfos = new org.uddi.api_v3.RelatedBusinessInfos(); - org.apache.juddi.model.BusinessEntity focalBusiness = null; - try { - focalBusiness = em.find(org.apache.juddi.model.BusinessEntity.class, focalKey); - } catch (ClassCastException e) {} - if (focalBusiness == null) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BusinessNotFound", focalKey)); - - List pubAssertList = null; - if (direction == Direction.FROM_KEY) - pubAssertList = focalBusiness.getPublisherAssertionsForFromKey(); - else - pubAssertList = focalBusiness.getPublisherAssertionsForToKey(); - - if (pubAssertList != null) { - for (org.apache.juddi.model.PublisherAssertion modelPublisherAssertion : pubAssertList) { - if ("true".equalsIgnoreCase(modelPublisherAssertion.getFromCheck()) && "true".equalsIgnoreCase(modelPublisherAssertion.getToCheck())) { - if (keyedRef != null) { - if(!keyedRef.getTModelKey().equals(modelPublisherAssertion.getTmodelKey()) || - !keyedRef.getKeyName().equals(modelPublisherAssertion.getKeyName()) || - !keyedRef.getKeyValue().equals(modelPublisherAssertion.getKeyValue())) { - continue; - } - } - - org.apache.juddi.model.BusinessEntity modelRelatedBusiness = null; - if (direction == Direction.FROM_KEY) - modelRelatedBusiness = em.find(org.apache.juddi.model.BusinessEntity.class, modelPublisherAssertion.getId().getToKey()); - else - modelRelatedBusiness = em.find(org.apache.juddi.model.BusinessEntity.class, modelPublisherAssertion.getId().getFromKey()); - - if (modifiedAfter != null && modifiedAfter.after(modelRelatedBusiness.getModifiedIncludingChildren())) - continue; - - if (modifiedBefore != null && modifiedBefore.before(modelRelatedBusiness.getModifiedIncludingChildren())) - continue; - - org.uddi.api_v3.RelatedBusinessInfo apiRelatedBusinessInfo = new org.uddi.api_v3.RelatedBusinessInfo(); - - MappingModelToApi.mapRelatedBusinessInfo(modelPublisherAssertion, modelRelatedBusiness, direction, apiRelatedBusinessInfo); - - relatedBusinessInfos.getRelatedBusinessInfo().add(apiRelatedBusinessInfo); - } - } - } - - } - - public static RelatedBusinessesList getRelatedBusinessesList(FindRelatedBusinesses body, EntityManager em) throws DispositionReportFaultMessage { - return getRelatedBusinessesList(body, em, null, null); - } - - public static RelatedBusinessesList getRelatedBusinessesList(FindRelatedBusinesses body, EntityManager em, Date modifiedAfter, Date modifiedBefore) throws DispositionReportFaultMessage { - RelatedBusinessesList result = new RelatedBusinessesList(); - result.setBusinessKey(body.getBusinessKey()); - ListDescription listDesc = new ListDescription(); - result.setListDescription(listDesc); - - // Either one of the businessKey, fromKey or toKey will be passed. This is considered the "focal" business to which related businesses must be - // found. Rather than use a query, it seems simpler to take advantage of the model's publisher assertion collections. - org.uddi.api_v3.RelatedBusinessInfos relatedBusinessInfos = new org.uddi.api_v3.RelatedBusinessInfos(); - if (body.getBusinessKey() != null ) { - InquiryHelper.getRelatedBusinesses(em, Direction.FROM_KEY, body.getBusinessKey(), body.getKeyedReference(), relatedBusinessInfos, modifiedAfter, modifiedBefore); - InquiryHelper.getRelatedBusinesses(em, Direction.TO_KEY, body.getBusinessKey(), body.getKeyedReference(), relatedBusinessInfos, modifiedAfter, modifiedBefore); - } - else if (body.getFromKey() != null) { - InquiryHelper.getRelatedBusinesses(em, Direction.FROM_KEY, body.getFromKey(), body.getKeyedReference(), relatedBusinessInfos, modifiedAfter, modifiedBefore); - result.setBusinessKey(body.getFromKey()); - } else if (body.getToKey() != null) { - InquiryHelper.getRelatedBusinesses(em, Direction.TO_KEY, body.getToKey(), body.getKeyedReference(), relatedBusinessInfos, modifiedAfter, modifiedBefore); - result.setBusinessKey(body.getToKey()); - } - if (relatedBusinessInfos.getRelatedBusinessInfo().size() > 0) { - // TODO: Do proper pagination! - listDesc.setActualCount(relatedBusinessInfos.getRelatedBusinessInfo().size()); - listDesc.setIncludeCount(relatedBusinessInfos.getRelatedBusinessInfo().size()); - listDesc.setListHead(1); - - result.setRelatedBusinessInfos(relatedBusinessInfos); - } - - return result; - } - - /** - * Performs the necessary queries for the find_tModel search and adds resulting tModel keys to the tModelBag provided. - */ - private static void doFindTModelEmbeddedSearch(EntityManager em, - org.uddi.api_v3.FindQualifiers fq, - FindTModel findTmodel, - TModelBag tmodelBag) - throws DispositionReportFaultMessage { - - - if (findTmodel != null && tmodelBag != null) { - org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); - findQualifiers.mapApiFindQualifiers(findTmodel.getFindQualifiers()); - - - List tmodelKeysFound = null; - tmodelKeysFound = FindTModelByIdentifierQuery.select(em, findQualifiers, findTmodel.getIdentifierBag(), tmodelKeysFound); - tmodelKeysFound = FindTModelByCategoryQuery.select(em, findQualifiers, findTmodel.getCategoryBag(), tmodelKeysFound); - tmodelKeysFound = FindTModelByCategoryGroupQuery.select(em, findQualifiers, findTmodel.getCategoryBag(), tmodelKeysFound); - tmodelKeysFound = FindTModelByNameQuery.select(em, findQualifiers, findTmodel.getName(), tmodelKeysFound); - - if (tmodelKeysFound != null && tmodelKeysFound.size() > 0) { - for (Object item : tmodelKeysFound) - tmodelBag.getTModelKey().add((String)item); - } - } - } - - private static List findBindingsByServiceKey(EntityManager em, String serviceKey, List keysFound) { - org.apache.juddi.model.BusinessService modelBusinessService=em.find(org.apache.juddi.model.BusinessService.class, serviceKey); - for (BindingTemplate bt : modelBusinessService.getBindingTemplates()){ - keysFound.add(bt.getEntityKey()); - } - return keysFound; - } - - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.util.ArrayList; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.xml.ws.Holder; +import org.apache.commons.configuration.ConfigurationException; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.Property; +import org.apache.juddi.mapping.MappingModelToApi; +import org.apache.juddi.model.BindingTemplate; +import org.apache.juddi.query.FetchBindingTemplatesQuery; +import org.apache.juddi.query.FetchBusinessEntitiesQuery; +import org.apache.juddi.query.FetchBusinessServicesQuery; +import org.apache.juddi.query.FetchTModelsQuery; +import org.apache.juddi.query.FindBindingByCategoryGroupQuery; +import org.apache.juddi.query.FindBindingByCategoryQuery; +import org.apache.juddi.query.FindBindingByTModelKeyQuery; +import org.apache.juddi.query.FindBusinessByCategoryGroupQuery; +import org.apache.juddi.query.FindBusinessByCategoryQuery; +import org.apache.juddi.query.FindBusinessByCombinedCategoryQuery; +import org.apache.juddi.query.FindBusinessByDiscoveryURLQuery; +import org.apache.juddi.query.FindBusinessByIdentifierQuery; +import org.apache.juddi.query.FindBusinessByNameQuery; +import org.apache.juddi.query.FindBusinessByTModelKeyQuery; +import org.apache.juddi.query.FindServiceByCategoryGroupQuery; +import org.apache.juddi.query.FindServiceByCategoryQuery; +import org.apache.juddi.query.FindServiceByCombinedCategoryQuery; +import org.apache.juddi.query.FindServiceByNameQuery; +import org.apache.juddi.query.FindServiceByTModelKeyQuery; +import org.apache.juddi.query.FindTModelByCategoryGroupQuery; +import org.apache.juddi.query.FindTModelByCategoryQuery; +import org.apache.juddi.query.FindTModelByIdentifierQuery; +import org.apache.juddi.query.FindTModelByNameQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.InvalidKeyPassedException; +import org.uddi.api_v3.BindingDetail; +import org.uddi.api_v3.BusinessList; +import org.uddi.api_v3.Direction; +import org.uddi.api_v3.FindBinding; +import org.uddi.api_v3.FindBusiness; +import org.uddi.api_v3.FindRelatedBusinesses; +import org.uddi.api_v3.FindService; +import org.uddi.api_v3.FindTModel; +import org.uddi.api_v3.ListDescription; +import org.uddi.api_v3.Name; +import org.uddi.api_v3.RelatedBusinessesList; +import org.uddi.api_v3.ServiceList; +import org.uddi.api_v3.TModelBag; +import org.uddi.api_v3.TModelList; +import org.uddi.v3_service.DispositionReportFaultMessage; + +/**Co + * Used to factor out inquiry functionality as it is used in more than one spot. + * + * @author Jeff Faath + */ +public class InquiryHelper { + + private static Log logger = LogFactory.getLog(InquiryHelper.class); + + public static List findBinding(FindBinding body, FindQualifiers findQualifiers, EntityManager em) throws DispositionReportFaultMessage { + + List keysFound = new LinkedList(); + if (body.getServiceKey()!=null && body.getServiceKey().length() > 0) { + keysFound = findBindingsByServiceKey(em, body.getServiceKey(), keysFound); + } + + if (body.getTModelBag() == null) + body.setTModelBag(new TModelBag()); + // First perform the embedded FindTModel search which will augment the tModel bag with any resulting tModel keys. + doFindTModelEmbeddedSearch(em, body.getFindQualifiers(), body.getFindTModel(), body.getTModelBag()); + keysFound = FindBindingByTModelKeyQuery.select(em, findQualifiers, body.getTModelBag(), body.getServiceKey(), keysFound); + keysFound = FindBindingByCategoryQuery.select(em, findQualifiers, body.getCategoryBag(), body.getServiceKey(), keysFound); + keysFound = FindBindingByCategoryGroupQuery.select(em, findQualifiers, body.getCategoryBag(), body.getServiceKey(), keysFound); + + return keysFound; + } + + public static BindingDetail getBindingDetailFromKeys(FindBinding body, FindQualifiers findQualifiers, EntityManager em, List keysFound) throws DispositionReportFaultMessage { + return getBindingDetailFromKeys(body, findQualifiers, em, keysFound, null, null, null, null); + } + + public static BindingDetail getBindingDetailFromKeys(FindBinding body, FindQualifiers findQualifiers, EntityManager em, List keysFound, + Date modifiedAfter, Date modifiedBefore, Holder subscriptionStartIndex, Integer subscriptionMaxRows) + throws DispositionReportFaultMessage { + + BindingDetail result = new BindingDetail(); + ListDescription listDesc = new ListDescription(); + result.setListDescription(listDesc); + + // Sort and retrieve the final results with paging taken into account + List queryResults = FetchBindingTemplatesQuery.select(em, findQualifiers, keysFound, body.getMaxRows(), body.getListHead(), listDesc); + + // Set the currentIndex to 0 or the value of the subscriptionStartIndex + int currentIndex = 0; + if (subscriptionStartIndex != null && subscriptionStartIndex.value != null) + currentIndex = subscriptionStartIndex.value; + + int returnedRowCount = 0; + + while (currentIndex < queryResults.size()) { + Object item = queryResults.get(currentIndex); + + org.apache.juddi.model.BindingTemplate modelBindingTemplate = (org.apache.juddi.model.BindingTemplate)item; + org.uddi.api_v3.BindingTemplate apiBindingTemplate = new org.uddi.api_v3.BindingTemplate(); + + if (modifiedAfter != null && modifiedAfter.after(modelBindingTemplate.getModifiedIncludingChildren())) { + currentIndex++; + continue; + } + + if (modifiedBefore != null && modifiedBefore.before(modelBindingTemplate.getModifiedIncludingChildren())) { + currentIndex++; + continue; + } + + MappingModelToApi.mapBindingTemplate(modelBindingTemplate, apiBindingTemplate); + + result.getBindingTemplate().add(apiBindingTemplate); + + returnedRowCount++; + // If the returned rows equals the max allowed, we can end the loop (applies to subscription calls only) + if (subscriptionMaxRows != null) { + if (returnedRowCount == subscriptionMaxRows) + break; + } + + currentIndex++; + } + + // If the loop was broken prematurely (max row count hit) we set the subscriptionStartIndex to the next index to start with. + // Otherwise, set it to null so the subscription call won't trigger chunk token generation. + if (currentIndex < (queryResults.size() - 1)) { + if (subscriptionStartIndex != null) + subscriptionStartIndex.value = currentIndex + 1; + result.setTruncated(Boolean.TRUE); + } + else { + if (subscriptionStartIndex != null) + subscriptionStartIndex.value = null; + result.setTruncated(Boolean.FALSE); + } + result.getListDescription().setListHead(currentIndex); + result.getListDescription().setActualCount(result.getBindingTemplate().size()); + result.getListDescription().setIncludeCount(returnedRowCount); + return result; + } + + public static List findBusiness(FindBusiness body, FindQualifiers findQualifiers, EntityManager em) throws DispositionReportFaultMessage { + + List keysFound = null; + + // First perform the embedded FindTModel search which will augment the tModel bag with any resulting tModel keys. + if (body.getTModelBag() == null) + body.setTModelBag(new TModelBag()); + doFindTModelEmbeddedSearch(em, body.getFindQualifiers(), body.getFindTModel(), body.getTModelBag()); + + // The embedded find_relatedBusinesses search is performed first. This is done the same as the actual API call, except the resulting business keys are + // extracted and placed in the keysFound array to restrict future searches to only those keys. + if (body.getFindRelatedBusinesses() != null) { + FindRelatedBusinesses frb = body.getFindRelatedBusinesses(); + + org.uddi.api_v3.RelatedBusinessInfos relatedBusinessInfos = new org.uddi.api_v3.RelatedBusinessInfos(); + if (body.getFindRelatedBusinesses().getBusinessKey() != null ) { + getRelatedBusinesses(em, Direction.FROM_KEY, frb.getBusinessKey(), frb.getKeyedReference(), relatedBusinessInfos); + getRelatedBusinesses(em, Direction.TO_KEY, frb.getBusinessKey(), frb.getKeyedReference(), relatedBusinessInfos); + } + else if (body.getFindRelatedBusinesses().getFromKey() != null) + getRelatedBusinesses(em, Direction.FROM_KEY, frb.getFromKey(), frb.getKeyedReference(), relatedBusinessInfos); + else if (body.getFindRelatedBusinesses().getToKey() != null) + getRelatedBusinesses(em, Direction.TO_KEY, frb.getToKey(), frb.getKeyedReference(), relatedBusinessInfos); + + List relatedBusinessKeys = new ArrayList(0); + for (org.uddi.api_v3.RelatedBusinessInfo rbi : relatedBusinessInfos.getRelatedBusinessInfo()) + relatedBusinessKeys.add(rbi.getBusinessKey()); + + keysFound = relatedBusinessKeys; + } + + keysFound = FindBusinessByTModelKeyQuery.select(em, findQualifiers, body.getTModelBag(), keysFound); + keysFound = FindBusinessByIdentifierQuery.select(em, findQualifiers, body.getIdentifierBag(), keysFound); + keysFound = FindBusinessByDiscoveryURLQuery.select(em, findQualifiers, body.getDiscoveryURLs(), keysFound); + if (findQualifiers.isCombineCategoryBags()) { + keysFound = FindBusinessByCombinedCategoryQuery.select(em, findQualifiers, body.getCategoryBag(), keysFound); + } else { + keysFound = FindBusinessByCategoryQuery.select(em, findQualifiers, body.getCategoryBag(), keysFound); + } + + keysFound = FindBusinessByCategoryGroupQuery.select(em, findQualifiers, body.getCategoryBag(), keysFound); + keysFound = FindBusinessByNameQuery.select(em, findQualifiers, body.getName(), keysFound); + + // If there no keys in the bag then remove the empty TModelBag + if (body.getTModelBag().getTModelKey().size()==0) body.setTModelBag(null); + + return keysFound; + } + + public static BusinessList getBusinessListFromKeys(FindBusiness body, FindQualifiers findQualifiers, EntityManager em, List keysFound) throws DispositionReportFaultMessage { + return getBusinessListFromKeys(body, findQualifiers, em, keysFound, null, null, null, null); + } + + public static BusinessList getBusinessListFromKeys(FindBusiness body, FindQualifiers findQualifiers, EntityManager em, List keysFound, + Date modifiedAfter, Date modifiedBefore, Holder subscriptionStartIndex, Integer subscriptionMaxRows) + throws DispositionReportFaultMessage { + + BusinessList result = new BusinessList(); + ListDescription listDesc = new ListDescription(); + result.setListDescription(listDesc); + + // Sort and retrieve the final results taking paging into account + List queryResults = FetchBusinessEntitiesQuery.select(em, findQualifiers, keysFound, body.getMaxRows(), body.getListHead(), listDesc); + + boolean enabled = true; + try { + //AppConfig.reloadConfig(); + enabled= AppConfig.getConfiguration().getBoolean(Property.JUDDI_ENABLE_FIND_BUSINESS_TMODEL_BAG_FILTERING, true); + } catch (ConfigurationException ex) { + logger.error(ex); + } + if (enabled) { + logger.info("FindBusiness by tModelBag is enabled! Loaded from " + AppConfig.getConfigFileURL()); + List serviceResults = null; + for (int i = 0; i < queryResults.size(); i++) { + org.apache.juddi.model.BusinessEntity be = (org.apache.juddi.model.BusinessEntity) queryResults.get(i); + + List keysIn = new ArrayList(); + List services = be.getBusinessServices(); + for (int j = 0; j < services.size(); j++) { + keysIn.add(services.get(j).getEntityKey()); + } + + serviceResults = FindServiceByTModelKeyQuery.select(em, findQualifiers, body.getTModelBag(), null, keysIn); + if (serviceResults == null) { + be.setBusinessServices(null); + } else { + ListDescription ldesc = new ListDescription(); + result.setListDescription(listDesc); + List srvcs = FetchBusinessServicesQuery.select(em, findQualifiers, serviceResults, body.getMaxRows(), + body.getListHead(), ldesc); + be.setBusinessServices((List) srvcs); + } + } + } + + + if (queryResults != null && queryResults.size() > 0) + result.setBusinessInfos(new org.uddi.api_v3.BusinessInfos()); + + // Set the currentIndex to 0 or the value of the subscriptionStartIndex + int currentIndex = 0; + if (subscriptionStartIndex != null && subscriptionStartIndex.value != null) + currentIndex = subscriptionStartIndex.value; + + int returnedRowCount = 0; + + while (queryResults!=null && currentIndex < queryResults.size()) { + Object item = queryResults.get(currentIndex); + + org.apache.juddi.model.BusinessEntity modelBusinessEntity = (org.apache.juddi.model.BusinessEntity)item; + org.uddi.api_v3.BusinessInfo apiBusinessInfo = new org.uddi.api_v3.BusinessInfo(); + + if (modifiedAfter != null && modifiedAfter.after(modelBusinessEntity.getModifiedIncludingChildren())){ + currentIndex++; + continue; + } + + if (modifiedBefore != null && modifiedBefore.before(modelBusinessEntity.getModifiedIncludingChildren())) { + currentIndex++; + continue; + } + + MappingModelToApi.mapBusinessInfo(modelBusinessEntity, apiBusinessInfo); + + result.getBusinessInfos().getBusinessInfo().add(apiBusinessInfo); + + returnedRowCount++; + // If the returned rows equals the max allowed, we can end the loop (applies to subscription calls only) + if (subscriptionMaxRows != null) { + if (returnedRowCount == subscriptionMaxRows) + break; + } + + currentIndex++; + } + + // If the loop was broken prematurely (max row count hit) we set the subscriptionStartIndex to the next index to start with. + // Otherwise, set it to null so the subscription call won't trigger chunk token generation. + if (queryResults!=null && currentIndex < (queryResults.size() - 1)) { + if (subscriptionStartIndex != null) + subscriptionStartIndex.value = currentIndex + 1; + result.setTruncated(Boolean.TRUE); + } + else { + if (subscriptionStartIndex != null) + subscriptionStartIndex.value = null; + result.setTruncated(Boolean.FALSE); + } + return result; + } + + public static List findService(FindService body, FindQualifiers findQualifiers, EntityManager em) throws DispositionReportFaultMessage { + + List keysFound = null; + + // First perform the embedded FindTModel search which will augment the tModel bag with any resulting tModel keys. + if (body.getTModelBag() == null) + body.setTModelBag(new TModelBag()); + doFindTModelEmbeddedSearch(em, body.getFindQualifiers(), body.getFindTModel(), body.getTModelBag()); + + keysFound = FindServiceByTModelKeyQuery.select(em, findQualifiers, body.getTModelBag(), body.getBusinessKey(), keysFound); + if (findQualifiers.isCombineCategoryBags()) { + keysFound = FindServiceByCombinedCategoryQuery.select(em, findQualifiers, body.getCategoryBag(), body.getBusinessKey(), keysFound); + } else { + keysFound = FindServiceByCategoryQuery.select(em, findQualifiers, body.getCategoryBag(), body.getBusinessKey(), keysFound); + } + keysFound = FindServiceByCategoryGroupQuery.select(em, findQualifiers, body.getCategoryBag(), body.getBusinessKey(), keysFound); + + if (body.getFindTModel()==null && body.getCategoryBag()==null && + ( body.getTModelBag()==null || body.getTModelBag().getTModelKey().size() == 0) + && body.getName().size() == 0 && body.getBusinessKey() != null) { + //support searching for all services for a business + findQualifiers.setApproximateMatch(true); + body.getName().add(new Name("%", null)); + } + keysFound = FindServiceByNameQuery.select(em, findQualifiers, body.getName(), body.getBusinessKey(), keysFound); + + if (body.getTModelBag().getTModelKey().size()==0) body.setTModelBag(null); + return keysFound; + } + + public static ServiceList getServiceListFromKeys(FindService body, FindQualifiers findQualifiers, EntityManager em, List keysFound) throws DispositionReportFaultMessage { + return getServiceListFromKeys(body, findQualifiers, em, keysFound, null, null, null, null); + } + + public static ServiceList getServiceListFromKeys(FindService body, FindQualifiers findQualifiers, EntityManager em, List keysFound, + Date modifiedAfter, Date modifiedBefore, Holder subscriptionStartIndex, Integer subscriptionMaxRows) + throws DispositionReportFaultMessage { + ServiceList result = new ServiceList(); + ListDescription listDesc = new ListDescription(); + result.setListDescription(listDesc); + + // Sort and retrieve the final results taking paging into account + List queryResults = FetchBusinessServicesQuery.select(em, findQualifiers, keysFound, body.getMaxRows(), body.getListHead(), listDesc); + if (queryResults != null && queryResults.size() > 0) + result.setServiceInfos(new org.uddi.api_v3.ServiceInfos()); + + // Set the currentIndex to 0 or the value of the subscriptionStartIndex + int currentIndex = 0; + if (subscriptionStartIndex != null && subscriptionStartIndex.value != null) + currentIndex = subscriptionStartIndex.value; + + int returnedRowCount = 0; + if (logger.isDebugEnabled()) logger.debug("Period = " + modifiedAfter + " ---- " + modifiedBefore); + while (queryResults!=null && currentIndex < queryResults.size()) { + Object item = queryResults.get(currentIndex); + + org.apache.juddi.model.BusinessService modelBusinessService = (org.apache.juddi.model.BusinessService)item; + org.uddi.api_v3.ServiceInfo apiServiceInfo = new org.uddi.api_v3.ServiceInfo(); + + logger.debug(modelBusinessService.getEntityKey() + " is modified " + modelBusinessService.getModifiedIncludingChildren() + " " + modelBusinessService.getModifiedIncludingChildren().getTime() ); + if (modifiedAfter != null && modifiedAfter.after(modelBusinessService.getModifiedIncludingChildren())) { + currentIndex++; + continue; + } + + if (modifiedBefore != null && modifiedBefore.before(modelBusinessService.getModifiedIncludingChildren())) { + currentIndex++; + continue; + } + MappingModelToApi.mapServiceInfo(modelBusinessService, apiServiceInfo); + + result.getServiceInfos().getServiceInfo().add(apiServiceInfo); + + returnedRowCount++; + // If the returned rows equals the max allowed, we can end the loop (applies to subscription calls only) + if (subscriptionMaxRows != null) { + if (returnedRowCount == subscriptionMaxRows) + break; + } + + currentIndex++; + } + + // If the loop was broken prematurely (max row count hit) we set the subscriptionStartIndex to the next index to start with. + // Otherwise, set it to null so the subscription call won't trigger chunk token generation. + if (queryResults!=null && currentIndex < (queryResults.size() - 1)) { + if (subscriptionStartIndex != null) + subscriptionStartIndex.value = currentIndex + 1; + result.setTruncated(Boolean.TRUE); + } + else { + if (subscriptionStartIndex != null) + subscriptionStartIndex.value = null; + result.setTruncated(Boolean.FALSE); + } + + return result; + } + + public static List findTModel(FindTModel body, FindQualifiers findQualifiers, EntityManager em) throws DispositionReportFaultMessage { + List keysFound = null; + + keysFound = FindTModelByIdentifierQuery.select(em, findQualifiers, body.getIdentifierBag(), keysFound); + keysFound = FindTModelByCategoryQuery.select(em, findQualifiers, body.getCategoryBag(), keysFound); + keysFound = FindTModelByCategoryGroupQuery.select(em, findQualifiers, body.getCategoryBag(), keysFound); + keysFound = FindTModelByNameQuery.select(em, findQualifiers, body.getName(), keysFound); + + return keysFound; + } + + public static TModelList getTModelListFromKeys(FindTModel body, FindQualifiers findQualifiers, EntityManager em, List keysFound) throws DispositionReportFaultMessage { + return getTModelListFromKeys(body, findQualifiers, em, keysFound, null, null, null, null); + } + + public static TModelList getTModelListFromKeys(FindTModel body, FindQualifiers findQualifiers, EntityManager em, List keysFound, + Date modifiedAfter, Date modifiedBefore, Holder subscriptionStartIndex, Integer subscriptionMaxRows) + throws DispositionReportFaultMessage { + TModelList result = new TModelList(); + ListDescription listDesc = new ListDescription(); + result.setListDescription(listDesc); + + // Sort and retrieve the final results taking paging into account + List queryResults = FetchTModelsQuery.select(em, findQualifiers, keysFound, body.getMaxRows(), body.getListHead(), listDesc); + if (queryResults != null && queryResults.size() > 0) + result.setTModelInfos(new org.uddi.api_v3.TModelInfos()); + + // Set the currentIndex to 0 or the value of the subscriptionStartIndex + int currentIndex = 0; + if (subscriptionStartIndex != null && subscriptionStartIndex.value != null) + currentIndex = subscriptionStartIndex.value; + + int returnedRowCount = 0; + + while (queryResults!=null && currentIndex < queryResults.size()) { + Object item = queryResults.get(currentIndex); + + org.apache.juddi.model.Tmodel modelTModel = (org.apache.juddi.model.Tmodel)item; + org.uddi.api_v3.TModelInfo apiTModelInfo = new org.uddi.api_v3.TModelInfo(); + + if (modifiedAfter != null && modifiedAfter.after(modelTModel.getModifiedIncludingChildren())) { + currentIndex++; + continue; + } + + if (modifiedBefore != null && modifiedBefore.before(modelTModel.getModifiedIncludingChildren())) { + currentIndex++; + continue; + } + + MappingModelToApi.mapTModelInfo(modelTModel, apiTModelInfo); + + result.getTModelInfos().getTModelInfo().add(apiTModelInfo); + + returnedRowCount++; + // If the returned rows equals the max allowed, we can end the loop (applies to subscription calls only) + if (subscriptionMaxRows != null) { + if (returnedRowCount == subscriptionMaxRows) + break; + } + + currentIndex++; + } + + // If the loop was broken prematurely (max row count hit) we set the subscriptionStartIndex to the next index to start with. + // Otherwise, set it to null so the subscription call won't trigger chunk token generation. + if (queryResults!=null && currentIndex < (queryResults.size() - 1)) { + if (subscriptionStartIndex != null) + subscriptionStartIndex.value = currentIndex + 1; + result.setTruncated(Boolean.TRUE); + } + else { + if (subscriptionStartIndex != null) + subscriptionStartIndex.value = null; + result.setTruncated(Boolean.FALSE); + } + + return result; + } + + + /* + * Retrieves related businesses based on the focal business and the direction (fromKey or toKey). The focal business is retrieved and then the + * appropriate publisher assertion collection is examined for matches. The assertion must be "completed" and if a keyedReference is passed, it must + * match exactly. Successful assertion matches are mapped to a RelationBusinessInfo structure and added to the passed in RelationalBusinessInfos + * structure. + */ + public static void getRelatedBusinesses(EntityManager em, + Direction direction, + String focalKey, + org.uddi.api_v3.KeyedReference keyedRef, + org.uddi.api_v3.RelatedBusinessInfos relatedBusinessInfos) + throws DispositionReportFaultMessage { + getRelatedBusinesses(em, direction, focalKey, keyedRef, relatedBusinessInfos, null, null); + } + + public static void getRelatedBusinesses(EntityManager em, + Direction direction, + String focalKey, + org.uddi.api_v3.KeyedReference keyedRef, + org.uddi.api_v3.RelatedBusinessInfos relatedBusinessInfos, + Date modifiedAfter, + Date modifiedBefore) + throws DispositionReportFaultMessage { + if (relatedBusinessInfos == null) + relatedBusinessInfos = new org.uddi.api_v3.RelatedBusinessInfos(); + org.apache.juddi.model.BusinessEntity focalBusiness = null; + try { + focalBusiness = em.find(org.apache.juddi.model.BusinessEntity.class, focalKey); + } catch (ClassCastException e) {} + if (focalBusiness == null) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BusinessNotFound", focalKey)); + + List pubAssertList = null; + if (direction == Direction.FROM_KEY) + pubAssertList = focalBusiness.getPublisherAssertionsForFromKey(); + else + pubAssertList = focalBusiness.getPublisherAssertionsForToKey(); + + if (pubAssertList != null) { + for (org.apache.juddi.model.PublisherAssertion modelPublisherAssertion : pubAssertList) { + if ("true".equalsIgnoreCase(modelPublisherAssertion.getFromCheck()) && "true".equalsIgnoreCase(modelPublisherAssertion.getToCheck())) { + if (keyedRef != null) { + if(!keyedRef.getTModelKey().equals(modelPublisherAssertion.getTmodelKey()) || + !keyedRef.getKeyName().equals(modelPublisherAssertion.getKeyName()) || + !keyedRef.getKeyValue().equals(modelPublisherAssertion.getKeyValue())) { + continue; + } + } + + org.apache.juddi.model.BusinessEntity modelRelatedBusiness = null; + if (direction == Direction.FROM_KEY) + modelRelatedBusiness = em.find(org.apache.juddi.model.BusinessEntity.class, modelPublisherAssertion.getId().getToKey()); + else + modelRelatedBusiness = em.find(org.apache.juddi.model.BusinessEntity.class, modelPublisherAssertion.getId().getFromKey()); + + if (modifiedAfter != null && modifiedAfter.after(modelRelatedBusiness.getModifiedIncludingChildren())) + continue; + + if (modifiedBefore != null && modifiedBefore.before(modelRelatedBusiness.getModifiedIncludingChildren())) + continue; + + org.uddi.api_v3.RelatedBusinessInfo apiRelatedBusinessInfo = new org.uddi.api_v3.RelatedBusinessInfo(); + + MappingModelToApi.mapRelatedBusinessInfo(modelPublisherAssertion, modelRelatedBusiness, direction, apiRelatedBusinessInfo); + + relatedBusinessInfos.getRelatedBusinessInfo().add(apiRelatedBusinessInfo); + } + } + } + + } + + public static RelatedBusinessesList getRelatedBusinessesList(FindRelatedBusinesses body, EntityManager em) throws DispositionReportFaultMessage { + return getRelatedBusinessesList(body, em, null, null); + } + + public static RelatedBusinessesList getRelatedBusinessesList(FindRelatedBusinesses body, EntityManager em, Date modifiedAfter, Date modifiedBefore) throws DispositionReportFaultMessage { + RelatedBusinessesList result = new RelatedBusinessesList(); + result.setBusinessKey(body.getBusinessKey()); + ListDescription listDesc = new ListDescription(); + result.setListDescription(listDesc); + + // Either one of the businessKey, fromKey or toKey will be passed. This is considered the "focal" business to which related businesses must be + // found. Rather than use a query, it seems simpler to take advantage of the model's publisher assertion collections. + org.uddi.api_v3.RelatedBusinessInfos relatedBusinessInfos = new org.uddi.api_v3.RelatedBusinessInfos(); + if (body.getBusinessKey() != null ) { + InquiryHelper.getRelatedBusinesses(em, Direction.FROM_KEY, body.getBusinessKey(), body.getKeyedReference(), relatedBusinessInfos, modifiedAfter, modifiedBefore); + InquiryHelper.getRelatedBusinesses(em, Direction.TO_KEY, body.getBusinessKey(), body.getKeyedReference(), relatedBusinessInfos, modifiedAfter, modifiedBefore); + } + else if (body.getFromKey() != null) { + InquiryHelper.getRelatedBusinesses(em, Direction.FROM_KEY, body.getFromKey(), body.getKeyedReference(), relatedBusinessInfos, modifiedAfter, modifiedBefore); + result.setBusinessKey(body.getFromKey()); + } else if (body.getToKey() != null) { + InquiryHelper.getRelatedBusinesses(em, Direction.TO_KEY, body.getToKey(), body.getKeyedReference(), relatedBusinessInfos, modifiedAfter, modifiedBefore); + result.setBusinessKey(body.getToKey()); + } + if (relatedBusinessInfos.getRelatedBusinessInfo().size() > 0) { + // TODO: Do proper pagination! + listDesc.setActualCount(relatedBusinessInfos.getRelatedBusinessInfo().size()); + listDesc.setIncludeCount(relatedBusinessInfos.getRelatedBusinessInfo().size()); + listDesc.setListHead(1); + + result.setRelatedBusinessInfos(relatedBusinessInfos); + } + + return result; + } + + /** + * Performs the necessary queries for the find_tModel search and adds resulting tModel keys to the tModelBag provided. + */ + private static void doFindTModelEmbeddedSearch(EntityManager em, + org.uddi.api_v3.FindQualifiers fq, + FindTModel findTmodel, + TModelBag tmodelBag) + throws DispositionReportFaultMessage { + + + if (findTmodel != null && tmodelBag != null) { + org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); + findQualifiers.mapApiFindQualifiers(findTmodel.getFindQualifiers()); + + + List tmodelKeysFound = null; + tmodelKeysFound = FindTModelByIdentifierQuery.select(em, findQualifiers, findTmodel.getIdentifierBag(), tmodelKeysFound); + tmodelKeysFound = FindTModelByCategoryQuery.select(em, findQualifiers, findTmodel.getCategoryBag(), tmodelKeysFound); + tmodelKeysFound = FindTModelByCategoryGroupQuery.select(em, findQualifiers, findTmodel.getCategoryBag(), tmodelKeysFound); + tmodelKeysFound = FindTModelByNameQuery.select(em, findQualifiers, findTmodel.getName(), tmodelKeysFound); + + if (tmodelKeysFound != null && tmodelKeysFound.size() > 0) { + for (Object item : tmodelKeysFound) + tmodelBag.getTModelKey().add((String)item); + } + } + } + + private static List findBindingsByServiceKey(EntityManager em, String serviceKey, List keysFound) { + org.apache.juddi.model.BusinessService modelBusinessService=em.find(org.apache.juddi.model.BusinessService.class, serviceKey); + for (BindingTemplate bt : modelBusinessService.getBindingTemplates()){ + keysFound.add(bt.getEntityKey()); + } + return keysFound; + } + + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/api/impl/JUDDIApiImpl.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/JUDDIApiImpl.java similarity index 98% rename from juddi-core/src/main/java/org/apache/juddi/api/impl/JUDDIApiImpl.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/JUDDIApiImpl.java index 4477e2d4c..740443a2c 100644 --- a/juddi-core/src/main/java/org/apache/juddi/api/impl/JUDDIApiImpl.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/JUDDIApiImpl.java @@ -1,1683 +1,1683 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.io.StringWriter; -import java.math.BigInteger; -import java.rmi.RemoteException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.jws.WebService; -import javax.persistence.EntityManager; -import javax.persistence.EntityTransaction; -import javax.persistence.Query; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Marshaller; -import javax.xml.ws.Holder; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.ClassUtil; -import static org.apache.juddi.api.impl.JUDDIApiImpl.sub; -import org.apache.juddi.api.util.JUDDIQuery; -import org.apache.juddi.api.util.QueryStatus; -import org.apache.juddi.api_v3.AdminSaveBusinessWrapper; -import org.apache.juddi.api_v3.AdminSaveTModelWrapper; -import org.apache.juddi.api_v3.Clerk; -import org.apache.juddi.api_v3.ClerkDetail; -import org.apache.juddi.api_v3.ClerkList; -import org.apache.juddi.api_v3.ClientSubscriptionInfoDetail; -import org.apache.juddi.api_v3.DeleteClerk; -import org.apache.juddi.api_v3.DeleteClientSubscriptionInfo; -import org.apache.juddi.api_v3.DeleteNode; -import org.apache.juddi.api_v3.DeletePublisher; -import org.apache.juddi.api_v3.GetAllClientSubscriptionInfoDetail; -import org.apache.juddi.api_v3.GetAllPublisherDetail; -import org.apache.juddi.api_v3.GetClientSubscriptionInfoDetail; -import org.apache.juddi.api_v3.GetEntityHistoryMessageRequest; -import org.apache.juddi.api_v3.GetEntityHistoryMessageResponse; -import org.apache.juddi.api_v3.GetFailedReplicationChangeRecordsMessageRequest; -import org.apache.juddi.api_v3.GetFailedReplicationChangeRecordsMessageResponse; -import org.apache.juddi.api_v3.GetPublisherDetail; -import org.apache.juddi.api_v3.NodeDetail; -import org.apache.juddi.api_v3.NodeList; -import org.apache.juddi.api_v3.PublisherDetail; -import org.apache.juddi.api_v3.SaveClerk; -import org.apache.juddi.api_v3.SaveClientSubscriptionInfo; -import org.apache.juddi.api_v3.SaveNode; -import org.apache.juddi.api_v3.SavePublisher; -import org.apache.juddi.api_v3.SubscriptionWrapper; -import org.apache.juddi.api_v3.SyncSubscription; -import org.apache.juddi.api_v3.SyncSubscriptionDetail; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.PersistenceManager; -import org.apache.juddi.config.Property; -import org.apache.juddi.mapping.MappingApiToModel; -import org.apache.juddi.mapping.MappingModelToApi; -import org.apache.juddi.model.BusinessEntity; -import org.apache.juddi.model.ChangeRecord; -import org.apache.juddi.model.ClientSubscriptionInfo; -import org.apache.juddi.model.Node; -import org.apache.juddi.model.Publisher; -import org.apache.juddi.model.ReplicationConfiguration; -import org.apache.juddi.model.Tmodel; -import org.apache.juddi.model.UddiEntityPublisher; -import org.apache.juddi.replication.ReplicationNotifier; -import org.apache.juddi.subscription.NotificationList; -import org.apache.juddi.subscription.notify.TemporaryMailContainer; -import org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier; -import org.apache.juddi.v3.client.transport.Transport; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.FatalErrorException; -import org.apache.juddi.v3.error.InvalidKeyPassedException; -import org.apache.juddi.v3.error.InvalidValueException; -import org.apache.juddi.v3.error.UserMismatchException; -import org.apache.juddi.v3_service.JUDDIApiPortType; -import org.apache.juddi.validation.ValidateClerk; -import org.apache.juddi.validation.ValidateClientSubscriptionInfo; -import org.apache.juddi.validation.ValidateNode; -import org.apache.juddi.validation.ValidatePublish; -import org.apache.juddi.validation.ValidatePublisher; -import org.apache.juddi.validation.ValidateReplication; -import org.uddi.api_v3.AuthToken; -import org.uddi.api_v3.BusinessInfo; -import org.uddi.api_v3.BusinessInfos; -import org.uddi.api_v3.Contact; -import org.uddi.api_v3.DeleteTModel; -import org.uddi.api_v3.DispositionReport; -import org.uddi.api_v3.GetRegisteredInfo; -import org.uddi.api_v3.InfoSelection; -import org.uddi.api_v3.PersonName; -import org.uddi.api_v3.RegisteredInfo; -import org.uddi.api_v3.Result; -import org.uddi.api_v3.SaveBusiness; -import org.uddi.api_v3.SaveTModel; -import org.uddi.api_v3.TModelInfo; -import org.uddi.api_v3.TModelInfos; -import org.uddi.repl_v3.ChangeRecords; -import org.uddi.repl_v3.CommunicationGraph; -import org.uddi.repl_v3.Operator; -import org.uddi.repl_v3.OperatorStatusType; -import org.uddi.sub_v3.GetSubscriptionResults; -import org.uddi.sub_v3.Subscription; -import org.uddi.sub_v3.SubscriptionResultsList; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.v3_service.UDDISubscriptionPortType; - -/** - * Implements the jUDDI API service. These methods are outside of the UDDI spec - * and are specific to jUDDI. They are primarily used for administrative - * functions. - * - * @author Jeff Faath - * @author Kurt T Stam - * @author Alex O'Ree - */ -@WebService(serviceName = "JUDDIApiService", - endpointInterface = "org.apache.juddi.v3_service.JUDDIApiPortType", - targetNamespace = "urn:juddi-apache-org:v3_service" - //, wsdlLocation = "classpath:/juddi_api_v1.wsdl" -) -public class JUDDIApiImpl extends AuthenticatedService implements JUDDIApiPortType { - - private Log log = LogFactory.getLog(this.getClass()); - private UDDIServiceCounter serviceCounter = ServiceCounterLifecycleResource.getServiceCounter(this.getClass()); - - /** - * Saves publisher(s) to the persistence layer. This method is specific - * to jUDDI. Administrative privilege required. - * - * @param body - * @return PublisherDetail - * @throws DispositionReportFaultMessage - */ - public PublisherDetail savePublisher(SavePublisher body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); - - new ValidatePublish(publisher).validateSavePublisher(em, body); - - PublisherDetail result = new PublisherDetail(); - - List apiPublisherList = body.getPublisher(); - for (org.apache.juddi.api_v3.Publisher apiPublisher : apiPublisherList) { - - org.apache.juddi.model.Publisher modelPublisher = new org.apache.juddi.model.Publisher(); - - MappingApiToModel.mapPublisher(apiPublisher, modelPublisher); - - Object existingUddiEntity = em.find(modelPublisher.getClass(), modelPublisher.getAuthorizedName()); - if (existingUddiEntity != null) { - em.remove(existingUddiEntity); - } - - em.persist(modelPublisher); - - result.getPublisher().add(apiPublisher); - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.SAVE_PUBLISHER, - QueryStatus.SUCCESS, procTime); - return result; - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.SAVE_PUBLISHER, - QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - /** - * Deletes publisher(s) from the persistence layer. This method is - * specific to jUDDI. Administrative privilege required. Also removes - * all registered business entities of the user and marks all created - * tModels as "deleted" but not does not remove the tModel from - * persistence. All subscriptions are also destroyed - * - * @param body - * @throws DispositionReportFaultMessage - */ - @Override - public void deletePublisher(DeletePublisher body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); - - new ValidatePublish(publisher).validateDeletePublisher(em, body); - - List entityKeyList = body.getPublisherId(); - List deletedPubs = new ArrayList(); - for (String entityKey : entityKeyList) { - Publisher obj = em.find(org.apache.juddi.model.Publisher.class, entityKey); - deletedPubs.add(obj); - //get an authtoken for this publisher so that we can get its registeredInfo - UDDISecurityImpl security = new UDDISecurityImpl(); - AuthToken authToken = security.getAuthToken(entityKey); - - GetRegisteredInfo r = new GetRegisteredInfo(); - r.setAuthInfo(authToken.getAuthInfo()); - r.setInfoSelection(InfoSelection.ALL); - - log.info("removing all businesses owned by publisher " + entityKey + "."); - UDDIPublicationImpl publish = new UDDIPublicationImpl(); - RegisteredInfo registeredInfo = publish.getRegisteredInfo(r); - BusinessInfos businessInfos = registeredInfo.getBusinessInfos(); - if (businessInfos != null && businessInfos.getBusinessInfo() != null) { - Iterator iter = businessInfos.getBusinessInfo().iterator(); - while (iter.hasNext()) { - BusinessInfo businessInfo = iter.next(); - Object business = em.find(org.apache.juddi.model.BusinessEntity.class, businessInfo.getBusinessKey()); - em.remove(business); - } - } - - log.info("mark all tmodels for publisher " + entityKey + " as deleted."); - TModelInfos tmodelInfos = registeredInfo.getTModelInfos(); - if (tmodelInfos != null && tmodelInfos.getTModelInfo() != null) { - Iterator iter = tmodelInfos.getTModelInfo().iterator(); - while (iter.hasNext()) { - TModelInfo tModelInfo = iter.next(); - Tmodel tmodel = (Tmodel) em.find(org.apache.juddi.model.Tmodel.class, tModelInfo.getTModelKey()); - tmodel.setDeleted(true); - em.persist(tmodel); - } - } - log.info("remove all persisted AuthTokens for publisher " + entityKey + "."); - Query q1 = em.createQuery("DELETE FROM AuthToken auth WHERE auth.authorizedName = ?1"); - q1.setParameter(1, entityKey); - q1.executeUpdate(); - log.info("remove all subscriptions for publisher " + entityKey + "."); - q1 = em.createQuery("DELETE FROM Subscription s WHERE s.authorizedName = ?1"); - q1.setParameter(1, entityKey); - q1.executeUpdate(); - - log.info("removing publisher " + entityKey + "."); - //delete the publisher - em.remove(obj); - } - - tx.commit(); - for (Publisher p: deletedPubs){ - USERFRIENDLYSMTPNotifier.notifyAccountDeleted(new TemporaryMailContainer(null, p, (Publisher) publisher)); - } - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.DELETE_PUBLISHER, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.DELETE_PUBLISHER, - QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - /** - * Retrieves publisher(s) from the persistence layer. This method is - * specific to jUDDI. Administrative privilege required. - * - * @param body - * @return PublisherDetail - * @throws DispositionReportFaultMessage - */ - public PublisherDetail getPublisherDetail(GetPublisherDetail body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - new ValidatePublisher(null).validateGetPublisherDetail(body); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - this.getEntityPublisher(em, body.getAuthInfo()); - - PublisherDetail result = new PublisherDetail(); - - List publisherIdList = body.getPublisherId(); - for (String publisherId : publisherIdList) { - org.apache.juddi.model.Publisher modelPublisher = null; - try { - modelPublisher = em.find(org.apache.juddi.model.Publisher.class, publisherId); - } catch (ClassCastException e) { - } - if (modelPublisher == null) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.PublisherNotFound", publisherId)); - } - - org.apache.juddi.api_v3.Publisher apiPublisher = new org.apache.juddi.api_v3.Publisher(); - - MappingModelToApi.mapPublisher(modelPublisher, apiPublisher); - - result.getPublisher().add(apiPublisher); - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.GET_PUBLISHER_DETAIL, - QueryStatus.SUCCESS, procTime); - return result; - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.GET_PUBLISHER_DETAIL, - QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - } - - /** - * Retrieves all publisher from the persistence layer. This method is - * specific to jUDDI. Administrative privilege required. Use caution - * when calling, result set is not bound. If there are many publishers, - * it is possible to have a result set that is too large - * - * @param body - * @return PublisherDetail - * @throws DispositionReportFaultMessage - * @throws RemoteException - */ - @SuppressWarnings("unchecked") - public PublisherDetail getAllPublisherDetail(GetAllPublisherDetail body) - throws DispositionReportFaultMessage, RemoteException { - long startTime = System.currentTimeMillis(); - new ValidatePublisher(null).validateGetAllPublisherDetail(body); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - this.getEntityPublisher(em, body.getAuthInfo()); - - PublisherDetail result = new PublisherDetail(); - - Query query = em.createQuery("SELECT p from Publisher as p"); - List modelPublisherList = query.getResultList(); - - for (Publisher modelPublisher : modelPublisherList) { - - org.apache.juddi.api_v3.Publisher apiPublisher = new org.apache.juddi.api_v3.Publisher(); - - MappingModelToApi.mapPublisher(modelPublisher, apiPublisher); - - result.getPublisher().add(apiPublisher); - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.GET_ALL_PUBLISHER_DETAIL, - QueryStatus.SUCCESS, procTime); - return result; - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.GET_ALL_PUBLISHER_DETAIL, - QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - /** - * Completely deletes a tModel from the persistence layer. - * Administrative privilege required. All entities that reference this - * tModel will no longer be able to use the tModel if jUDDI Option - * Enforce referential Integrity is enabled.
- * Required permission, you must be am administrator - * {@link Property#JUDDI_ENFORCE_REFERENTIAL_INTEGRITY}. In addition, - * tModels that are owned by another node via replication cannot be - * deleted using this method and will throw an exception - * - * - * @param body - * @throws DispositionReportFaultMessage - */ - @Override - public void adminDeleteTModel(DeleteTModel body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); - - new ValidatePublish(publisher).validateAdminDeleteTModel(em, body); - - //TODO if referiental integrity is turned on, check to see if this is referenced anywhere and prevent the delete - List changes = new ArrayList(); - List entityKeyList = body.getTModelKey(); - for (String entityKey : entityKeyList) { - org.apache.juddi.model.Tmodel obj = em.find(org.apache.juddi.model.Tmodel.class, entityKey); - - if (obj == null) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.TModelNotFound", entityKey)); - } - if (!obj.getNodeId().equals(getNode())) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.TModelNodeOwner", entityKey + " this node " + getNode() + " owning node " + obj.getNodeId())); - } - em.remove(obj); - changes.add(UDDIPublicationImpl.getChangeRecord_deleteTModelDelete(entityKey, getNode(), df)); - - } - - tx.commit(); - for (ChangeRecord cr : changes) { - ReplicationNotifier.enqueue(cr); - } - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.ADMIN_DELETE_TMODEL, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.ADMIN_DELETE_TMODEL, - QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - /** - * Delete's a client's subscription information. This is typically used - * for server to server subscriptions Administrative privilege required. - * - * @param body - * @throws DispositionReportFaultMessage - * @throws RemoteException - */ - public void deleteClientSubscriptionInfo(DeleteClientSubscriptionInfo body) - throws DispositionReportFaultMessage, RemoteException { - long startTime = System.currentTimeMillis(); - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); - - new ValidateClientSubscriptionInfo(publisher).validateDeleteClientSubscriptionInfo(em, body); - - List entityKeyList = body.getSubscriptionKey(); - for (String entityKey : entityKeyList) { - Object obj = em.find(org.apache.juddi.model.ClientSubscriptionInfo.class, entityKey); - em.remove(obj); - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.DELETE_CLIENT_SUB, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.DELETE_CLIENT_SUB, - QueryStatus.FAILED, procTime); - throw drfm; - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - } - - /** - * Adds client subscription information. This effectively links a server - * to serverr subscription to clerk Administrative privilege required. - * - * @param body - * @return ClientSubscriptionInfoDetail - * @throws DispositionReportFaultMessage - * @throws RemoteException - */ - public ClientSubscriptionInfoDetail saveClientSubscriptionInfo(SaveClientSubscriptionInfo body) - throws DispositionReportFaultMessage, RemoteException { - long startTime = System.currentTimeMillis(); - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); - - new ValidateClientSubscriptionInfo(publisher).validateSaveClientSubscriptionInfo(em, body); - - ClientSubscriptionInfoDetail result = new ClientSubscriptionInfoDetail(); - - List apiClientSubscriptionInfoList = body.getClientSubscriptionInfo(); - for (org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo : apiClientSubscriptionInfoList) { - - org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo = new org.apache.juddi.model.ClientSubscriptionInfo(); - - MappingApiToModel.mapClientSubscriptionInfo(apiClientSubscriptionInfo, modelClientSubscriptionInfo); - - Object existingUddiEntity = em.find(modelClientSubscriptionInfo.getClass(), modelClientSubscriptionInfo.getSubscriptionKey()); - if (existingUddiEntity != null) { - em.remove(existingUddiEntity); - } - - em.persist(modelClientSubscriptionInfo); - - result.getClientSubscriptionInfo().add(apiClientSubscriptionInfo); - } - - tx.commit(); - - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.SAVE_CLIENT_SUB, - QueryStatus.SUCCESS, procTime); - return result; - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.SAVE_CLIENT_SUB, - QueryStatus.FAILED, procTime); - throw drfm; - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - /** - * Gets all client subscription information. This is used for server to - * server subscriptions Administrative privilege required. - * - * @param body - * @return ClientSubscriptionInfoDetail - * @throws DispositionReportFaultMessage - */ - @SuppressWarnings("unchecked") - public ClientSubscriptionInfoDetail getAllClientSubscriptionInfoDetail(GetAllClientSubscriptionInfoDetail body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - new ValidateClientSubscriptionInfo(null).validateGetAllClientSubscriptionDetail(body); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - this.getEntityPublisher(em, body.getAuthInfo()); - - ClientSubscriptionInfoDetail result = new ClientSubscriptionInfoDetail(); - - Query query = em.createQuery("SELECT cs from ClientSubscriptionInfo as cs"); - List modelClientSubscriptionInfoList = query.getResultList(); - - for (ClientSubscriptionInfo modelClientSubscriptionInfo : modelClientSubscriptionInfoList) { - - org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo = new org.apache.juddi.api_v3.ClientSubscriptionInfo(); - - MappingModelToApi.mapClientSubscriptionInfo(modelClientSubscriptionInfo, apiClientSubscriptionInfo, em); - - result.getClientSubscriptionInfo().add(apiClientSubscriptionInfo); - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.GET_ALL_CLIENT_SUB, - QueryStatus.SUCCESS, procTime); - return result; - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.GET_ALL_CLIENT_SUB, - QueryStatus.FAILED, procTime); - throw drfm; - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - } - - /** - * Retrieves clientSubscriptionKey(s) from the persistence layer. This - * method is specific to jUDDI. Used for server to server subscriptions - * Administrative privilege required. - * - * @param body - * @return ClientSubscriptionInfoDetail - * @throws DispositionReportFaultMessage - */ - public ClientSubscriptionInfoDetail getClientSubscriptionInfoDetail(GetClientSubscriptionInfoDetail body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - new ValidateClientSubscriptionInfo(null).validateGetClientSubscriptionInfoDetail(body); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - this.getEntityPublisher(em, body.getAuthInfo()); - - ClientSubscriptionInfoDetail result = new ClientSubscriptionInfoDetail(); - - List subscriptionKeyList = body.getClientSubscriptionKey(); - for (String subscriptionKey : subscriptionKeyList) { - - org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo = null; - - try { - modelClientSubscriptionInfo = em.find(org.apache.juddi.model.ClientSubscriptionInfo.class, subscriptionKey); - } catch (ClassCastException e) { - } - if (modelClientSubscriptionInfo == null) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.SubscripKeyNotFound", subscriptionKey)); - } - - org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo = new org.apache.juddi.api_v3.ClientSubscriptionInfo(); - - MappingModelToApi.mapClientSubscriptionInfo(modelClientSubscriptionInfo, apiClientSubscriptionInfo, em); - - result.getClientSubscriptionInfo().add(apiClientSubscriptionInfo); - } - - tx.commit(); - - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.GET_CLIENT_SUB, - QueryStatus.SUCCESS, procTime); - return result; - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.GET_CLIENT_SUB, - QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - } - - /** - * Saves clerk(s) to the persistence layer. This method is specific to - * jUDDI. This is used for server to server subscriptions and for future - * use with replication. Administrative privilege required. - * - * @param body - * @return ClerkDetail - * @throws DispositionReportFaultMessage - */ - @Override - public ClerkDetail saveClerk(SaveClerk body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); - - new ValidateClerk(publisher).validateSaveClerk(em, body); - - ClerkDetail result = new ClerkDetail(); - - List apiClerkList = body.getClerk();; - for (org.apache.juddi.api_v3.Clerk apiClerk : apiClerkList) { - - org.apache.juddi.model.Clerk modelClerk = new org.apache.juddi.model.Clerk(); - - MappingApiToModel.mapClerk(apiClerk, modelClerk); - org.apache.juddi.model.Node node2 = em.find(org.apache.juddi.model.Node.class, apiClerk.getNode().getName()); - if (node2 == null) { - //it doesn't exist yet - node2 = new Node(); - MappingApiToModel.mapNode(apiClerk.getNode(), node2); - em.persist(node2); - } - - modelClerk.setNode(node2.getName()); - Object existingUddiEntity = em.find(modelClerk.getClass(), modelClerk.getClerkName()); - if (existingUddiEntity != null) { - - em.merge(modelClerk); - } else { - em.persist(modelClerk); - } - - result.getClerk().add(apiClerk); - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.SAVE_CLERK, - QueryStatus.SUCCESS, procTime); - return result; - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.SAVE_CLERK, - QueryStatus.FAILED, procTime); - throw drfm; - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - /** - * Saves nodes(s) to the persistence layer. This method is specific to - * jUDDI. Administrative privilege required. This is used for server to - * server subscriptions and for future use with replication. - * Administrative privilege required. - * - * @param body - * @return NodeDetail - * @throws DispositionReportFaultMessage - */ - public NodeDetail saveNode(SaveNode body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); - - new ValidateNode(publisher).validateSaveNode(em, body); - - NodeDetail result = new NodeDetail(); - - List apiNodeList = body.getNode(); - for (org.apache.juddi.api_v3.Node apiNode : apiNodeList) { - - org.apache.juddi.model.Node modelNode = new org.apache.juddi.model.Node(); - - MappingApiToModel.mapNode(apiNode, modelNode); - - Object existingUddiEntity = em.find(modelNode.getClass(), modelNode.getName()); - if (existingUddiEntity != null) { - em.merge(modelNode); - } else { - em.persist(modelNode); - } - - result.getNode().add(apiNode); - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.SAVE_NODE, - QueryStatus.SUCCESS, procTime); - return result; - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.SAVE_NODE, - QueryStatus.FAILED, procTime); - throw drfm; - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - /** - * Instructs the registry to perform a synchronous subscription - * response. - * - * @param body - * @return SyncSubscriptionDetail - * @throws DispositionReportFaultMessage - * @throws RemoteException - */ - @SuppressWarnings("unchecked") - @Override - public SyncSubscriptionDetail invokeSyncSubscription( - SyncSubscription body) throws DispositionReportFaultMessage, - RemoteException { - long startTime = System.currentTimeMillis(); - //validate - SyncSubscriptionDetail syncSubscriptionDetail = new SyncSubscriptionDetail(); - - Map clientSubscriptionInfoMap - = new HashMap(); - //find the clerks to go with these subscriptions - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - this.getEntityPublisher(em, body.getAuthInfo()); - for (GetSubscriptionResults getSubscriptionResult : body.getGetSubscriptionResultsList()) { - String subscriptionKey = getSubscriptionResult.getSubscriptionKey(); - org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo = null; - - try { - modelClientSubscriptionInfo = em.find(org.apache.juddi.model.ClientSubscriptionInfo.class, subscriptionKey); - } catch (ClassCastException e) { - } - if (modelClientSubscriptionInfo == null) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.SubscripKeyNotFound", subscriptionKey)); - } - org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo = new org.apache.juddi.api_v3.ClientSubscriptionInfo(); - MappingModelToApi.mapClientSubscriptionInfo(modelClientSubscriptionInfo, apiClientSubscriptionInfo, em); - clientSubscriptionInfoMap.put(apiClientSubscriptionInfo.getSubscriptionKey(), apiClientSubscriptionInfo); - } - - tx.commit(); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.INVOKE_SYNCSUB, - QueryStatus.FAILED, procTime); - throw drfm; - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - for (GetSubscriptionResults getSubscriptionResult : body.getGetSubscriptionResultsList()) { - try { - String subscriptionKey = getSubscriptionResult.getSubscriptionKey(); - Clerk fromClerk = clientSubscriptionInfoMap.get(subscriptionKey).getFromClerk(); - Clerk toClerk = clientSubscriptionInfoMap.get(subscriptionKey).getToClerk(); - String clazz = fromClerk.getNode().getProxyTransport(); - Class transportClass = ClassUtil.forName(clazz, this.getClass()); - Transport transport = (Transport) transportClass.getConstructor(String.class - ).newInstance(fromClerk.getNode().getName()); - UDDISubscriptionPortType subscriptionService = transport.getUDDISubscriptionService(fromClerk.getNode().getSubscriptionUrl()); - SubscriptionResultsList list = subscriptionService.getSubscriptionResults(getSubscriptionResult); - - JAXBContext context = JAXBContext.newInstance(list.getClass()); - Marshaller marshaller = context.createMarshaller(); - StringWriter sw = new StringWriter(); - - marshaller.marshal(list, sw); - - log.info( - "Notification received by UDDISubscriptionListenerService : " + sw.toString()); - - NotificationList nl = NotificationList.getInstance(); - - nl.getNotifications() - .add(sw.toString()); - - //update the registry with the notification list. - XRegisterHelper.handle(fromClerk, toClerk, list); - - syncSubscriptionDetail.getSubscriptionResultsList() - .add(list); - } catch (Exception ce) { - log.error(ce.getMessage(), ce); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.SAVE_NODE, - QueryStatus.FAILED, procTime); - if (ce instanceof DispositionReportFaultMessage) { - throw (DispositionReportFaultMessage) ce; - } - if (ce instanceof RemoteException) { - DispositionReportFaultMessage x = new FatalErrorException(new ErrorMessage("errors.subscriptionnotifier.client", ce.getMessage())); - throw x; - } - } - } - //for now sending a clean object back - - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.INVOKE_SYNCSUB, - QueryStatus.SUCCESS, procTime); - return syncSubscriptionDetail; - } - - @Override - public NodeList getAllNodes(String authInfo) throws DispositionReportFaultMessage, RemoteException { - long startTime = System.currentTimeMillis(); - NodeList r = new NodeList(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); - - new ValidatePublish(publisher).validateGetAllNodes(); - - StringBuilder sql = new StringBuilder(); - sql.append("select distinct c from Node c "); - sql.toString(); - Query qry = em.createQuery(sql.toString()); - List resultList = qry.getResultList(); - for (int i = 0; i < resultList.size(); i++) { - org.apache.juddi.api_v3.Node api = new org.apache.juddi.api_v3.Node(); - MappingModelToApi.mapNode(resultList.get(i), api); - r.getNode().add(api); - - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.GET_ALL_NODES, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.GET_ALL_NODES, - QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - return r; - } - - @Override - public ClerkList getAllClerks(String authInfo) throws DispositionReportFaultMessage, RemoteException { - long startTime = System.currentTimeMillis(); - ClerkList ret = new ClerkList(); - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); - - new ValidatePublish(publisher).validateGetAllNodes(); - - StringBuilder sql = new StringBuilder(); - sql.append("select distinct c from Clerk c "); - sql.toString(); - Query qry = em.createQuery(sql.toString()); - List resultList = qry.getResultList(); - for (int i = 0; i < resultList.size(); i++) { - Clerk api = new Clerk(); - MappingModelToApi.mapClerk(resultList.get(i), api, em); - ret.getClerk().add(api); - - } - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.GET_ALL_CLERKS, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.GET_ALL_CLERKS, - QueryStatus.FAILED, procTime); - throw drfm; - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - return ret; - - } - - @Override - public void deleteNode(DeleteNode req) throws DispositionReportFaultMessage, RemoteException { - long startTime = System.currentTimeMillis(); - boolean found = false; - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - //TODO if the given node is in the replication config, prevent deletion - UddiEntityPublisher publisher = this.getEntityPublisher(em, req.getAuthInfo()); - new ValidatePublish(publisher).validateDeleteNode(em, req, getReplicationNodes(req.getAuthInfo())); - - org.apache.juddi.model.Node existingUddiEntity = em.find(org.apache.juddi.model.Node.class, req.getNodeID()); - if (existingUddiEntity != null) { - - //cascade delete all clerks tied to this node, confirm that it works - Query createQuery = em.createQuery("delete from Clerk c where c.node = :nodename"); - createQuery.setParameter("nodename", req.getNodeID()); - createQuery.executeUpdate(); - - em.remove(existingUddiEntity); - found = true; - } else { - throw new InvalidKeyPassedException(new ErrorMessage("errors.deleteNode.NotFound")); - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.DELETE_NODE, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.DELETE_NODE, - QueryStatus.FAILED, procTime); - throw drfm; - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - if (!found) { - - throw new InvalidKeyPassedException(new ErrorMessage("errors.deleteNode.NotFound", req.getNodeID())); - } - } - - @Override - public void deleteClerk(DeleteClerk req) throws DispositionReportFaultMessage, RemoteException { - long startTime = System.currentTimeMillis(); - boolean found = false; - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, req.getAuthInfo()); - - new ValidatePublish(publisher).validateDeleteClerk(em, req); - - org.apache.juddi.model.Clerk existingUddiEntity = em.find(org.apache.juddi.model.Clerk.class, req.getClerkID()); - if (existingUddiEntity - != null) { - em.remove(existingUddiEntity); - found = true; - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.DELETE_CLERK, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.DELETE_CLERK, - QueryStatus.FAILED, procTime); - throw drfm; - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - if (!found) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.deleteClerk.NotFound")); - } - - } - - /* - * enables tmodel owners to setup valid values for tmodel instance infos - * to use? - * - * @param authInfo - * @param values - * @return - * @throws DispositionReportFaultMessage - - @Override - public DispositionReport setAllValidValues(String authInfo, List values) throws DispositionReportFaultMessage, RemoteException { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - /* EntityManager em = PersistenceManager.getEntityManager(); - UddiEntityPublisher entityPublisher = getEntityPublisher(em, authInfo); - - new ValidateValueSetValidation(entityPublisher).validateSetAllValidValues(values); - - EntityTransaction tx = em.getTransaction(); - try { - - // is this tModel used anywhere?, if so, validate all instances against the new rule? - tx.begin(); - - //each tmodel/value set - for (int i = 0; i < values.size(); i++) { - //remove any existing references to the key - ValueSetValues find = em.find(ValueSetValues.class, values.get(i).getTModekKey()); - - if (find != null) { - find.setValidatorClass(values.get(i).getValidationClass()); - em.persist(find); - - } else { - org.apache.juddi.model.ValueSetValues vv = new ValueSetValues(); - vv.setTModelKey(values.get(i).getTModekKey()); - vv.setValidatorClass(values.get(i).getValidationClass()); - em.persist(vv); - } - } - - tx.commit(); - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - DispositionReport r = new DispositionReport(); - r.getResult().add(new Result()); - return r; - }*/ - @Override - public void adminDeleteSubscription(String authInfo, List subscriptionKey) throws DispositionReportFaultMessage, RemoteException { - - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher requestor = this.getEntityPublisher(em, authInfo); - if (!((Publisher) requestor).isAdmin()) { - throw new UserMismatchException(new ErrorMessage("errors.AdminReqd")); - } - //new ValidateSubscription(publisher).validateDeleteSubscription(em, body); - List notifications = new ArrayList(); - List subscriptionKeyList = subscriptionKey; - for (String key : subscriptionKeyList) { - if (key != null && key.length() > 0) { - org.apache.juddi.model.Subscription obj = em.find(org.apache.juddi.model.Subscription.class, key); - Publisher publisher = em.find(Publisher.class, obj.getAuthorizedName()); - notifications.add(new TemporaryMailContainer(obj, publisher, (Publisher) requestor)); - em.remove(obj); - } - } - - tx.commit(); - for (TemporaryMailContainer t : notifications) { - USERFRIENDLYSMTPNotifier.notifySubscriptionDeleted(t); - } - notifications.clear(); - notifications = null; - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.ADMIN_DELETE_SUB, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.ADMIN_DELETE_SUB, - QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - } - - @Override - public DispositionReport adminSaveBusiness(String authInfo, List values) throws DispositionReportFaultMessage, RemoteException { - long startTime = System.currentTimeMillis(); - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - UddiEntityPublisher requestor = this.getEntityPublisher(em, authInfo); - if (!((Publisher) requestor).isAdmin()) { - throw new UserMismatchException(new ErrorMessage("errors.AdminReqd")); - } - - for (int i = 0; i < values.size(); i++) { - //impersonate the user - AuthToken authToken = sec.getAuthToken(values.get(i).getPublisherID()); - - SaveBusiness stm = new SaveBusiness(); - - stm.setAuthInfo(authToken.getAuthInfo()); - stm.getBusinessEntity().addAll(values.get(i).getBusinessEntity()); - pub.saveBusiness(stm); - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.ADMIN_SAVE_BUSINESS, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.ADMIN_SAVE_BUSINESS, - QueryStatus.FAILED, procTime); - throw drfm; - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - DispositionReport r = new DispositionReport(); - return r; - - } - - @Override - public DispositionReport adminSaveTModel(String authInfo, List values) throws DispositionReportFaultMessage, RemoteException { - long startTime = System.currentTimeMillis(); - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - UddiEntityPublisher requestor = this.getEntityPublisher(em, authInfo); - if (!((Publisher) requestor).isAdmin()) { - throw new UserMismatchException(new ErrorMessage("errors.AdminReqd")); - } - - for (int i = 0; i < values.size(); i++) { - //impersonate the user - AuthToken authToken = sec.getAuthToken(values.get(i).getPublisherID()); - SaveTModel stm = new SaveTModel(); - stm.setAuthInfo(authToken.getAuthInfo()); - stm.getTModel().addAll(values.get(i).getTModel()); - pub.saveTModel(stm); - } - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.ADMIN_SAVE_TMODEL, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.ADMIN_SAVE_TMODEL, - QueryStatus.FAILED, procTime); - throw drfm; - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - DispositionReport r = new DispositionReport(); - return r; - } - - @Override - public List getAllClientSubscriptionInfo(String authInfo) throws DispositionReportFaultMessage, RemoteException { - long startTime = System.currentTimeMillis(); - - List r = new ArrayList(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); - if (!((Publisher) publisher).isAdmin()) { - throw new UserMismatchException(new ErrorMessage("errors.AdminReqd")); - } - - StringBuilder sql = new StringBuilder(); - sql.append("select distinct c from Subscription c "); - Query qry = em.createQuery(sql.toString()); - List resultList = qry.getResultList(); - for (int i = 0; i < resultList.size(); i++) { - Subscription sub = new Subscription(); - MappingModelToApi.mapSubscription(resultList.get(i), sub); - SubscriptionWrapper x = new SubscriptionWrapper(); - x.getSubscription().add(sub); - x.setPublisherIdOrUsername(resultList.get(i).getAuthorizedName()); - r.add(x); - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.GET_ALL_CLIENT_SUB, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.GET_ALL_CLIENT_SUB, - QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - return r; - } - - @Override - public synchronized DispositionReport setReplicationNodes(String authInfo, org.uddi.repl_v3.ReplicationConfiguration replicationConfiguration) throws DispositionReportFaultMessage, RemoteException { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - org.uddi.repl_v3.ReplicationConfiguration oldConfig = null; - UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); - if (!((Publisher) publisher).isAdmin()) { - throw new UserMismatchException(new ErrorMessage("errors.AdminReqd")); - } - new ValidateReplication(publisher).validateSetReplicationNodes(replicationConfiguration, em, getNode(), AppConfig.getConfiguration()); - - org.apache.juddi.model.ReplicationConfiguration model = null; - logger.info(publisher.getAuthorizedName() + " is setting the replication config from " + getRequestorsIPAddress());// + " " + sw.toString()); - try { - model = (ReplicationConfiguration) em.createQuery("select c FROM ReplicationConfiguration c order by c.serialNumber desc").getSingleResult(); - } catch (Exception ex) { - } - SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddkkmmZ"); - if (model == null) { - //this is a brand new configuration and we didn't have one before - model = new ReplicationConfiguration(); - MappingApiToModel.mapReplicationConfiguration(replicationConfiguration, model, em); - model.setSerialNumber(System.currentTimeMillis()); - model.setTimeOfConfigurationUpdate(sdf.format(new Date())); - em.persist(model); - //if (newReplicationNode(model)){ - //tell the replication notifier to start transfering with - //the first change record - //} - - } else { - //a config exists, remove it, add the new one - //spec doesn't appear to mention if recording a change history on the config is required - //assuming we'll keep it for now, might be useful later. - //em.remove(model); - oldConfig = new org.uddi.repl_v3.ReplicationConfiguration(); - MappingModelToApi.mapReplicationConfiguration(model, oldConfig); - - ReplicationConfiguration model2 = new ReplicationConfiguration(); - MappingApiToModel.mapReplicationConfiguration(replicationConfiguration, model2, em); - model2.setSerialNumber(System.currentTimeMillis()); - - model2.setTimeOfConfigurationUpdate(sdf.format(new Date())); - em.persist(model2); - - } - - tx.commit(); - UDDIReplicationImpl.notifyConfigurationChange(oldConfig, replicationConfiguration, this); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.SET_REPLICATION_NODES, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.SET_REPLICATION_NODES, - QueryStatus.FAILED, procTime); - throw drfm; - } catch (Exception ex) { - logger.error(ex, ex); - throw new FatalErrorException(new ErrorMessage("E_fatalError", ex.getMessage())); - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - DispositionReport d = new DispositionReport(); - Result res = new Result(); - - d.getResult().add(res); - return d; - } - - @Override - public synchronized org.uddi.repl_v3.ReplicationConfiguration getReplicationNodes(String authInfo) throws DispositionReportFaultMessage, RemoteException { - long startTime = System.currentTimeMillis(); - org.uddi.repl_v3.ReplicationConfiguration r = new org.uddi.repl_v3.ReplicationConfiguration(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); - if (!((Publisher) publisher).isAdmin()) { - throw new UserMismatchException(new ErrorMessage("errors.AdminReqd")); - } - - StringBuilder sql = new StringBuilder(); - sql.append("select c from ReplicationConfiguration c order by c.serialNumber desc"); - //sql.toString(); - Query qry = em.createQuery(sql.toString()); - qry.setMaxResults(1); - - org.apache.juddi.model.ReplicationConfiguration resultList = (org.apache.juddi.model.ReplicationConfiguration) qry.getSingleResult(); - MappingModelToApi.mapReplicationConfiguration(resultList, r); - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.GET_ALL_NODES, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.GET_ALL_NODES, - QueryStatus.FAILED, procTime); - throw drfm; - } catch (Exception ex) { - //possible that there is no config to return - logger.debug("Error caught, is there a replication config is avaiable? Returning a default config (no replication): ", ex); - - r.setCommunicationGraph(new CommunicationGraph()); - Operator op = new Operator(); - op.setOperatorNodeID(getNode()); - op.setSoapReplicationURL(baseUrlSSL + "replication/services/replication"); - - op.getContact().add(new Contact()); - op.getContact().get(0).getPersonName().add(new PersonName("Unknown", null)); - op.setOperatorStatus(OperatorStatusType.NORMAL); - - r.getOperator().add(op); - r.getCommunicationGraph().getNode().add(getNode()); - r.getCommunicationGraph().getControlledMessage().add("*"); - long procTime = System.currentTimeMillis() - startTime; - r.setSerialNumber(0); - SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddkkmmZ"); - r.setTimeOfConfigurationUpdate(sdf.format(new Date())); - r.setRegistryContact(new org.uddi.repl_v3.ReplicationConfiguration.RegistryContact()); - try { - // pull from root business - if (!tx.isActive()) { - tx = em.getTransaction(); - } - - BusinessEntity rootbiz = em.find(BusinessEntity.class, AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ROOT_BUSINESS)); - if (rootbiz != null) { - - for (int i = 0; i < rootbiz.getContacts().size(); i++) { - Contact c = new Contact(); - MappingModelToApi.mapContact(rootbiz.getContacts().get(i), c); - r.getRegistryContact().setContact(c); - break; - } - - } - tx.rollback(); - - } catch (Exception ex1) { - logger.warn("unexpected error", ex1); - } - if (r.getRegistryContact().getContact() == null) { - r.getRegistryContact().setContact(new Contact()); - r.getRegistryContact().getContact().getPersonName().add(new PersonName("Unknown", null)); - } - serviceCounter.update(JUDDIQuery.GET_REPLICATION_NODES, - QueryStatus.SUCCESS, procTime); - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - r.setMaximumTimeToGetChanges(BigInteger.ONE); - r.setMaximumTimeToSyncRegistry(BigInteger.ONE); - //StringWriter sw = new StringWriter(); - //JAXB.marshal(r, sw); - //logger.info("dumping returned replication config " + sw.toString()); - return r; - } - - static UDDISubscriptionImpl sub = new UDDISubscriptionImpl(); - static UDDISecurityImpl sec = new UDDISecurityImpl(); - static UDDIPublicationImpl pub = new UDDIPublicationImpl(); - - @Override - public void adminSaveSubscription(String authInfo, String publisherOrUsername, Holder> subscriptions) throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - UddiEntityPublisher requestor = this.getEntityPublisher(em, authInfo); - if (!((Publisher) requestor).isAdmin()) { - throw new UserMismatchException(new ErrorMessage("errors.AdminReqd")); - } - //impersonate the user - AuthToken authToken = sec.getAuthToken(publisherOrUsername); - sub.saveSubscription(authToken.getAuthInfo(), subscriptions); - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.ADMIN_SAVE_SUB, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.ADMIN_SAVE_SUB, - QueryStatus.FAILED, procTime); - throw drfm; - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - } - - /** - * {@inheritDoc } - * - * @param body - * @return item history or null if not found - * @throws DispositionReportFaultMessage - * @throws RemoteException - */ - @Override - public GetEntityHistoryMessageResponse getEntityHistory(GetEntityHistoryMessageRequest body) throws DispositionReportFaultMessage, RemoteException { - long startTime = System.currentTimeMillis(); - if (body == null) { - throw new InvalidValueException(new ErrorMessage("errors.NullInput")); - } - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - UddiEntityPublisher requestor = this.getEntityPublisher(em, body.getAuthInfo()); - if (!((Publisher) requestor).isAdmin()) { - throw new UserMismatchException(new ErrorMessage("errors.AdminReqd")); - } - if (body.getMaxRecords() <= 0) { - body.setMaxRecords(20); - } - if (body.getOffset() < 0) { - body.setOffset(0); - } - Query createQuery = em.createQuery("select m from ChangeRecord m where m.entityKey = :key order by m.id DESC"); - createQuery.setMaxResults((int) body.getMaxRecords()); - createQuery.setParameter("key", body.getEntityKey()); - createQuery.setFirstResult((int) body.getOffset()); - List resultList = createQuery.getResultList(); - GetEntityHistoryMessageResponse res = new GetEntityHistoryMessageResponse(); - res.setChangeRecords(new ChangeRecords()); - for (ChangeRecord cr : resultList) { - res.getChangeRecords().getChangeRecord().add(MappingModelToApi.mapChangeRecord(cr)); - } - - tx.rollback(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.ADMIN_GET_HISTORY, - QueryStatus.SUCCESS, procTime); - return res; - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.ADMIN_GET_HISTORY, - QueryStatus.FAILED, procTime); - throw drfm; - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - /** - * {@inheritDoc } - * - * @param body - * @return - * @throws DispositionReportFaultMessage - * @throws RemoteException - */ - @Override - public GetFailedReplicationChangeRecordsMessageResponse getFailedReplicationChangeRecords( - GetFailedReplicationChangeRecordsMessageRequest body) - throws DispositionReportFaultMessage, RemoteException { - //public GetFailedReplicationChangeRecordsMessageResponse getFailedReplicationChangeRecords(GetFailedReplicationChangeRecordsMessageRequest body) throws DispositionReportFaultMessage, RemoteException { - long startTime = System.currentTimeMillis(); - if (body == null) { - throw new InvalidValueException(new ErrorMessage("errors.NullInput")); - } - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - UddiEntityPublisher requestor = this.getEntityPublisher(em, body.getAuthInfo()); - if (!((Publisher) requestor).isAdmin()) { - throw new UserMismatchException(new ErrorMessage("errors.AdminReqd")); - } - if (body.getMaxRecords() <= 0) { - body.setMaxRecords(20); - } - if (body.getOffset() < 0) { - body.setOffset(0); - } - Query createQuery = em.createQuery("select m from ChangeRecord m where m.isAppliedLocally=false order by m.id DESC "); - createQuery.setMaxResults((int) body.getMaxRecords()); - createQuery.setFirstResult((int) body.getOffset()); - List resultList = createQuery.getResultList(); - GetFailedReplicationChangeRecordsMessageResponse res = new GetFailedReplicationChangeRecordsMessageResponse(); - res.setChangeRecords(new ChangeRecords()); - for (ChangeRecord cr : resultList) { - res.getChangeRecords().getChangeRecord().add(MappingModelToApi.mapChangeRecord(cr)); - } - - tx.rollback(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.ADMIN_GET_FAILED_CRS, - QueryStatus.SUCCESS, procTime); - return res; - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(JUDDIQuery.ADMIN_GET_FAILED_CRS, - QueryStatus.FAILED, procTime); - throw drfm; - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.io.StringWriter; +import java.math.BigInteger; +import java.rmi.RemoteException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.jws.WebService; +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.persistence.Query; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Marshaller; +import javax.xml.ws.Holder; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.ClassUtil; +import static org.apache.juddi.api.impl.JUDDIApiImpl.sub; +import org.apache.juddi.api.util.JUDDIQuery; +import org.apache.juddi.api.util.QueryStatus; +import org.apache.juddi.api_v3.AdminSaveBusinessWrapper; +import org.apache.juddi.api_v3.AdminSaveTModelWrapper; +import org.apache.juddi.api_v3.Clerk; +import org.apache.juddi.api_v3.ClerkDetail; +import org.apache.juddi.api_v3.ClerkList; +import org.apache.juddi.api_v3.ClientSubscriptionInfoDetail; +import org.apache.juddi.api_v3.DeleteClerk; +import org.apache.juddi.api_v3.DeleteClientSubscriptionInfo; +import org.apache.juddi.api_v3.DeleteNode; +import org.apache.juddi.api_v3.DeletePublisher; +import org.apache.juddi.api_v3.GetAllClientSubscriptionInfoDetail; +import org.apache.juddi.api_v3.GetAllPublisherDetail; +import org.apache.juddi.api_v3.GetClientSubscriptionInfoDetail; +import org.apache.juddi.api_v3.GetEntityHistoryMessageRequest; +import org.apache.juddi.api_v3.GetEntityHistoryMessageResponse; +import org.apache.juddi.api_v3.GetFailedReplicationChangeRecordsMessageRequest; +import org.apache.juddi.api_v3.GetFailedReplicationChangeRecordsMessageResponse; +import org.apache.juddi.api_v3.GetPublisherDetail; +import org.apache.juddi.api_v3.NodeDetail; +import org.apache.juddi.api_v3.NodeList; +import org.apache.juddi.api_v3.PublisherDetail; +import org.apache.juddi.api_v3.SaveClerk; +import org.apache.juddi.api_v3.SaveClientSubscriptionInfo; +import org.apache.juddi.api_v3.SaveNode; +import org.apache.juddi.api_v3.SavePublisher; +import org.apache.juddi.api_v3.SubscriptionWrapper; +import org.apache.juddi.api_v3.SyncSubscription; +import org.apache.juddi.api_v3.SyncSubscriptionDetail; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.PersistenceManager; +import org.apache.juddi.config.Property; +import org.apache.juddi.mapping.MappingApiToModel; +import org.apache.juddi.mapping.MappingModelToApi; +import org.apache.juddi.model.BusinessEntity; +import org.apache.juddi.model.ChangeRecord; +import org.apache.juddi.model.ClientSubscriptionInfo; +import org.apache.juddi.model.Node; +import org.apache.juddi.model.Publisher; +import org.apache.juddi.model.ReplicationConfiguration; +import org.apache.juddi.model.Tmodel; +import org.apache.juddi.model.UddiEntityPublisher; +import org.apache.juddi.replication.ReplicationNotifier; +import org.apache.juddi.subscription.NotificationList; +import org.apache.juddi.subscription.notify.TemporaryMailContainer; +import org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier; +import org.apache.juddi.v3.client.transport.Transport; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.FatalErrorException; +import org.apache.juddi.v3.error.InvalidKeyPassedException; +import org.apache.juddi.v3.error.InvalidValueException; +import org.apache.juddi.v3.error.UserMismatchException; +import org.apache.juddi.v3_service.JUDDIApiPortType; +import org.apache.juddi.validation.ValidateClerk; +import org.apache.juddi.validation.ValidateClientSubscriptionInfo; +import org.apache.juddi.validation.ValidateNode; +import org.apache.juddi.validation.ValidatePublish; +import org.apache.juddi.validation.ValidatePublisher; +import org.apache.juddi.validation.ValidateReplication; +import org.uddi.api_v3.AuthToken; +import org.uddi.api_v3.BusinessInfo; +import org.uddi.api_v3.BusinessInfos; +import org.uddi.api_v3.Contact; +import org.uddi.api_v3.DeleteTModel; +import org.uddi.api_v3.DispositionReport; +import org.uddi.api_v3.GetRegisteredInfo; +import org.uddi.api_v3.InfoSelection; +import org.uddi.api_v3.PersonName; +import org.uddi.api_v3.RegisteredInfo; +import org.uddi.api_v3.Result; +import org.uddi.api_v3.SaveBusiness; +import org.uddi.api_v3.SaveTModel; +import org.uddi.api_v3.TModelInfo; +import org.uddi.api_v3.TModelInfos; +import org.uddi.repl_v3.ChangeRecords; +import org.uddi.repl_v3.CommunicationGraph; +import org.uddi.repl_v3.Operator; +import org.uddi.repl_v3.OperatorStatusType; +import org.uddi.sub_v3.GetSubscriptionResults; +import org.uddi.sub_v3.Subscription; +import org.uddi.sub_v3.SubscriptionResultsList; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.v3_service.UDDISubscriptionPortType; + +/** + * Implements the jUDDI API service. These methods are outside of the UDDI spec + * and are specific to jUDDI. They are primarily used for administrative + * functions. + * + * @author Jeff Faath + * @author Kurt T Stam + * @author Alex O'Ree + */ +@WebService(serviceName = "JUDDIApiService", + endpointInterface = "org.apache.juddi.v3_service.JUDDIApiPortType", + targetNamespace = "urn:juddi-apache-org:v3_service" + //, wsdlLocation = "classpath:/juddi_api_v1.wsdl" +) +public class JUDDIApiImpl extends AuthenticatedService implements JUDDIApiPortType { + + private Log log = LogFactory.getLog(this.getClass()); + private UDDIServiceCounter serviceCounter = ServiceCounterLifecycleResource.getServiceCounter(this.getClass()); + + /** + * Saves publisher(s) to the persistence layer. This method is specific + * to jUDDI. Administrative privilege required. + * + * @param body + * @return PublisherDetail + * @throws DispositionReportFaultMessage + */ + public PublisherDetail savePublisher(SavePublisher body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); + + new ValidatePublish(publisher).validateSavePublisher(em, body); + + PublisherDetail result = new PublisherDetail(); + + List apiPublisherList = body.getPublisher(); + for (org.apache.juddi.api_v3.Publisher apiPublisher : apiPublisherList) { + + org.apache.juddi.model.Publisher modelPublisher = new org.apache.juddi.model.Publisher(); + + MappingApiToModel.mapPublisher(apiPublisher, modelPublisher); + + Object existingUddiEntity = em.find(modelPublisher.getClass(), modelPublisher.getAuthorizedName()); + if (existingUddiEntity != null) { + em.remove(existingUddiEntity); + } + + em.persist(modelPublisher); + + result.getPublisher().add(apiPublisher); + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.SAVE_PUBLISHER, + QueryStatus.SUCCESS, procTime); + return result; + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.SAVE_PUBLISHER, + QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + /** + * Deletes publisher(s) from the persistence layer. This method is + * specific to jUDDI. Administrative privilege required. Also removes + * all registered business entities of the user and marks all created + * tModels as "deleted" but not does not remove the tModel from + * persistence. All subscriptions are also destroyed + * + * @param body + * @throws DispositionReportFaultMessage + */ + @Override + public void deletePublisher(DeletePublisher body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); + + new ValidatePublish(publisher).validateDeletePublisher(em, body); + + List entityKeyList = body.getPublisherId(); + List deletedPubs = new ArrayList(); + for (String entityKey : entityKeyList) { + Publisher obj = em.find(org.apache.juddi.model.Publisher.class, entityKey); + deletedPubs.add(obj); + //get an authtoken for this publisher so that we can get its registeredInfo + UDDISecurityImpl security = new UDDISecurityImpl(); + AuthToken authToken = security.getAuthToken(entityKey); + + GetRegisteredInfo r = new GetRegisteredInfo(); + r.setAuthInfo(authToken.getAuthInfo()); + r.setInfoSelection(InfoSelection.ALL); + + log.info("removing all businesses owned by publisher " + entityKey + "."); + UDDIPublicationImpl publish = new UDDIPublicationImpl(); + RegisteredInfo registeredInfo = publish.getRegisteredInfo(r); + BusinessInfos businessInfos = registeredInfo.getBusinessInfos(); + if (businessInfos != null && businessInfos.getBusinessInfo() != null) { + Iterator iter = businessInfos.getBusinessInfo().iterator(); + while (iter.hasNext()) { + BusinessInfo businessInfo = iter.next(); + Object business = em.find(org.apache.juddi.model.BusinessEntity.class, businessInfo.getBusinessKey()); + em.remove(business); + } + } + + log.info("mark all tmodels for publisher " + entityKey + " as deleted."); + TModelInfos tmodelInfos = registeredInfo.getTModelInfos(); + if (tmodelInfos != null && tmodelInfos.getTModelInfo() != null) { + Iterator iter = tmodelInfos.getTModelInfo().iterator(); + while (iter.hasNext()) { + TModelInfo tModelInfo = iter.next(); + Tmodel tmodel = (Tmodel) em.find(org.apache.juddi.model.Tmodel.class, tModelInfo.getTModelKey()); + tmodel.setDeleted(true); + em.persist(tmodel); + } + } + log.info("remove all persisted AuthTokens for publisher " + entityKey + "."); + Query q1 = em.createQuery("DELETE FROM AuthToken auth WHERE auth.authorizedName = ?1"); + q1.setParameter(1, entityKey); + q1.executeUpdate(); + log.info("remove all subscriptions for publisher " + entityKey + "."); + q1 = em.createQuery("DELETE FROM Subscription s WHERE s.authorizedName = ?1"); + q1.setParameter(1, entityKey); + q1.executeUpdate(); + + log.info("removing publisher " + entityKey + "."); + //delete the publisher + em.remove(obj); + } + + tx.commit(); + for (Publisher p: deletedPubs){ + USERFRIENDLYSMTPNotifier.notifyAccountDeleted(new TemporaryMailContainer(null, p, (Publisher) publisher)); + } + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.DELETE_PUBLISHER, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.DELETE_PUBLISHER, + QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + /** + * Retrieves publisher(s) from the persistence layer. This method is + * specific to jUDDI. Administrative privilege required. + * + * @param body + * @return PublisherDetail + * @throws DispositionReportFaultMessage + */ + public PublisherDetail getPublisherDetail(GetPublisherDetail body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + new ValidatePublisher(null).validateGetPublisherDetail(body); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + this.getEntityPublisher(em, body.getAuthInfo()); + + PublisherDetail result = new PublisherDetail(); + + List publisherIdList = body.getPublisherId(); + for (String publisherId : publisherIdList) { + org.apache.juddi.model.Publisher modelPublisher = null; + try { + modelPublisher = em.find(org.apache.juddi.model.Publisher.class, publisherId); + } catch (ClassCastException e) { + } + if (modelPublisher == null) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.PublisherNotFound", publisherId)); + } + + org.apache.juddi.api_v3.Publisher apiPublisher = new org.apache.juddi.api_v3.Publisher(); + + MappingModelToApi.mapPublisher(modelPublisher, apiPublisher); + + result.getPublisher().add(apiPublisher); + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.GET_PUBLISHER_DETAIL, + QueryStatus.SUCCESS, procTime); + return result; + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.GET_PUBLISHER_DETAIL, + QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + } + + /** + * Retrieves all publisher from the persistence layer. This method is + * specific to jUDDI. Administrative privilege required. Use caution + * when calling, result set is not bound. If there are many publishers, + * it is possible to have a result set that is too large + * + * @param body + * @return PublisherDetail + * @throws DispositionReportFaultMessage + * @throws RemoteException + */ + @SuppressWarnings("unchecked") + public PublisherDetail getAllPublisherDetail(GetAllPublisherDetail body) + throws DispositionReportFaultMessage, RemoteException { + long startTime = System.currentTimeMillis(); + new ValidatePublisher(null).validateGetAllPublisherDetail(body); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + this.getEntityPublisher(em, body.getAuthInfo()); + + PublisherDetail result = new PublisherDetail(); + + Query query = em.createQuery("SELECT p from Publisher as p"); + List modelPublisherList = query.getResultList(); + + for (Publisher modelPublisher : modelPublisherList) { + + org.apache.juddi.api_v3.Publisher apiPublisher = new org.apache.juddi.api_v3.Publisher(); + + MappingModelToApi.mapPublisher(modelPublisher, apiPublisher); + + result.getPublisher().add(apiPublisher); + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.GET_ALL_PUBLISHER_DETAIL, + QueryStatus.SUCCESS, procTime); + return result; + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.GET_ALL_PUBLISHER_DETAIL, + QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + /** + * Completely deletes a tModel from the persistence layer. + * Administrative privilege required. All entities that reference this + * tModel will no longer be able to use the tModel if jUDDI Option + * Enforce referential Integrity is enabled.
+ * Required permission, you must be am administrator + * {@link Property#JUDDI_ENFORCE_REFERENTIAL_INTEGRITY}. In addition, + * tModels that are owned by another node via replication cannot be + * deleted using this method and will throw an exception + * + * + * @param body + * @throws DispositionReportFaultMessage + */ + @Override + public void adminDeleteTModel(DeleteTModel body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); + + new ValidatePublish(publisher).validateAdminDeleteTModel(em, body); + + //TODO if referiental integrity is turned on, check to see if this is referenced anywhere and prevent the delete + List changes = new ArrayList(); + List entityKeyList = body.getTModelKey(); + for (String entityKey : entityKeyList) { + org.apache.juddi.model.Tmodel obj = em.find(org.apache.juddi.model.Tmodel.class, entityKey); + + if (obj == null) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.TModelNotFound", entityKey)); + } + if (!obj.getNodeId().equals(getNode())) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.TModelNodeOwner", entityKey + " this node " + getNode() + " owning node " + obj.getNodeId())); + } + em.remove(obj); + changes.add(UDDIPublicationImpl.getChangeRecord_deleteTModelDelete(entityKey, getNode(), df)); + + } + + tx.commit(); + for (ChangeRecord cr : changes) { + ReplicationNotifier.enqueue(cr); + } + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.ADMIN_DELETE_TMODEL, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.ADMIN_DELETE_TMODEL, + QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + /** + * Delete's a client's subscription information. This is typically used + * for server to server subscriptions Administrative privilege required. + * + * @param body + * @throws DispositionReportFaultMessage + * @throws RemoteException + */ + public void deleteClientSubscriptionInfo(DeleteClientSubscriptionInfo body) + throws DispositionReportFaultMessage, RemoteException { + long startTime = System.currentTimeMillis(); + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); + + new ValidateClientSubscriptionInfo(publisher).validateDeleteClientSubscriptionInfo(em, body); + + List entityKeyList = body.getSubscriptionKey(); + for (String entityKey : entityKeyList) { + Object obj = em.find(org.apache.juddi.model.ClientSubscriptionInfo.class, entityKey); + em.remove(obj); + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.DELETE_CLIENT_SUB, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.DELETE_CLIENT_SUB, + QueryStatus.FAILED, procTime); + throw drfm; + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + } + + /** + * Adds client subscription information. This effectively links a server + * to serverr subscription to clerk Administrative privilege required. + * + * @param body + * @return ClientSubscriptionInfoDetail + * @throws DispositionReportFaultMessage + * @throws RemoteException + */ + public ClientSubscriptionInfoDetail saveClientSubscriptionInfo(SaveClientSubscriptionInfo body) + throws DispositionReportFaultMessage, RemoteException { + long startTime = System.currentTimeMillis(); + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); + + new ValidateClientSubscriptionInfo(publisher).validateSaveClientSubscriptionInfo(em, body); + + ClientSubscriptionInfoDetail result = new ClientSubscriptionInfoDetail(); + + List apiClientSubscriptionInfoList = body.getClientSubscriptionInfo(); + for (org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo : apiClientSubscriptionInfoList) { + + org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo = new org.apache.juddi.model.ClientSubscriptionInfo(); + + MappingApiToModel.mapClientSubscriptionInfo(apiClientSubscriptionInfo, modelClientSubscriptionInfo); + + Object existingUddiEntity = em.find(modelClientSubscriptionInfo.getClass(), modelClientSubscriptionInfo.getSubscriptionKey()); + if (existingUddiEntity != null) { + em.remove(existingUddiEntity); + } + + em.persist(modelClientSubscriptionInfo); + + result.getClientSubscriptionInfo().add(apiClientSubscriptionInfo); + } + + tx.commit(); + + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.SAVE_CLIENT_SUB, + QueryStatus.SUCCESS, procTime); + return result; + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.SAVE_CLIENT_SUB, + QueryStatus.FAILED, procTime); + throw drfm; + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + /** + * Gets all client subscription information. This is used for server to + * server subscriptions Administrative privilege required. + * + * @param body + * @return ClientSubscriptionInfoDetail + * @throws DispositionReportFaultMessage + */ + @SuppressWarnings("unchecked") + public ClientSubscriptionInfoDetail getAllClientSubscriptionInfoDetail(GetAllClientSubscriptionInfoDetail body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + new ValidateClientSubscriptionInfo(null).validateGetAllClientSubscriptionDetail(body); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + this.getEntityPublisher(em, body.getAuthInfo()); + + ClientSubscriptionInfoDetail result = new ClientSubscriptionInfoDetail(); + + Query query = em.createQuery("SELECT cs from ClientSubscriptionInfo as cs"); + List modelClientSubscriptionInfoList = query.getResultList(); + + for (ClientSubscriptionInfo modelClientSubscriptionInfo : modelClientSubscriptionInfoList) { + + org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo = new org.apache.juddi.api_v3.ClientSubscriptionInfo(); + + MappingModelToApi.mapClientSubscriptionInfo(modelClientSubscriptionInfo, apiClientSubscriptionInfo, em); + + result.getClientSubscriptionInfo().add(apiClientSubscriptionInfo); + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.GET_ALL_CLIENT_SUB, + QueryStatus.SUCCESS, procTime); + return result; + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.GET_ALL_CLIENT_SUB, + QueryStatus.FAILED, procTime); + throw drfm; + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + } + + /** + * Retrieves clientSubscriptionKey(s) from the persistence layer. This + * method is specific to jUDDI. Used for server to server subscriptions + * Administrative privilege required. + * + * @param body + * @return ClientSubscriptionInfoDetail + * @throws DispositionReportFaultMessage + */ + public ClientSubscriptionInfoDetail getClientSubscriptionInfoDetail(GetClientSubscriptionInfoDetail body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + new ValidateClientSubscriptionInfo(null).validateGetClientSubscriptionInfoDetail(body); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + this.getEntityPublisher(em, body.getAuthInfo()); + + ClientSubscriptionInfoDetail result = new ClientSubscriptionInfoDetail(); + + List subscriptionKeyList = body.getClientSubscriptionKey(); + for (String subscriptionKey : subscriptionKeyList) { + + org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo = null; + + try { + modelClientSubscriptionInfo = em.find(org.apache.juddi.model.ClientSubscriptionInfo.class, subscriptionKey); + } catch (ClassCastException e) { + } + if (modelClientSubscriptionInfo == null) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.SubscripKeyNotFound", subscriptionKey)); + } + + org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo = new org.apache.juddi.api_v3.ClientSubscriptionInfo(); + + MappingModelToApi.mapClientSubscriptionInfo(modelClientSubscriptionInfo, apiClientSubscriptionInfo, em); + + result.getClientSubscriptionInfo().add(apiClientSubscriptionInfo); + } + + tx.commit(); + + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.GET_CLIENT_SUB, + QueryStatus.SUCCESS, procTime); + return result; + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.GET_CLIENT_SUB, + QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + } + + /** + * Saves clerk(s) to the persistence layer. This method is specific to + * jUDDI. This is used for server to server subscriptions and for future + * use with replication. Administrative privilege required. + * + * @param body + * @return ClerkDetail + * @throws DispositionReportFaultMessage + */ + @Override + public ClerkDetail saveClerk(SaveClerk body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); + + new ValidateClerk(publisher).validateSaveClerk(em, body); + + ClerkDetail result = new ClerkDetail(); + + List apiClerkList = body.getClerk();; + for (org.apache.juddi.api_v3.Clerk apiClerk : apiClerkList) { + + org.apache.juddi.model.Clerk modelClerk = new org.apache.juddi.model.Clerk(); + + MappingApiToModel.mapClerk(apiClerk, modelClerk); + org.apache.juddi.model.Node node2 = em.find(org.apache.juddi.model.Node.class, apiClerk.getNode().getName()); + if (node2 == null) { + //it doesn't exist yet + node2 = new Node(); + MappingApiToModel.mapNode(apiClerk.getNode(), node2); + em.persist(node2); + } + + modelClerk.setNode(node2.getName()); + Object existingUddiEntity = em.find(modelClerk.getClass(), modelClerk.getClerkName()); + if (existingUddiEntity != null) { + + em.merge(modelClerk); + } else { + em.persist(modelClerk); + } + + result.getClerk().add(apiClerk); + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.SAVE_CLERK, + QueryStatus.SUCCESS, procTime); + return result; + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.SAVE_CLERK, + QueryStatus.FAILED, procTime); + throw drfm; + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + /** + * Saves nodes(s) to the persistence layer. This method is specific to + * jUDDI. Administrative privilege required. This is used for server to + * server subscriptions and for future use with replication. + * Administrative privilege required. + * + * @param body + * @return NodeDetail + * @throws DispositionReportFaultMessage + */ + public NodeDetail saveNode(SaveNode body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); + + new ValidateNode(publisher).validateSaveNode(em, body); + + NodeDetail result = new NodeDetail(); + + List apiNodeList = body.getNode(); + for (org.apache.juddi.api_v3.Node apiNode : apiNodeList) { + + org.apache.juddi.model.Node modelNode = new org.apache.juddi.model.Node(); + + MappingApiToModel.mapNode(apiNode, modelNode); + + Object existingUddiEntity = em.find(modelNode.getClass(), modelNode.getName()); + if (existingUddiEntity != null) { + em.merge(modelNode); + } else { + em.persist(modelNode); + } + + result.getNode().add(apiNode); + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.SAVE_NODE, + QueryStatus.SUCCESS, procTime); + return result; + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.SAVE_NODE, + QueryStatus.FAILED, procTime); + throw drfm; + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + /** + * Instructs the registry to perform a synchronous subscription + * response. + * + * @param body + * @return SyncSubscriptionDetail + * @throws DispositionReportFaultMessage + * @throws RemoteException + */ + @SuppressWarnings("unchecked") + @Override + public SyncSubscriptionDetail invokeSyncSubscription( + SyncSubscription body) throws DispositionReportFaultMessage, + RemoteException { + long startTime = System.currentTimeMillis(); + //validate + SyncSubscriptionDetail syncSubscriptionDetail = new SyncSubscriptionDetail(); + + Map clientSubscriptionInfoMap + = new HashMap(); + //find the clerks to go with these subscriptions + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + this.getEntityPublisher(em, body.getAuthInfo()); + for (GetSubscriptionResults getSubscriptionResult : body.getGetSubscriptionResultsList()) { + String subscriptionKey = getSubscriptionResult.getSubscriptionKey(); + org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo = null; + + try { + modelClientSubscriptionInfo = em.find(org.apache.juddi.model.ClientSubscriptionInfo.class, subscriptionKey); + } catch (ClassCastException e) { + } + if (modelClientSubscriptionInfo == null) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.SubscripKeyNotFound", subscriptionKey)); + } + org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo = new org.apache.juddi.api_v3.ClientSubscriptionInfo(); + MappingModelToApi.mapClientSubscriptionInfo(modelClientSubscriptionInfo, apiClientSubscriptionInfo, em); + clientSubscriptionInfoMap.put(apiClientSubscriptionInfo.getSubscriptionKey(), apiClientSubscriptionInfo); + } + + tx.commit(); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.INVOKE_SYNCSUB, + QueryStatus.FAILED, procTime); + throw drfm; + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + for (GetSubscriptionResults getSubscriptionResult : body.getGetSubscriptionResultsList()) { + try { + String subscriptionKey = getSubscriptionResult.getSubscriptionKey(); + Clerk fromClerk = clientSubscriptionInfoMap.get(subscriptionKey).getFromClerk(); + Clerk toClerk = clientSubscriptionInfoMap.get(subscriptionKey).getToClerk(); + String clazz = fromClerk.getNode().getProxyTransport(); + Class transportClass = ClassUtil.forName(clazz, this.getClass()); + Transport transport = (Transport) transportClass.getConstructor(String.class + ).newInstance(fromClerk.getNode().getName()); + UDDISubscriptionPortType subscriptionService = transport.getUDDISubscriptionService(fromClerk.getNode().getSubscriptionUrl()); + SubscriptionResultsList list = subscriptionService.getSubscriptionResults(getSubscriptionResult); + + JAXBContext context = JAXBContext.newInstance(list.getClass()); + Marshaller marshaller = context.createMarshaller(); + StringWriter sw = new StringWriter(); + + marshaller.marshal(list, sw); + + log.info( + "Notification received by UDDISubscriptionListenerService : " + sw.toString()); + + NotificationList nl = NotificationList.getInstance(); + + nl.getNotifications() + .add(sw.toString()); + + //update the registry with the notification list. + XRegisterHelper.handle(fromClerk, toClerk, list); + + syncSubscriptionDetail.getSubscriptionResultsList() + .add(list); + } catch (Exception ce) { + log.error(ce.getMessage(), ce); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.SAVE_NODE, + QueryStatus.FAILED, procTime); + if (ce instanceof DispositionReportFaultMessage) { + throw (DispositionReportFaultMessage) ce; + } + if (ce instanceof RemoteException) { + DispositionReportFaultMessage x = new FatalErrorException(new ErrorMessage("errors.subscriptionnotifier.client", ce.getMessage())); + throw x; + } + } + } + //for now sending a clean object back + + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.INVOKE_SYNCSUB, + QueryStatus.SUCCESS, procTime); + return syncSubscriptionDetail; + } + + @Override + public NodeList getAllNodes(String authInfo) throws DispositionReportFaultMessage, RemoteException { + long startTime = System.currentTimeMillis(); + NodeList r = new NodeList(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); + + new ValidatePublish(publisher).validateGetAllNodes(); + + StringBuilder sql = new StringBuilder(); + sql.append("select distinct c from Node c "); + sql.toString(); + Query qry = em.createQuery(sql.toString()); + List resultList = qry.getResultList(); + for (int i = 0; i < resultList.size(); i++) { + org.apache.juddi.api_v3.Node api = new org.apache.juddi.api_v3.Node(); + MappingModelToApi.mapNode(resultList.get(i), api); + r.getNode().add(api); + + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.GET_ALL_NODES, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.GET_ALL_NODES, + QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + return r; + } + + @Override + public ClerkList getAllClerks(String authInfo) throws DispositionReportFaultMessage, RemoteException { + long startTime = System.currentTimeMillis(); + ClerkList ret = new ClerkList(); + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); + + new ValidatePublish(publisher).validateGetAllNodes(); + + StringBuilder sql = new StringBuilder(); + sql.append("select distinct c from Clerk c "); + sql.toString(); + Query qry = em.createQuery(sql.toString()); + List resultList = qry.getResultList(); + for (int i = 0; i < resultList.size(); i++) { + Clerk api = new Clerk(); + MappingModelToApi.mapClerk(resultList.get(i), api, em); + ret.getClerk().add(api); + + } + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.GET_ALL_CLERKS, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.GET_ALL_CLERKS, + QueryStatus.FAILED, procTime); + throw drfm; + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + return ret; + + } + + @Override + public void deleteNode(DeleteNode req) throws DispositionReportFaultMessage, RemoteException { + long startTime = System.currentTimeMillis(); + boolean found = false; + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + //TODO if the given node is in the replication config, prevent deletion + UddiEntityPublisher publisher = this.getEntityPublisher(em, req.getAuthInfo()); + new ValidatePublish(publisher).validateDeleteNode(em, req, getReplicationNodes(req.getAuthInfo())); + + org.apache.juddi.model.Node existingUddiEntity = em.find(org.apache.juddi.model.Node.class, req.getNodeID()); + if (existingUddiEntity != null) { + + //cascade delete all clerks tied to this node, confirm that it works + Query createQuery = em.createQuery("delete from Clerk c where c.node = :nodename"); + createQuery.setParameter("nodename", req.getNodeID()); + createQuery.executeUpdate(); + + em.remove(existingUddiEntity); + found = true; + } else { + throw new InvalidKeyPassedException(new ErrorMessage("errors.deleteNode.NotFound")); + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.DELETE_NODE, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.DELETE_NODE, + QueryStatus.FAILED, procTime); + throw drfm; + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + if (!found) { + + throw new InvalidKeyPassedException(new ErrorMessage("errors.deleteNode.NotFound", req.getNodeID())); + } + } + + @Override + public void deleteClerk(DeleteClerk req) throws DispositionReportFaultMessage, RemoteException { + long startTime = System.currentTimeMillis(); + boolean found = false; + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, req.getAuthInfo()); + + new ValidatePublish(publisher).validateDeleteClerk(em, req); + + org.apache.juddi.model.Clerk existingUddiEntity = em.find(org.apache.juddi.model.Clerk.class, req.getClerkID()); + if (existingUddiEntity + != null) { + em.remove(existingUddiEntity); + found = true; + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.DELETE_CLERK, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.DELETE_CLERK, + QueryStatus.FAILED, procTime); + throw drfm; + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + if (!found) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.deleteClerk.NotFound")); + } + + } + + /* + * enables tmodel owners to setup valid values for tmodel instance infos + * to use? + * + * @param authInfo + * @param values + * @return + * @throws DispositionReportFaultMessage + + @Override + public DispositionReport setAllValidValues(String authInfo, List values) throws DispositionReportFaultMessage, RemoteException { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + /* EntityManager em = PersistenceManager.getEntityManager(); + UddiEntityPublisher entityPublisher = getEntityPublisher(em, authInfo); + + new ValidateValueSetValidation(entityPublisher).validateSetAllValidValues(values); + + EntityTransaction tx = em.getTransaction(); + try { + + // is this tModel used anywhere?, if so, validate all instances against the new rule? + tx.begin(); + + //each tmodel/value set + for (int i = 0; i < values.size(); i++) { + //remove any existing references to the key + ValueSetValues find = em.find(ValueSetValues.class, values.get(i).getTModekKey()); + + if (find != null) { + find.setValidatorClass(values.get(i).getValidationClass()); + em.persist(find); + + } else { + org.apache.juddi.model.ValueSetValues vv = new ValueSetValues(); + vv.setTModelKey(values.get(i).getTModekKey()); + vv.setValidatorClass(values.get(i).getValidationClass()); + em.persist(vv); + } + } + + tx.commit(); + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + DispositionReport r = new DispositionReport(); + r.getResult().add(new Result()); + return r; + }*/ + @Override + public void adminDeleteSubscription(String authInfo, List subscriptionKey) throws DispositionReportFaultMessage, RemoteException { + + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher requestor = this.getEntityPublisher(em, authInfo); + if (!((Publisher) requestor).isAdmin()) { + throw new UserMismatchException(new ErrorMessage("errors.AdminReqd")); + } + //new ValidateSubscription(publisher).validateDeleteSubscription(em, body); + List notifications = new ArrayList(); + List subscriptionKeyList = subscriptionKey; + for (String key : subscriptionKeyList) { + if (key != null && key.length() > 0) { + org.apache.juddi.model.Subscription obj = em.find(org.apache.juddi.model.Subscription.class, key); + Publisher publisher = em.find(Publisher.class, obj.getAuthorizedName()); + notifications.add(new TemporaryMailContainer(obj, publisher, (Publisher) requestor)); + em.remove(obj); + } + } + + tx.commit(); + for (TemporaryMailContainer t : notifications) { + USERFRIENDLYSMTPNotifier.notifySubscriptionDeleted(t); + } + notifications.clear(); + notifications = null; + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.ADMIN_DELETE_SUB, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.ADMIN_DELETE_SUB, + QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + } + + @Override + public DispositionReport adminSaveBusiness(String authInfo, List values) throws DispositionReportFaultMessage, RemoteException { + long startTime = System.currentTimeMillis(); + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + UddiEntityPublisher requestor = this.getEntityPublisher(em, authInfo); + if (!((Publisher) requestor).isAdmin()) { + throw new UserMismatchException(new ErrorMessage("errors.AdminReqd")); + } + + for (int i = 0; i < values.size(); i++) { + //impersonate the user + AuthToken authToken = sec.getAuthToken(values.get(i).getPublisherID()); + + SaveBusiness stm = new SaveBusiness(); + + stm.setAuthInfo(authToken.getAuthInfo()); + stm.getBusinessEntity().addAll(values.get(i).getBusinessEntity()); + pub.saveBusiness(stm); + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.ADMIN_SAVE_BUSINESS, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.ADMIN_SAVE_BUSINESS, + QueryStatus.FAILED, procTime); + throw drfm; + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + DispositionReport r = new DispositionReport(); + return r; + + } + + @Override + public DispositionReport adminSaveTModel(String authInfo, List values) throws DispositionReportFaultMessage, RemoteException { + long startTime = System.currentTimeMillis(); + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + UddiEntityPublisher requestor = this.getEntityPublisher(em, authInfo); + if (!((Publisher) requestor).isAdmin()) { + throw new UserMismatchException(new ErrorMessage("errors.AdminReqd")); + } + + for (int i = 0; i < values.size(); i++) { + //impersonate the user + AuthToken authToken = sec.getAuthToken(values.get(i).getPublisherID()); + SaveTModel stm = new SaveTModel(); + stm.setAuthInfo(authToken.getAuthInfo()); + stm.getTModel().addAll(values.get(i).getTModel()); + pub.saveTModel(stm); + } + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.ADMIN_SAVE_TMODEL, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.ADMIN_SAVE_TMODEL, + QueryStatus.FAILED, procTime); + throw drfm; + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + DispositionReport r = new DispositionReport(); + return r; + } + + @Override + public List getAllClientSubscriptionInfo(String authInfo) throws DispositionReportFaultMessage, RemoteException { + long startTime = System.currentTimeMillis(); + + List r = new ArrayList(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); + if (!((Publisher) publisher).isAdmin()) { + throw new UserMismatchException(new ErrorMessage("errors.AdminReqd")); + } + + StringBuilder sql = new StringBuilder(); + sql.append("select distinct c from Subscription c "); + Query qry = em.createQuery(sql.toString()); + List resultList = qry.getResultList(); + for (int i = 0; i < resultList.size(); i++) { + Subscription sub = new Subscription(); + MappingModelToApi.mapSubscription(resultList.get(i), sub); + SubscriptionWrapper x = new SubscriptionWrapper(); + x.getSubscription().add(sub); + x.setPublisherIdOrUsername(resultList.get(i).getAuthorizedName()); + r.add(x); + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.GET_ALL_CLIENT_SUB, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.GET_ALL_CLIENT_SUB, + QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + return r; + } + + @Override + public synchronized DispositionReport setReplicationNodes(String authInfo, org.uddi.repl_v3.ReplicationConfiguration replicationConfiguration) throws DispositionReportFaultMessage, RemoteException { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + org.uddi.repl_v3.ReplicationConfiguration oldConfig = null; + UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); + if (!((Publisher) publisher).isAdmin()) { + throw new UserMismatchException(new ErrorMessage("errors.AdminReqd")); + } + new ValidateReplication(publisher).validateSetReplicationNodes(replicationConfiguration, em, getNode(), AppConfig.getConfiguration()); + + org.apache.juddi.model.ReplicationConfiguration model = null; + logger.info(publisher.getAuthorizedName() + " is setting the replication config from " + getRequestorsIPAddress());// + " " + sw.toString()); + try { + model = (ReplicationConfiguration) em.createQuery("select c FROM ReplicationConfiguration c order by c.serialNumber desc").getSingleResult(); + } catch (Exception ex) { + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddkkmmZ"); + if (model == null) { + //this is a brand new configuration and we didn't have one before + model = new ReplicationConfiguration(); + MappingApiToModel.mapReplicationConfiguration(replicationConfiguration, model, em); + model.setSerialNumber(System.currentTimeMillis()); + model.setTimeOfConfigurationUpdate(sdf.format(new Date())); + em.persist(model); + //if (newReplicationNode(model)){ + //tell the replication notifier to start transfering with + //the first change record + //} + + } else { + //a config exists, remove it, add the new one + //spec doesn't appear to mention if recording a change history on the config is required + //assuming we'll keep it for now, might be useful later. + //em.remove(model); + oldConfig = new org.uddi.repl_v3.ReplicationConfiguration(); + MappingModelToApi.mapReplicationConfiguration(model, oldConfig); + + ReplicationConfiguration model2 = new ReplicationConfiguration(); + MappingApiToModel.mapReplicationConfiguration(replicationConfiguration, model2, em); + model2.setSerialNumber(System.currentTimeMillis()); + + model2.setTimeOfConfigurationUpdate(sdf.format(new Date())); + em.persist(model2); + + } + + tx.commit(); + UDDIReplicationImpl.notifyConfigurationChange(oldConfig, replicationConfiguration, this); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.SET_REPLICATION_NODES, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.SET_REPLICATION_NODES, + QueryStatus.FAILED, procTime); + throw drfm; + } catch (Exception ex) { + logger.error(ex, ex); + throw new FatalErrorException(new ErrorMessage("E_fatalError", ex.getMessage())); + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + DispositionReport d = new DispositionReport(); + Result res = new Result(); + + d.getResult().add(res); + return d; + } + + @Override + public synchronized org.uddi.repl_v3.ReplicationConfiguration getReplicationNodes(String authInfo) throws DispositionReportFaultMessage, RemoteException { + long startTime = System.currentTimeMillis(); + org.uddi.repl_v3.ReplicationConfiguration r = new org.uddi.repl_v3.ReplicationConfiguration(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); + if (!((Publisher) publisher).isAdmin()) { + throw new UserMismatchException(new ErrorMessage("errors.AdminReqd")); + } + + StringBuilder sql = new StringBuilder(); + sql.append("select c from ReplicationConfiguration c order by c.serialNumber desc"); + //sql.toString(); + Query qry = em.createQuery(sql.toString()); + qry.setMaxResults(1); + + org.apache.juddi.model.ReplicationConfiguration resultList = (org.apache.juddi.model.ReplicationConfiguration) qry.getSingleResult(); + MappingModelToApi.mapReplicationConfiguration(resultList, r); + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.GET_ALL_NODES, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.GET_ALL_NODES, + QueryStatus.FAILED, procTime); + throw drfm; + } catch (Exception ex) { + //possible that there is no config to return + logger.debug("Error caught, is there a replication config is avaiable? Returning a default config (no replication): ", ex); + + r.setCommunicationGraph(new CommunicationGraph()); + Operator op = new Operator(); + op.setOperatorNodeID(getNode()); + op.setSoapReplicationURL(baseUrlSSL + "replication/services/replication"); + + op.getContact().add(new Contact()); + op.getContact().get(0).getPersonName().add(new PersonName("Unknown", null)); + op.setOperatorStatus(OperatorStatusType.NORMAL); + + r.getOperator().add(op); + r.getCommunicationGraph().getNode().add(getNode()); + r.getCommunicationGraph().getControlledMessage().add("*"); + long procTime = System.currentTimeMillis() - startTime; + r.setSerialNumber(0); + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddkkmmZ"); + r.setTimeOfConfigurationUpdate(sdf.format(new Date())); + r.setRegistryContact(new org.uddi.repl_v3.ReplicationConfiguration.RegistryContact()); + try { + // pull from root business + if (!tx.isActive()) { + tx = em.getTransaction(); + } + + BusinessEntity rootbiz = em.find(BusinessEntity.class, AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ROOT_BUSINESS)); + if (rootbiz != null) { + + for (int i = 0; i < rootbiz.getContacts().size(); i++) { + Contact c = new Contact(); + MappingModelToApi.mapContact(rootbiz.getContacts().get(i), c); + r.getRegistryContact().setContact(c); + break; + } + + } + tx.rollback(); + + } catch (Exception ex1) { + logger.warn("unexpected error", ex1); + } + if (r.getRegistryContact().getContact() == null) { + r.getRegistryContact().setContact(new Contact()); + r.getRegistryContact().getContact().getPersonName().add(new PersonName("Unknown", null)); + } + serviceCounter.update(JUDDIQuery.GET_REPLICATION_NODES, + QueryStatus.SUCCESS, procTime); + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + r.setMaximumTimeToGetChanges(BigInteger.ONE); + r.setMaximumTimeToSyncRegistry(BigInteger.ONE); + //StringWriter sw = new StringWriter(); + //JAXB.marshal(r, sw); + //logger.info("dumping returned replication config " + sw.toString()); + return r; + } + + static UDDISubscriptionImpl sub = new UDDISubscriptionImpl(); + static UDDISecurityImpl sec = new UDDISecurityImpl(); + static UDDIPublicationImpl pub = new UDDIPublicationImpl(); + + @Override + public void adminSaveSubscription(String authInfo, String publisherOrUsername, Holder> subscriptions) throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + UddiEntityPublisher requestor = this.getEntityPublisher(em, authInfo); + if (!((Publisher) requestor).isAdmin()) { + throw new UserMismatchException(new ErrorMessage("errors.AdminReqd")); + } + //impersonate the user + AuthToken authToken = sec.getAuthToken(publisherOrUsername); + sub.saveSubscription(authToken.getAuthInfo(), subscriptions); + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.ADMIN_SAVE_SUB, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.ADMIN_SAVE_SUB, + QueryStatus.FAILED, procTime); + throw drfm; + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + } + + /** + * {@inheritDoc } + * + * @param body + * @return item history or null if not found + * @throws DispositionReportFaultMessage + * @throws RemoteException + */ + @Override + public GetEntityHistoryMessageResponse getEntityHistory(GetEntityHistoryMessageRequest body) throws DispositionReportFaultMessage, RemoteException { + long startTime = System.currentTimeMillis(); + if (body == null) { + throw new InvalidValueException(new ErrorMessage("errors.NullInput")); + } + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + UddiEntityPublisher requestor = this.getEntityPublisher(em, body.getAuthInfo()); + if (!((Publisher) requestor).isAdmin()) { + throw new UserMismatchException(new ErrorMessage("errors.AdminReqd")); + } + if (body.getMaxRecords() <= 0) { + body.setMaxRecords(20); + } + if (body.getOffset() < 0) { + body.setOffset(0); + } + Query createQuery = em.createQuery("select m from ChangeRecord m where m.entityKey = :key order by m.id DESC"); + createQuery.setMaxResults((int) body.getMaxRecords()); + createQuery.setParameter("key", body.getEntityKey()); + createQuery.setFirstResult((int) body.getOffset()); + List resultList = createQuery.getResultList(); + GetEntityHistoryMessageResponse res = new GetEntityHistoryMessageResponse(); + res.setChangeRecords(new ChangeRecords()); + for (ChangeRecord cr : resultList) { + res.getChangeRecords().getChangeRecord().add(MappingModelToApi.mapChangeRecord(cr)); + } + + tx.rollback(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.ADMIN_GET_HISTORY, + QueryStatus.SUCCESS, procTime); + return res; + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.ADMIN_GET_HISTORY, + QueryStatus.FAILED, procTime); + throw drfm; + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + /** + * {@inheritDoc } + * + * @param body + * @return + * @throws DispositionReportFaultMessage + * @throws RemoteException + */ + @Override + public GetFailedReplicationChangeRecordsMessageResponse getFailedReplicationChangeRecords( + GetFailedReplicationChangeRecordsMessageRequest body) + throws DispositionReportFaultMessage, RemoteException { + //public GetFailedReplicationChangeRecordsMessageResponse getFailedReplicationChangeRecords(GetFailedReplicationChangeRecordsMessageRequest body) throws DispositionReportFaultMessage, RemoteException { + long startTime = System.currentTimeMillis(); + if (body == null) { + throw new InvalidValueException(new ErrorMessage("errors.NullInput")); + } + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + UddiEntityPublisher requestor = this.getEntityPublisher(em, body.getAuthInfo()); + if (!((Publisher) requestor).isAdmin()) { + throw new UserMismatchException(new ErrorMessage("errors.AdminReqd")); + } + if (body.getMaxRecords() <= 0) { + body.setMaxRecords(20); + } + if (body.getOffset() < 0) { + body.setOffset(0); + } + Query createQuery = em.createQuery("select m from ChangeRecord m where m.isAppliedLocally=false order by m.id DESC "); + createQuery.setMaxResults((int) body.getMaxRecords()); + createQuery.setFirstResult((int) body.getOffset()); + List resultList = createQuery.getResultList(); + GetFailedReplicationChangeRecordsMessageResponse res = new GetFailedReplicationChangeRecordsMessageResponse(); + res.setChangeRecords(new ChangeRecords()); + for (ChangeRecord cr : resultList) { + res.getChangeRecords().getChangeRecord().add(MappingModelToApi.mapChangeRecord(cr)); + } + + tx.rollback(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.ADMIN_GET_FAILED_CRS, + QueryStatus.SUCCESS, procTime); + return res; + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(JUDDIQuery.ADMIN_GET_FAILED_CRS, + QueryStatus.FAILED, procTime); + throw drfm; + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/api/impl/PublicationHelper.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/PublicationHelper.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/api/impl/PublicationHelper.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/PublicationHelper.java index d2589abb0..aa0c48c22 100644 --- a/juddi-core/src/main/java/org/apache/juddi/api/impl/PublicationHelper.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/PublicationHelper.java @@ -1,62 +1,62 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import javax.persistence.EntityManager; - -import org.apache.juddi.mapping.MappingModelToApi; -import org.apache.juddi.model.UddiEntityPublisher; -import org.apache.juddi.query.FindBusinessByPublisherQuery; -import org.apache.juddi.query.FindPublisherAssertionByBusinessQuery; -import org.uddi.api_v3.AssertionStatusItem; -import org.uddi.api_v3.CompletionStatus; -import org.uddi.v3_service.DispositionReportFaultMessage; - -/** - * Used to factor out publication functionality that is used in more than one spot. - * - * @author Jeff Faath - */ -public class PublicationHelper { - - public static List getAssertionStatusItemList(UddiEntityPublisher publisher, CompletionStatus completionStatus, EntityManager em) throws DispositionReportFaultMessage { - List result = new ArrayList(0); - - List businessKeysFound = null; - businessKeysFound = FindBusinessByPublisherQuery.select(em, null, publisher, businessKeysFound); - - List pubAssertionList = FindPublisherAssertionByBusinessQuery.select(em, businessKeysFound, completionStatus); - if (pubAssertionList==null) - return result; - for(org.apache.juddi.model.PublisherAssertion modelPubAssertion : pubAssertionList) { - org.uddi.api_v3.AssertionStatusItem apiAssertionStatusItem = new org.uddi.api_v3.AssertionStatusItem(); - - MappingModelToApi.mapAssertionStatusItem(modelPubAssertion, apiAssertionStatusItem, businessKeysFound); - - result.add(apiAssertionStatusItem); - } - - return result; - } - - - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import javax.persistence.EntityManager; + +import org.apache.juddi.mapping.MappingModelToApi; +import org.apache.juddi.model.UddiEntityPublisher; +import org.apache.juddi.query.FindBusinessByPublisherQuery; +import org.apache.juddi.query.FindPublisherAssertionByBusinessQuery; +import org.uddi.api_v3.AssertionStatusItem; +import org.uddi.api_v3.CompletionStatus; +import org.uddi.v3_service.DispositionReportFaultMessage; + +/** + * Used to factor out publication functionality that is used in more than one spot. + * + * @author Jeff Faath + */ +public class PublicationHelper { + + public static List getAssertionStatusItemList(UddiEntityPublisher publisher, CompletionStatus completionStatus, EntityManager em) throws DispositionReportFaultMessage { + List result = new ArrayList(0); + + List businessKeysFound = null; + businessKeysFound = FindBusinessByPublisherQuery.select(em, null, publisher, businessKeysFound); + + List pubAssertionList = FindPublisherAssertionByBusinessQuery.select(em, businessKeysFound, completionStatus); + if (pubAssertionList==null) + return result; + for(org.apache.juddi.model.PublisherAssertion modelPubAssertion : pubAssertionList) { + org.uddi.api_v3.AssertionStatusItem apiAssertionStatusItem = new org.uddi.api_v3.AssertionStatusItem(); + + MappingModelToApi.mapAssertionStatusItem(modelPubAssertion, apiAssertionStatusItem, businessKeysFound); + + result.add(apiAssertionStatusItem); + } + + return result; + } + + + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/api/impl/ServiceCounterLifecycleResource.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/ServiceCounterLifecycleResource.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/api/impl/ServiceCounterLifecycleResource.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/ServiceCounterLifecycleResource.java diff --git a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDICustodyTransferImpl.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDICustodyTransferImpl.java similarity index 98% rename from juddi-core/src/main/java/org/apache/juddi/api/impl/UDDICustodyTransferImpl.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDICustodyTransferImpl.java index bec809a07..b8919330e 100644 --- a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDICustodyTransferImpl.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDICustodyTransferImpl.java @@ -1,471 +1,471 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.UUID; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.jws.WebService; -import javax.persistence.EntityManager; -import javax.persistence.EntityTransaction; -import javax.persistence.Query; -import javax.xml.datatype.DatatypeConfigurationException; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.datatype.XMLGregorianCalendar; -import javax.xml.ws.BindingProvider; -import javax.xml.ws.Holder; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.api.util.CustodyTransferQuery; -import org.apache.juddi.api.util.QueryStatus; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.PersistenceManager; -import org.apache.juddi.config.Property; -import org.apache.juddi.mapping.MappingApiToModel; -import org.apache.juddi.mapping.MappingModelToApi; -import org.apache.juddi.model.BindingTemplate; -import org.apache.juddi.model.BusinessEntity; -import org.apache.juddi.model.BusinessService; -import org.apache.juddi.model.Operator; -import org.apache.juddi.model.Tmodel; -import org.apache.juddi.model.TransferTokenKey; -import org.apache.juddi.model.UddiEntity; -import org.apache.juddi.model.UddiEntityPublisher; -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.replication.ReplicationNotifier; -import org.apache.juddi.v3.client.UDDIService; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.FatalErrorException; -import org.apache.juddi.v3.error.InvalidValueException; -import org.apache.juddi.v3.error.TransferNotAllowedException; -import org.apache.juddi.validation.ValidateCustodyTransfer; -import org.uddi.api_v3.OperationalInfo; -import org.uddi.custody_v3.DiscardTransferToken; -import org.uddi.custody_v3.KeyBag; -import org.uddi.custody_v3.TransferEntities; -import org.uddi.custody_v3.TransferOperationalInfo; -import org.uddi.repl_v3.ChangeRecord; -import org.uddi.repl_v3.ChangeRecordIDType; -import org.uddi.repl_v3.ChangeRecordNewData; -import org.uddi.repl_v3.TransferCustody; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.v3_service.UDDICustodyTransferPortType; -import org.uddi.v3_service.UDDIReplicationPortType; - -/** - * This implements the UDDI v3 Custody Transfer API web service - * - */ -@WebService(serviceName = "UDDICustodyTransferService", - endpointInterface = "org.uddi.v3_service.UDDICustodyTransferPortType", - targetNamespace = "urn:uddi-org:v3_service") -public class UDDICustodyTransferImpl extends AuthenticatedService implements UDDICustodyTransferPortType { - - public static final String TRANSFER_TOKEN_PREFIX = "transfertoken:"; - public static final int DEFAULT_TRANSFEREXPIRATION_DAYS = 3; - - private static Log logger = LogFactory.getLog(UDDICustodyTransferImpl.class); - - private static DatatypeFactory df = null; - private UDDIServiceCounter serviceCounter; - - public UDDICustodyTransferImpl() { - super(); - serviceCounter = ServiceCounterLifecycleResource.getServiceCounter(this.getClass()); - init(); - } - - private static synchronized void init() { - if (df == null) { - try { - df = DatatypeFactory.newInstance(); - } catch (DatatypeConfigurationException ex) { - Logger.getLogger(UDDICustodyTransferImpl.class.getName()).log(Level.SEVERE, null, ex); - } - } - } - - @SuppressWarnings("unchecked") - @Override - public void discardTransferToken(DiscardTransferToken body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); - - new ValidateCustodyTransfer(publisher).validateDiscardTransferToken(em, body); - - org.uddi.custody_v3.TransferToken apiTransferToken = body.getTransferToken(); - if (apiTransferToken != null) { - String transferTokenId; - try { - transferTokenId = new String(apiTransferToken.getOpaqueToken(), UTF8); - } catch (UnsupportedEncodingException ex) { - throw new InvalidValueException(new ErrorMessage("errors.stringEncoding")); - } - org.apache.juddi.model.TransferToken modelTransferToken = em.find(org.apache.juddi.model.TransferToken.class, transferTokenId); - if (modelTransferToken != null) { - em.remove(modelTransferToken); - } - } - - KeyBag keyBag = body.getKeyBag(); - if (keyBag != null) { - List keyList = keyBag.getKey(); - Vector params = new Vector(0); - for (String key : keyList) { - // Creating parameters for key-checking query - DynamicQuery.Parameter param = new DynamicQuery.Parameter("UPPER(ttk.entityKey)", - key.toUpperCase(), - DynamicQuery.PREDICATE_EQUALS); - - params.add(param); - } - - // Find the associated transfer tokens and remove them. - DynamicQuery getTokensQry = new DynamicQuery(); - getTokensQry.append("select distinct ttk.transferToken from TransferTokenKey ttk").pad(); - getTokensQry.WHERE().pad().appendGroupedOr(params.toArray(new DynamicQuery.Parameter[0])); - - Query qry = getTokensQry.buildJPAQuery(em); - List tokensToDelete = qry.getResultList(); - if (tokensToDelete != null && tokensToDelete.size() > 0) { - for (org.apache.juddi.model.TransferToken tt : tokensToDelete) { - em.remove(tt); - } - } - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(CustodyTransferQuery.DISCARD_TRANSFERTOKEN, - QueryStatus.SUCCESS, procTime); - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - @Override - public void getTransferToken(String authInfo, KeyBag keyBag, - Holder nodeID, Holder expirationTime, - Holder opaqueToken) throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); - - new ValidateCustodyTransfer(publisher).validateGetTransferToken(em, keyBag); - - int transferExpirationDays = DEFAULT_TRANSFEREXPIRATION_DAYS; - try { - transferExpirationDays = AppConfig.getConfiguration().getInt(Property.JUDDI_TRANSFER_EXPIRATION_DAYS); - // For output - nodeID.value = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID); - } catch (ConfigurationException ce) { - throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval")); - } - - String transferKey = TRANSFER_TOKEN_PREFIX + UUID.randomUUID(); - org.apache.juddi.model.TransferToken transferToken = new org.apache.juddi.model.TransferToken(); - transferToken.setTransferToken(transferKey); - try { - // For output - opaqueToken.value = transferKey.getBytes(UTF8); - } catch (UnsupportedEncodingException ex) { - throw new InvalidValueException(new ErrorMessage("errors.stringEncoding")); - } - - GregorianCalendar gc = new GregorianCalendar(); - gc.add(GregorianCalendar.DAY_OF_MONTH, transferExpirationDays); - - transferToken.setExpirationDate(gc.getTime()); - - try { - DatatypeFactory df = DatatypeFactory.newInstance(); - // For output - expirationTime.value = df.newXMLGregorianCalendar(gc); - } catch (DatatypeConfigurationException ce) { - throw new FatalErrorException(new ErrorMessage("errors.Unspecified")); - } - - List keyList = keyBag.getKey(); - for (String key : keyList) { - TransferTokenKey tokenKey = new TransferTokenKey(transferToken, key); - transferToken.getTransferKeys().add(tokenKey); - } - - em.persist(transferToken); - - tx.commit(); - - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(CustodyTransferQuery.GET_TRANSFERTOKEN, - QueryStatus.SUCCESS, procTime); - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - @Override - public void transferEntities(TransferEntities body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - List changes = new ArrayList(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); - - ValidateCustodyTransfer verifier = new ValidateCustodyTransfer(publisher); - - //if the destination transfer is to a different node, - if (!verifier.validateTransferEntities(em, body)) { - //i don't own these entities, so tell the owner to transfer to me. - - //look up the replication config endpoint for that node and trigger the transfer, then return - //ok this is a node to node transfer, first up a replication client to the destination node - String sourceNode = null; - try { - KeyBag keyBag = body.getKeyBag(); - List keyList = keyBag.getKey(); - for (String key : keyList) { - UddiEntity uddiEntity = em.find(UddiEntity.class, key); - - if (uddiEntity!=null) { - uddiEntity.setIsTransferInProgress(true); - sourceNode = uddiEntity.getNodeId(); - em.merge(uddiEntity); - //save the fact we are expecting a transfer - } - else - { - logger.warn("couldn't find a record for key " + key); - } - } - if (sourceNode==null){ - logger.warn("unable to process transfer, could not locate the source node, perhaps it hasn't been replicated to this node yet?") - ; - throw new Exception("unable to process transfer, could not locate the source node for any of the specific keys, perhaps it hasn't been replicated to this node yet?"); - } - - UDDIReplicationPortType replicationClient = getReplicationClient(sourceNode); - if (replicationClient == null) { - throw new Exception("Unknown node. is it in the replication graph?" + sourceNode); - } - TransferCustody transferCustody = new TransferCustody(); - transferCustody.setTransferToken(body.getTransferToken()); - transferCustody.setKeyBag(body.getKeyBag()); - transferCustody.setTransferOperationalInfo(new TransferOperationalInfo()); - transferCustody.getTransferOperationalInfo().setAuthorizedName(publisher.getAuthorizedName()); - transferCustody.getTransferOperationalInfo().setNodeID(getNode()); - - //and trigger the transfer - logger.info("AUDIT, transfering " + transferCustody.getKeyBag().getKey().size() + " entities to " + publisher.getAuthorizedName() + " at node " + getNode() + " from source " + sourceNode); - replicationClient.transferCustody(transferCustody); - } catch (DispositionReportFaultMessage df) { - logger.error("Unable to transfer entities from " + sourceNode + " to node " + getNode() + " to user " + publisher.getAuthorizedName(), df); - throw new TransferNotAllowedException(new ErrorMessage("E_transferBlocked", df.getMessage())); - } catch (Exception ex) { - logger.error("Unable to transfer entities from " + sourceNode + " to node " + getNode() + " to user " + publisher.getAuthorizedName(), ex); - throw new TransferNotAllowedException(new ErrorMessage("E_transferBlocked", ex.getMessage())); - } - - } else { - changes.addAll(executeTransfer(body, em, publisher.getAuthorizedName(), getNode())); - //all of the items to be transfer are owned locally by *this node. - - } - tx.commit(); - //we need to do something for replication purposes here - //enqueue notifications and storage of the changed records - for (ChangeRecord c : changes) { - try { - c.setChangeID(new ChangeRecordIDType()); - c.getChangeID().setNodeID(getNode()); - c.getChangeID().setOriginatingUSN(null); - ReplicationNotifier.enqueue(MappingApiToModel.mapChangeRecord(c)); - } catch (UnsupportedEncodingException ex) { - logger.error("", ex); - } - } - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(CustodyTransferQuery.TRANSFER_ENTITIES, - QueryStatus.SUCCESS, procTime); - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - } - - private synchronized UDDIReplicationPortType getReplicationClient(String node) { - - UDDIService svc = new UDDIService(); - UDDIReplicationPortType replicationClient = svc.getUDDIReplicationPort(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - StringBuilder sql = new StringBuilder(); - sql.append("select c from ReplicationConfiguration c order by c.serialNumber desc"); - sql.toString(); - Query qry = em.createQuery(sql.toString()); - qry.setMaxResults(1); - - org.apache.juddi.model.ReplicationConfiguration resultList = (org.apache.juddi.model.ReplicationConfiguration) qry.getSingleResult(); - for (Operator o : resultList.getOperator()) { - if (o.getOperatorNodeID().equalsIgnoreCase(node)) { - ((BindingProvider) replicationClient).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, o.getSoapReplicationURL()); - - return replicationClient; - } - } - tx.rollback(); - - } catch (Exception ex) { - logger.fatal("Node not found (or there isn't a replication config)!" + node, ex); - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - //em.close(); - return null; - - } - - /** - * used to factor out the actual execution of custody transfer, used by - * both this service and the replication service. - * - * @since 3.3 - * @param body - * @param em - * @param transferToPublisher - * @param transferToNode - * @return - * @throws DispositionReportFaultMessage - */ - protected List executeTransfer(TransferEntities body, EntityManager em, String transferToPublisher, String transferToNode) throws DispositionReportFaultMessage { - // Once validated, the ownership transfer is as simple as switching the publisher - List changes = new ArrayList();; - KeyBag keyBag = body.getKeyBag(); - List keyList = keyBag.getKey(); - //used for the change journal - - for (String key : keyList) { - UddiEntity uddiEntity = em.find(UddiEntity.class, key); - uddiEntity.setAuthorizedName(transferToPublisher); - uddiEntity.setNodeId(transferToNode); - Date now = new Date(); - uddiEntity.setModified(now); - uddiEntity.setModifiedIncludingChildren(now); - - if (uddiEntity instanceof BusinessEntity) { - BusinessEntity be = (BusinessEntity) uddiEntity; - - List bsList = be.getBusinessServices(); - for (BusinessService bs : bsList) { - bs.setAuthorizedName(transferToPublisher); - bs.setNodeId(transferToNode); - bs.setModified(now); - bs.setModifiedIncludingChildren(now); - - List btList = bs.getBindingTemplates(); - for (BindingTemplate bt : btList) { - bt.setAuthorizedName(transferToPublisher); - bt.setNodeId(transferToNode); - bt.setModified(now); - bt.setModifiedIncludingChildren(now); - - } - } - } - ChangeRecord cr = new ChangeRecord(); - cr.setChangeRecordNewData(new ChangeRecordNewData()); - cr.getChangeRecordNewData().setOperationalInfo(new OperationalInfo()); - cr.getChangeRecordNewData().getOperationalInfo().setAuthorizedName(transferToPublisher); - cr.getChangeRecordNewData().getOperationalInfo().setEntityKey(uddiEntity.getEntityKey()); - cr.getChangeRecordNewData().getOperationalInfo().setNodeID(transferToNode); - GregorianCalendar gcal = new GregorianCalendar(); - gcal.setTime(uddiEntity.getCreated()); - cr.getChangeRecordNewData().getOperationalInfo().setCreated(df.newXMLGregorianCalendar(gcal)); - gcal = new GregorianCalendar(); - gcal.setTime(now); - cr.getChangeRecordNewData().getOperationalInfo().setModified(df.newXMLGregorianCalendar(gcal)); - cr.getChangeRecordNewData().getOperationalInfo().setModifiedIncludingChildren(df.newXMLGregorianCalendar(gcal)); - cr.getChangeRecordNewData().getOperationalInfo().setEntityKey(uddiEntity.getEntityKey()); - - if (uddiEntity instanceof BusinessEntity) { - cr.getChangeRecordNewData().setBusinessEntity(new org.uddi.api_v3.BusinessEntity()); - MappingModelToApi.mapBusinessEntity((BusinessEntity) uddiEntity, cr.getChangeRecordNewData().getBusinessEntity()); - } - if (uddiEntity instanceof Tmodel) { - cr.getChangeRecordNewData().setTModel(new org.uddi.api_v3.TModel()); - MappingModelToApi.mapTModel((Tmodel) uddiEntity, cr.getChangeRecordNewData().getTModel()); - } - changes.add(cr); - em.persist(uddiEntity); - - } - - // After transfer is finished, the token can be removed - org.uddi.custody_v3.TransferToken apiTransferToken = body.getTransferToken(); - String transferTokenId; - try { - transferTokenId = new String(apiTransferToken.getOpaqueToken(), UTF8); - } catch (UnsupportedEncodingException ex) { - throw new InvalidValueException(new ErrorMessage("errors.stringEncoding")); - } - org.apache.juddi.model.TransferToken modelTransferToken = em.find(org.apache.juddi.model.TransferToken.class, transferTokenId); - em.remove(modelTransferToken); - return changes; - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.UUID; +import java.util.Vector; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.jws.WebService; +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.persistence.Query; +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.ws.BindingProvider; +import javax.xml.ws.Holder; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.api.util.CustodyTransferQuery; +import org.apache.juddi.api.util.QueryStatus; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.PersistenceManager; +import org.apache.juddi.config.Property; +import org.apache.juddi.mapping.MappingApiToModel; +import org.apache.juddi.mapping.MappingModelToApi; +import org.apache.juddi.model.BindingTemplate; +import org.apache.juddi.model.BusinessEntity; +import org.apache.juddi.model.BusinessService; +import org.apache.juddi.model.Operator; +import org.apache.juddi.model.Tmodel; +import org.apache.juddi.model.TransferTokenKey; +import org.apache.juddi.model.UddiEntity; +import org.apache.juddi.model.UddiEntityPublisher; +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.replication.ReplicationNotifier; +import org.apache.juddi.v3.client.UDDIService; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.FatalErrorException; +import org.apache.juddi.v3.error.InvalidValueException; +import org.apache.juddi.v3.error.TransferNotAllowedException; +import org.apache.juddi.validation.ValidateCustodyTransfer; +import org.uddi.api_v3.OperationalInfo; +import org.uddi.custody_v3.DiscardTransferToken; +import org.uddi.custody_v3.KeyBag; +import org.uddi.custody_v3.TransferEntities; +import org.uddi.custody_v3.TransferOperationalInfo; +import org.uddi.repl_v3.ChangeRecord; +import org.uddi.repl_v3.ChangeRecordIDType; +import org.uddi.repl_v3.ChangeRecordNewData; +import org.uddi.repl_v3.TransferCustody; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.v3_service.UDDICustodyTransferPortType; +import org.uddi.v3_service.UDDIReplicationPortType; + +/** + * This implements the UDDI v3 Custody Transfer API web service + * + */ +@WebService(serviceName = "UDDICustodyTransferService", + endpointInterface = "org.uddi.v3_service.UDDICustodyTransferPortType", + targetNamespace = "urn:uddi-org:v3_service") +public class UDDICustodyTransferImpl extends AuthenticatedService implements UDDICustodyTransferPortType { + + public static final String TRANSFER_TOKEN_PREFIX = "transfertoken:"; + public static final int DEFAULT_TRANSFEREXPIRATION_DAYS = 3; + + private static Log logger = LogFactory.getLog(UDDICustodyTransferImpl.class); + + private static DatatypeFactory df = null; + private UDDIServiceCounter serviceCounter; + + public UDDICustodyTransferImpl() { + super(); + serviceCounter = ServiceCounterLifecycleResource.getServiceCounter(this.getClass()); + init(); + } + + private static synchronized void init() { + if (df == null) { + try { + df = DatatypeFactory.newInstance(); + } catch (DatatypeConfigurationException ex) { + Logger.getLogger(UDDICustodyTransferImpl.class.getName()).log(Level.SEVERE, null, ex); + } + } + } + + @SuppressWarnings("unchecked") + @Override + public void discardTransferToken(DiscardTransferToken body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); + + new ValidateCustodyTransfer(publisher).validateDiscardTransferToken(em, body); + + org.uddi.custody_v3.TransferToken apiTransferToken = body.getTransferToken(); + if (apiTransferToken != null) { + String transferTokenId; + try { + transferTokenId = new String(apiTransferToken.getOpaqueToken(), UTF8); + } catch (UnsupportedEncodingException ex) { + throw new InvalidValueException(new ErrorMessage("errors.stringEncoding")); + } + org.apache.juddi.model.TransferToken modelTransferToken = em.find(org.apache.juddi.model.TransferToken.class, transferTokenId); + if (modelTransferToken != null) { + em.remove(modelTransferToken); + } + } + + KeyBag keyBag = body.getKeyBag(); + if (keyBag != null) { + List keyList = keyBag.getKey(); + Vector params = new Vector(0); + for (String key : keyList) { + // Creating parameters for key-checking query + DynamicQuery.Parameter param = new DynamicQuery.Parameter("UPPER(ttk.entityKey)", + key.toUpperCase(), + DynamicQuery.PREDICATE_EQUALS); + + params.add(param); + } + + // Find the associated transfer tokens and remove them. + DynamicQuery getTokensQry = new DynamicQuery(); + getTokensQry.append("select distinct ttk.transferToken from TransferTokenKey ttk").pad(); + getTokensQry.WHERE().pad().appendGroupedOr(params.toArray(new DynamicQuery.Parameter[0])); + + Query qry = getTokensQry.buildJPAQuery(em); + List tokensToDelete = qry.getResultList(); + if (tokensToDelete != null && tokensToDelete.size() > 0) { + for (org.apache.juddi.model.TransferToken tt : tokensToDelete) { + em.remove(tt); + } + } + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(CustodyTransferQuery.DISCARD_TRANSFERTOKEN, + QueryStatus.SUCCESS, procTime); + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + @Override + public void getTransferToken(String authInfo, KeyBag keyBag, + Holder nodeID, Holder expirationTime, + Holder opaqueToken) throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); + + new ValidateCustodyTransfer(publisher).validateGetTransferToken(em, keyBag); + + int transferExpirationDays = DEFAULT_TRANSFEREXPIRATION_DAYS; + try { + transferExpirationDays = AppConfig.getConfiguration().getInt(Property.JUDDI_TRANSFER_EXPIRATION_DAYS); + // For output + nodeID.value = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID); + } catch (ConfigurationException ce) { + throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval")); + } + + String transferKey = TRANSFER_TOKEN_PREFIX + UUID.randomUUID(); + org.apache.juddi.model.TransferToken transferToken = new org.apache.juddi.model.TransferToken(); + transferToken.setTransferToken(transferKey); + try { + // For output + opaqueToken.value = transferKey.getBytes(UTF8); + } catch (UnsupportedEncodingException ex) { + throw new InvalidValueException(new ErrorMessage("errors.stringEncoding")); + } + + GregorianCalendar gc = new GregorianCalendar(); + gc.add(GregorianCalendar.DAY_OF_MONTH, transferExpirationDays); + + transferToken.setExpirationDate(gc.getTime()); + + try { + DatatypeFactory df = DatatypeFactory.newInstance(); + // For output + expirationTime.value = df.newXMLGregorianCalendar(gc); + } catch (DatatypeConfigurationException ce) { + throw new FatalErrorException(new ErrorMessage("errors.Unspecified")); + } + + List keyList = keyBag.getKey(); + for (String key : keyList) { + TransferTokenKey tokenKey = new TransferTokenKey(transferToken, key); + transferToken.getTransferKeys().add(tokenKey); + } + + em.persist(transferToken); + + tx.commit(); + + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(CustodyTransferQuery.GET_TRANSFERTOKEN, + QueryStatus.SUCCESS, procTime); + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + @Override + public void transferEntities(TransferEntities body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + List changes = new ArrayList(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); + + ValidateCustodyTransfer verifier = new ValidateCustodyTransfer(publisher); + + //if the destination transfer is to a different node, + if (!verifier.validateTransferEntities(em, body)) { + //i don't own these entities, so tell the owner to transfer to me. + + //look up the replication config endpoint for that node and trigger the transfer, then return + //ok this is a node to node transfer, first up a replication client to the destination node + String sourceNode = null; + try { + KeyBag keyBag = body.getKeyBag(); + List keyList = keyBag.getKey(); + for (String key : keyList) { + UddiEntity uddiEntity = em.find(UddiEntity.class, key); + + if (uddiEntity!=null) { + uddiEntity.setIsTransferInProgress(true); + sourceNode = uddiEntity.getNodeId(); + em.merge(uddiEntity); + //save the fact we are expecting a transfer + } + else + { + logger.warn("couldn't find a record for key " + key); + } + } + if (sourceNode==null){ + logger.warn("unable to process transfer, could not locate the source node, perhaps it hasn't been replicated to this node yet?") + ; + throw new Exception("unable to process transfer, could not locate the source node for any of the specific keys, perhaps it hasn't been replicated to this node yet?"); + } + + UDDIReplicationPortType replicationClient = getReplicationClient(sourceNode); + if (replicationClient == null) { + throw new Exception("Unknown node. is it in the replication graph?" + sourceNode); + } + TransferCustody transferCustody = new TransferCustody(); + transferCustody.setTransferToken(body.getTransferToken()); + transferCustody.setKeyBag(body.getKeyBag()); + transferCustody.setTransferOperationalInfo(new TransferOperationalInfo()); + transferCustody.getTransferOperationalInfo().setAuthorizedName(publisher.getAuthorizedName()); + transferCustody.getTransferOperationalInfo().setNodeID(getNode()); + + //and trigger the transfer + logger.info("AUDIT, transfering " + transferCustody.getKeyBag().getKey().size() + " entities to " + publisher.getAuthorizedName() + " at node " + getNode() + " from source " + sourceNode); + replicationClient.transferCustody(transferCustody); + } catch (DispositionReportFaultMessage df) { + logger.error("Unable to transfer entities from " + sourceNode + " to node " + getNode() + " to user " + publisher.getAuthorizedName(), df); + throw new TransferNotAllowedException(new ErrorMessage("E_transferBlocked", df.getMessage())); + } catch (Exception ex) { + logger.error("Unable to transfer entities from " + sourceNode + " to node " + getNode() + " to user " + publisher.getAuthorizedName(), ex); + throw new TransferNotAllowedException(new ErrorMessage("E_transferBlocked", ex.getMessage())); + } + + } else { + changes.addAll(executeTransfer(body, em, publisher.getAuthorizedName(), getNode())); + //all of the items to be transfer are owned locally by *this node. + + } + tx.commit(); + //we need to do something for replication purposes here + //enqueue notifications and storage of the changed records + for (ChangeRecord c : changes) { + try { + c.setChangeID(new ChangeRecordIDType()); + c.getChangeID().setNodeID(getNode()); + c.getChangeID().setOriginatingUSN(null); + ReplicationNotifier.enqueue(MappingApiToModel.mapChangeRecord(c)); + } catch (UnsupportedEncodingException ex) { + logger.error("", ex); + } + } + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(CustodyTransferQuery.TRANSFER_ENTITIES, + QueryStatus.SUCCESS, procTime); + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + } + + private synchronized UDDIReplicationPortType getReplicationClient(String node) { + + UDDIService svc = new UDDIService(); + UDDIReplicationPortType replicationClient = svc.getUDDIReplicationPort(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + StringBuilder sql = new StringBuilder(); + sql.append("select c from ReplicationConfiguration c order by c.serialNumber desc"); + sql.toString(); + Query qry = em.createQuery(sql.toString()); + qry.setMaxResults(1); + + org.apache.juddi.model.ReplicationConfiguration resultList = (org.apache.juddi.model.ReplicationConfiguration) qry.getSingleResult(); + for (Operator o : resultList.getOperator()) { + if (o.getOperatorNodeID().equalsIgnoreCase(node)) { + ((BindingProvider) replicationClient).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, o.getSoapReplicationURL()); + + return replicationClient; + } + } + tx.rollback(); + + } catch (Exception ex) { + logger.fatal("Node not found (or there isn't a replication config)!" + node, ex); + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + //em.close(); + return null; + + } + + /** + * used to factor out the actual execution of custody transfer, used by + * both this service and the replication service. + * + * @since 3.3 + * @param body + * @param em + * @param transferToPublisher + * @param transferToNode + * @return + * @throws DispositionReportFaultMessage + */ + protected List executeTransfer(TransferEntities body, EntityManager em, String transferToPublisher, String transferToNode) throws DispositionReportFaultMessage { + // Once validated, the ownership transfer is as simple as switching the publisher + List changes = new ArrayList();; + KeyBag keyBag = body.getKeyBag(); + List keyList = keyBag.getKey(); + //used for the change journal + + for (String key : keyList) { + UddiEntity uddiEntity = em.find(UddiEntity.class, key); + uddiEntity.setAuthorizedName(transferToPublisher); + uddiEntity.setNodeId(transferToNode); + Date now = new Date(); + uddiEntity.setModified(now); + uddiEntity.setModifiedIncludingChildren(now); + + if (uddiEntity instanceof BusinessEntity) { + BusinessEntity be = (BusinessEntity) uddiEntity; + + List bsList = be.getBusinessServices(); + for (BusinessService bs : bsList) { + bs.setAuthorizedName(transferToPublisher); + bs.setNodeId(transferToNode); + bs.setModified(now); + bs.setModifiedIncludingChildren(now); + + List btList = bs.getBindingTemplates(); + for (BindingTemplate bt : btList) { + bt.setAuthorizedName(transferToPublisher); + bt.setNodeId(transferToNode); + bt.setModified(now); + bt.setModifiedIncludingChildren(now); + + } + } + } + ChangeRecord cr = new ChangeRecord(); + cr.setChangeRecordNewData(new ChangeRecordNewData()); + cr.getChangeRecordNewData().setOperationalInfo(new OperationalInfo()); + cr.getChangeRecordNewData().getOperationalInfo().setAuthorizedName(transferToPublisher); + cr.getChangeRecordNewData().getOperationalInfo().setEntityKey(uddiEntity.getEntityKey()); + cr.getChangeRecordNewData().getOperationalInfo().setNodeID(transferToNode); + GregorianCalendar gcal = new GregorianCalendar(); + gcal.setTime(uddiEntity.getCreated()); + cr.getChangeRecordNewData().getOperationalInfo().setCreated(df.newXMLGregorianCalendar(gcal)); + gcal = new GregorianCalendar(); + gcal.setTime(now); + cr.getChangeRecordNewData().getOperationalInfo().setModified(df.newXMLGregorianCalendar(gcal)); + cr.getChangeRecordNewData().getOperationalInfo().setModifiedIncludingChildren(df.newXMLGregorianCalendar(gcal)); + cr.getChangeRecordNewData().getOperationalInfo().setEntityKey(uddiEntity.getEntityKey()); + + if (uddiEntity instanceof BusinessEntity) { + cr.getChangeRecordNewData().setBusinessEntity(new org.uddi.api_v3.BusinessEntity()); + MappingModelToApi.mapBusinessEntity((BusinessEntity) uddiEntity, cr.getChangeRecordNewData().getBusinessEntity()); + } + if (uddiEntity instanceof Tmodel) { + cr.getChangeRecordNewData().setTModel(new org.uddi.api_v3.TModel()); + MappingModelToApi.mapTModel((Tmodel) uddiEntity, cr.getChangeRecordNewData().getTModel()); + } + changes.add(cr); + em.persist(uddiEntity); + + } + + // After transfer is finished, the token can be removed + org.uddi.custody_v3.TransferToken apiTransferToken = body.getTransferToken(); + String transferTokenId; + try { + transferTokenId = new String(apiTransferToken.getOpaqueToken(), UTF8); + } catch (UnsupportedEncodingException ex) { + throw new InvalidValueException(new ErrorMessage("errors.stringEncoding")); + } + org.apache.juddi.model.TransferToken modelTransferToken = em.find(org.apache.juddi.model.TransferToken.class, transferTokenId); + em.remove(modelTransferToken); + return changes; + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIInquiryImpl.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIInquiryImpl.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIInquiryImpl.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIInquiryImpl.java index 701f5f834..29a2cf495 100644 --- a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIInquiryImpl.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIInquiryImpl.java @@ -1,630 +1,630 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.io.File; -import java.io.FileOutputStream; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.jws.WebService; -import javax.persistence.EntityManager; -import javax.persistence.EntityTransaction; -import javax.xml.bind.JAXB; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.api.util.InquiryQuery; -import org.apache.juddi.api.util.QueryStatus; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.PersistenceManager; -import org.apache.juddi.config.Property; -import org.apache.juddi.mapping.MappingModelToApi; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.InvalidKeyPassedException; -import org.apache.juddi.validation.ValidateInquiry; -import org.uddi.api_v3.BindingDetail; -import org.uddi.api_v3.BusinessDetail; -import org.uddi.api_v3.BusinessList; -import org.uddi.api_v3.FindBinding; -import org.uddi.api_v3.FindBusiness; -import org.uddi.api_v3.FindRelatedBusinesses; -import org.uddi.api_v3.FindService; -import org.uddi.api_v3.FindTModel; -import org.uddi.api_v3.GetBindingDetail; -import org.uddi.api_v3.GetBusinessDetail; -import org.uddi.api_v3.GetOperationalInfo; -import org.uddi.api_v3.GetServiceDetail; -import org.uddi.api_v3.GetTModelDetail; -import org.uddi.api_v3.OperationalInfos; -import org.uddi.api_v3.RelatedBusinessesList; -import org.uddi.api_v3.ServiceDetail; -import org.uddi.api_v3.ServiceList; -import org.uddi.api_v3.TModelDetail; -import org.uddi.api_v3.TModelList; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.v3_service.UDDIInquiryPortType; - - -/** - * This implements the UDDI v3 Inquiry API web service - * @author Jeff Faath - */ -@WebService(serviceName="UDDIInquiryService", - endpointInterface="org.uddi.v3_service.UDDIInquiryPortType", - targetNamespace = "urn:uddi-org:api_v3_portType") -public class UDDIInquiryImpl extends AuthenticatedService implements UDDIInquiryPortType { - - - private static Log log = LogFactory.getLog(UDDIInquiryImpl.class); - - private static boolean isLogRequestPayloads() { - boolean result = false; - try { - result = AppConfig.getConfiguration().getBoolean(Property.JUDDI_LOGGING_FindApiCalls, false); - } catch (ConfigurationException e) { - log.error("Configuration exception occurred retrieving: " + Property.JUDDI_LOGGING_FindApiCalls, e); - } - return result; - } - private UDDIServiceCounter serviceCounter; - - public UDDIInquiryImpl() { - super(); - serviceCounter = ServiceCounterLifecycleResource.getServiceCounter(UDDIInquiryImpl.class); - } - - - private static void LogFindRelatedBusinessRequest(FindRelatedBusinesses request) { - request.setAuthInfo(null); - LogRequest(request); - } - private static void LogFindBindingRequest(FindBinding request) { - request.setAuthInfo(null); - LogRequest(request); - } - private static void LogFindTModelRequest(FindTModel request) { - request.setAuthInfo(null); - LogRequest(request); - } - private static void LogFindServiceRequest(FindService request) { - request.setAuthInfo(null); - LogRequest(request); - } - private static void LogFindBusinessRequest(FindBusiness request) { - request.setAuthInfo(null); - LogRequest(request); - } - private static synchronized void LogRequest(Object request) { - if (isLogRequestPayloads()) - try { - File f = new File(System.currentTimeMillis()+".xml"); - FileOutputStream fos = new FileOutputStream(f); - JAXB.marshal(request, fos); - fos.close(); - f = null; - } catch (Exception ex) { - logger.warn("Unable to log request payload", ex); - } - } - - - public BindingDetail findBinding(FindBinding body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - try { - new ValidateInquiry(null).validateFindBinding(body); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(InquiryQuery.FIND_BINDING, QueryStatus.FAILED, procTime); - throw drfm; - } - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - if (isAuthenticated()) - this.getEntityPublisher(em, body.getAuthInfo()); - - LogFindBindingRequest(body); - if (body.getServiceKey() != null && body.getServiceKey().length() > 0) { - // Check that we were passed a valid serviceKey per - // 5.1.12.4 of the UDDI v3 spec - String serviceKey = body.getServiceKey(); - org.apache.juddi.model.BusinessService modelBusinessService = null; - try { - modelBusinessService=em.find(org.apache.juddi.model.BusinessService.class, serviceKey); - } catch (Exception e) { - log.debug(e.getMessage(), e); - } - if (modelBusinessService == null) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ServiceNotFound", serviceKey)); - } - - org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); - findQualifiers.mapApiFindQualifiers(body.getFindQualifiers()); - - List keysFound = InquiryHelper.findBinding(body, findQualifiers, em); - - BindingDetail result = InquiryHelper.getBindingDetailFromKeys(body, findQualifiers, em, keysFound); - tx.rollback(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(InquiryQuery.FIND_BINDING, QueryStatus.SUCCESS, procTime); - - return result; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - - public BusinessList findBusiness(FindBusiness body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - try { - new ValidateInquiry(null).validateFindBusiness(body); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(InquiryQuery.FIND_BUSINESS, QueryStatus.FAILED, procTime); - throw drfm; - } - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - try { - //AppConfig.reloadConfig(); - logger.info("FindBusiness with tModel bag filtering is enabled: " + - AppConfig.getConfiguration().getBoolean(Property.JUDDI_ENABLE_FIND_BUSINESS_TMODEL_BAG_FILTERING,true) - + " loaded from " + AppConfig.getConfigFileURL()); - } catch (ConfigurationException ex) { - ex.printStackTrace(); - } - tx.begin(); - - if (isAuthenticated()) - this.getEntityPublisher(em, body.getAuthInfo()); - LogFindBusinessRequest(body); - org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); - findQualifiers.mapApiFindQualifiers(body.getFindQualifiers()); - - List keysFound = InquiryHelper.findBusiness(body, findQualifiers, em); - - BusinessList result = InquiryHelper.getBusinessListFromKeys(body, findQualifiers, em, keysFound); - - tx.rollback(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(InquiryQuery.FIND_BUSINESS, QueryStatus.SUCCESS, procTime); - - return result; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - - public RelatedBusinessesList findRelatedBusinesses(FindRelatedBusinesses body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - try { - new ValidateInquiry(null).validateFindRelatedBusinesses(body, false); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(InquiryQuery.FIND_RELATEDBUSINESSES, QueryStatus.FAILED, procTime); - throw drfm; - } - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - if (isAuthenticated()) - this.getEntityPublisher(em, body.getAuthInfo()); - LogFindRelatedBusinessRequest(body); - - // TODO: findQualifiers aren't really used for this call, except maybe for sorting. Sorting must be done in Java due to the retrieval method used. Right now - // no sorting is performed. - org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); - findQualifiers.mapApiFindQualifiers(body.getFindQualifiers()); - - RelatedBusinessesList result = InquiryHelper.getRelatedBusinessesList(body, em); - - tx.rollback(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(InquiryQuery.FIND_RELATEDBUSINESSES, QueryStatus.SUCCESS, procTime); - - return result; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - - public ServiceList findService(FindService body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - try { - new ValidateInquiry(null).validateFindService(body); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(InquiryQuery.FIND_SERVICE, QueryStatus.FAILED, procTime); - throw drfm; - } - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - if (isAuthenticated()) - this.getEntityPublisher(em, body.getAuthInfo()); - LogFindServiceRequest(body); - org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); - findQualifiers.mapApiFindQualifiers(body.getFindQualifiers()); - - List keysFound = InquiryHelper.findService(body, findQualifiers, em); - - if (keysFound.size() == 0) { - if (body.getBusinessKey() != null) { - // Check that we were passed a valid businessKey per - // 5.1.12.4 of the UDDI v3 spec - String businessKey = body.getBusinessKey(); - org.apache.juddi.model.BusinessEntity modelBusinessEntity = null; - try { - modelBusinessEntity = em.find(org.apache.juddi.model.BusinessEntity.class, businessKey); - } catch (ClassCastException e) {} - if (modelBusinessEntity == null) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BusinessNotFound", businessKey)); - } - } - } - - ServiceList result = InquiryHelper.getServiceListFromKeys(body, findQualifiers, em, keysFound); - - tx.rollback(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(InquiryQuery.FIND_SERVICE, QueryStatus.SUCCESS, procTime); - - return result; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - - public TModelList findTModel(FindTModel body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - try { - new ValidateInquiry(null).validateFindTModel(body, false); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(InquiryQuery.FIND_TMODEL, QueryStatus.FAILED, procTime); - throw drfm; - } - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - if (isAuthenticated()) - this.getEntityPublisher(em, body.getAuthInfo()); - LogFindTModelRequest(body); - org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); - findQualifiers.mapApiFindQualifiers(body.getFindQualifiers()); - - List keysFound = InquiryHelper.findTModel(body, findQualifiers, em); - - TModelList result = InquiryHelper.getTModelListFromKeys(body, findQualifiers, em, keysFound); - - tx.rollback(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(InquiryQuery.FIND_TMODEL, QueryStatus.SUCCESS, procTime); - - return result; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - - public BindingDetail getBindingDetail(GetBindingDetail body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - try { - new ValidateInquiry(null).validateGetBindingDetail(body); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(InquiryQuery.FIND_TMODEL, QueryStatus.FAILED, procTime); - throw drfm; - } - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - if (isAuthenticated()) - this.getEntityPublisher(em, body.getAuthInfo()); - - BindingDetail result = new BindingDetail(); - - List bindingKeyList = body.getBindingKey(); - for (String bindingKey : bindingKeyList) { - org.apache.juddi.model.BindingTemplate modelBindingTemplate = null; - try { - modelBindingTemplate = em.find(org.apache.juddi.model.BindingTemplate.class, bindingKey); - } catch (ClassCastException e) {} - if (modelBindingTemplate == null) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BindingTemplateNotFound", bindingKey)); - - org.uddi.api_v3.BindingTemplate apiBindingTemplate = new org.uddi.api_v3.BindingTemplate(); - - MappingModelToApi.mapBindingTemplate(modelBindingTemplate, apiBindingTemplate); - - result.getBindingTemplate().add(apiBindingTemplate); - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(InquiryQuery.GET_BINDINGDETAIL, QueryStatus.SUCCESS, procTime); - - return result; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - - public BusinessDetail getBusinessDetail(GetBusinessDetail body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - try { - new ValidateInquiry(null).validateGetBusinessDetail(body); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(InquiryQuery.GET_BUSINESSDETAIL, QueryStatus.FAILED, procTime); - throw drfm; - } - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - if (isAuthenticated()) - this.getEntityPublisher(em, body.getAuthInfo()); - - BusinessDetail result = new BusinessDetail(); - - List businessKeyList = body.getBusinessKey(); - for (String businessKey : businessKeyList) { - org.apache.juddi.model.BusinessEntity modelBusinessEntity = null; - try { - modelBusinessEntity = em.find(org.apache.juddi.model.BusinessEntity.class, businessKey); - } catch (ClassCastException e) {} - if (modelBusinessEntity == null) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BusinessNotFound", businessKey)); - - org.uddi.api_v3.BusinessEntity apiBusinessEntity = new org.uddi.api_v3.BusinessEntity(); - - MappingModelToApi.mapBusinessEntity(modelBusinessEntity, apiBusinessEntity); - - result.getBusinessEntity().add(apiBusinessEntity); - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(InquiryQuery.GET_BUSINESSDETAIL, QueryStatus.SUCCESS, procTime); - - return result; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - - public OperationalInfos getOperationalInfo(GetOperationalInfo body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - try { - new ValidateInquiry(null).validateGetOperationalInfo(body); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(InquiryQuery.GET_OPERATIONALINFO, QueryStatus.FAILED, procTime); - throw drfm; - } - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - if (isAuthenticated()) - this.getEntityPublisher(em, body.getAuthInfo()); - - OperationalInfos result = new OperationalInfos(); - - List entityKeyList = body.getEntityKey(); - for (String entityKey : entityKeyList) { - org.apache.juddi.model.UddiEntity modelUddiEntity = null; - try { - modelUddiEntity = em.find(org.apache.juddi.model.UddiEntity.class, entityKey); - } catch (ClassCastException e) {} - if (modelUddiEntity == null) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.EntityNotFound", entityKey)); - - org.uddi.api_v3.OperationalInfo apiOperationalInfo = new org.uddi.api_v3.OperationalInfo(); - - MappingModelToApi.mapOperationalInfo(modelUddiEntity, apiOperationalInfo); - - result.getOperationalInfo().add(apiOperationalInfo); - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(InquiryQuery.GET_OPERATIONALINFO, QueryStatus.SUCCESS, procTime); - - return result; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - - public ServiceDetail getServiceDetail(GetServiceDetail body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - try { - new ValidateInquiry(null).validateGetServiceDetail(body); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(InquiryQuery.GET_SERVICEDETAIL, QueryStatus.FAILED, procTime); - throw drfm; - } - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - if (isAuthenticated()) - this.getEntityPublisher(em, body.getAuthInfo()); - - ServiceDetail result = new ServiceDetail(); - - List serviceKeyList = body.getServiceKey(); - for (String serviceKey : serviceKeyList) { - org.apache.juddi.model.BusinessService modelBusinessService = null; - try { - modelBusinessService = em.find(org.apache.juddi.model.BusinessService.class, serviceKey); - } catch (ClassCastException e){} - if (modelBusinessService == null) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ServiceNotFound", serviceKey)); - - org.uddi.api_v3.BusinessService apiBusinessService = new org.uddi.api_v3.BusinessService(); - - MappingModelToApi.mapBusinessService(modelBusinessService, apiBusinessService); - - result.getBusinessService().add(apiBusinessService); - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(InquiryQuery.GET_SERVICEDETAIL, QueryStatus.SUCCESS, procTime); - - return result; - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - - public TModelDetail getTModelDetail(GetTModelDetail body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - try { - new ValidateInquiry(null).validateGetTModelDetail(body); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(InquiryQuery.GET_TMODELDETAIL, QueryStatus.FAILED, procTime); - throw drfm; - } - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - if (isAuthenticated()) - this.getEntityPublisher(em, body.getAuthInfo()); - - TModelDetail result = new TModelDetail(); - - List tmodelKeyList = body.getTModelKey(); - for (String tmodelKey : tmodelKeyList) { - org.apache.juddi.model.Tmodel modelTModel = null; - try { - modelTModel = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey); - } catch (ClassCastException e) {} - if (modelTModel == null) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.TModelNotFound", tmodelKey)); - - org.uddi.api_v3.TModel apiTModel = new org.uddi.api_v3.TModel(); - - MappingModelToApi.mapTModel(modelTModel, apiTModel); - - result.getTModel().add(apiTModel); - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(InquiryQuery.GET_TMODELDETAIL, QueryStatus.SUCCESS, procTime); - - return result; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - private boolean isAuthenticated() { - boolean result = false; - try { - result = AppConfig.getConfiguration().getBoolean(Property.JUDDI_AUTHENTICATE_INQUIRY); - } catch (ConfigurationException e) { - log.error("Configuration exception occurred retrieving: " + Property.JUDDI_AUTHENTICATE_INQUIRY, e); - } - return result; - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.io.File; +import java.io.FileOutputStream; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.jws.WebService; +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.xml.bind.JAXB; +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.api.util.InquiryQuery; +import org.apache.juddi.api.util.QueryStatus; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.PersistenceManager; +import org.apache.juddi.config.Property; +import org.apache.juddi.mapping.MappingModelToApi; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.InvalidKeyPassedException; +import org.apache.juddi.validation.ValidateInquiry; +import org.uddi.api_v3.BindingDetail; +import org.uddi.api_v3.BusinessDetail; +import org.uddi.api_v3.BusinessList; +import org.uddi.api_v3.FindBinding; +import org.uddi.api_v3.FindBusiness; +import org.uddi.api_v3.FindRelatedBusinesses; +import org.uddi.api_v3.FindService; +import org.uddi.api_v3.FindTModel; +import org.uddi.api_v3.GetBindingDetail; +import org.uddi.api_v3.GetBusinessDetail; +import org.uddi.api_v3.GetOperationalInfo; +import org.uddi.api_v3.GetServiceDetail; +import org.uddi.api_v3.GetTModelDetail; +import org.uddi.api_v3.OperationalInfos; +import org.uddi.api_v3.RelatedBusinessesList; +import org.uddi.api_v3.ServiceDetail; +import org.uddi.api_v3.ServiceList; +import org.uddi.api_v3.TModelDetail; +import org.uddi.api_v3.TModelList; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.v3_service.UDDIInquiryPortType; + + +/** + * This implements the UDDI v3 Inquiry API web service + * @author Jeff Faath + */ +@WebService(serviceName="UDDIInquiryService", + endpointInterface="org.uddi.v3_service.UDDIInquiryPortType", + targetNamespace = "urn:uddi-org:api_v3_portType") +public class UDDIInquiryImpl extends AuthenticatedService implements UDDIInquiryPortType { + + + private static Log log = LogFactory.getLog(UDDIInquiryImpl.class); + + private static boolean isLogRequestPayloads() { + boolean result = false; + try { + result = AppConfig.getConfiguration().getBoolean(Property.JUDDI_LOGGING_FindApiCalls, false); + } catch (ConfigurationException e) { + log.error("Configuration exception occurred retrieving: " + Property.JUDDI_LOGGING_FindApiCalls, e); + } + return result; + } + private UDDIServiceCounter serviceCounter; + + public UDDIInquiryImpl() { + super(); + serviceCounter = ServiceCounterLifecycleResource.getServiceCounter(UDDIInquiryImpl.class); + } + + + private static void LogFindRelatedBusinessRequest(FindRelatedBusinesses request) { + request.setAuthInfo(null); + LogRequest(request); + } + private static void LogFindBindingRequest(FindBinding request) { + request.setAuthInfo(null); + LogRequest(request); + } + private static void LogFindTModelRequest(FindTModel request) { + request.setAuthInfo(null); + LogRequest(request); + } + private static void LogFindServiceRequest(FindService request) { + request.setAuthInfo(null); + LogRequest(request); + } + private static void LogFindBusinessRequest(FindBusiness request) { + request.setAuthInfo(null); + LogRequest(request); + } + private static synchronized void LogRequest(Object request) { + if (isLogRequestPayloads()) + try { + File f = new File(System.currentTimeMillis()+".xml"); + FileOutputStream fos = new FileOutputStream(f); + JAXB.marshal(request, fos); + fos.close(); + f = null; + } catch (Exception ex) { + logger.warn("Unable to log request payload", ex); + } + } + + + public BindingDetail findBinding(FindBinding body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + try { + new ValidateInquiry(null).validateFindBinding(body); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(InquiryQuery.FIND_BINDING, QueryStatus.FAILED, procTime); + throw drfm; + } + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + if (isAuthenticated()) + this.getEntityPublisher(em, body.getAuthInfo()); + + LogFindBindingRequest(body); + if (body.getServiceKey() != null && body.getServiceKey().length() > 0) { + // Check that we were passed a valid serviceKey per + // 5.1.12.4 of the UDDI v3 spec + String serviceKey = body.getServiceKey(); + org.apache.juddi.model.BusinessService modelBusinessService = null; + try { + modelBusinessService=em.find(org.apache.juddi.model.BusinessService.class, serviceKey); + } catch (Exception e) { + log.debug(e.getMessage(), e); + } + if (modelBusinessService == null) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ServiceNotFound", serviceKey)); + } + + org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); + findQualifiers.mapApiFindQualifiers(body.getFindQualifiers()); + + List keysFound = InquiryHelper.findBinding(body, findQualifiers, em); + + BindingDetail result = InquiryHelper.getBindingDetailFromKeys(body, findQualifiers, em, keysFound); + tx.rollback(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(InquiryQuery.FIND_BINDING, QueryStatus.SUCCESS, procTime); + + return result; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + + public BusinessList findBusiness(FindBusiness body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + try { + new ValidateInquiry(null).validateFindBusiness(body); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(InquiryQuery.FIND_BUSINESS, QueryStatus.FAILED, procTime); + throw drfm; + } + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + try { + //AppConfig.reloadConfig(); + logger.info("FindBusiness with tModel bag filtering is enabled: " + + AppConfig.getConfiguration().getBoolean(Property.JUDDI_ENABLE_FIND_BUSINESS_TMODEL_BAG_FILTERING,true) + + " loaded from " + AppConfig.getConfigFileURL()); + } catch (ConfigurationException ex) { + ex.printStackTrace(); + } + tx.begin(); + + if (isAuthenticated()) + this.getEntityPublisher(em, body.getAuthInfo()); + LogFindBusinessRequest(body); + org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); + findQualifiers.mapApiFindQualifiers(body.getFindQualifiers()); + + List keysFound = InquiryHelper.findBusiness(body, findQualifiers, em); + + BusinessList result = InquiryHelper.getBusinessListFromKeys(body, findQualifiers, em, keysFound); + + tx.rollback(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(InquiryQuery.FIND_BUSINESS, QueryStatus.SUCCESS, procTime); + + return result; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + + public RelatedBusinessesList findRelatedBusinesses(FindRelatedBusinesses body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + try { + new ValidateInquiry(null).validateFindRelatedBusinesses(body, false); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(InquiryQuery.FIND_RELATEDBUSINESSES, QueryStatus.FAILED, procTime); + throw drfm; + } + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + if (isAuthenticated()) + this.getEntityPublisher(em, body.getAuthInfo()); + LogFindRelatedBusinessRequest(body); + + // TODO: findQualifiers aren't really used for this call, except maybe for sorting. Sorting must be done in Java due to the retrieval method used. Right now + // no sorting is performed. + org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); + findQualifiers.mapApiFindQualifiers(body.getFindQualifiers()); + + RelatedBusinessesList result = InquiryHelper.getRelatedBusinessesList(body, em); + + tx.rollback(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(InquiryQuery.FIND_RELATEDBUSINESSES, QueryStatus.SUCCESS, procTime); + + return result; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + + public ServiceList findService(FindService body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + try { + new ValidateInquiry(null).validateFindService(body); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(InquiryQuery.FIND_SERVICE, QueryStatus.FAILED, procTime); + throw drfm; + } + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + if (isAuthenticated()) + this.getEntityPublisher(em, body.getAuthInfo()); + LogFindServiceRequest(body); + org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); + findQualifiers.mapApiFindQualifiers(body.getFindQualifiers()); + + List keysFound = InquiryHelper.findService(body, findQualifiers, em); + + if (keysFound.size() == 0) { + if (body.getBusinessKey() != null) { + // Check that we were passed a valid businessKey per + // 5.1.12.4 of the UDDI v3 spec + String businessKey = body.getBusinessKey(); + org.apache.juddi.model.BusinessEntity modelBusinessEntity = null; + try { + modelBusinessEntity = em.find(org.apache.juddi.model.BusinessEntity.class, businessKey); + } catch (ClassCastException e) {} + if (modelBusinessEntity == null) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BusinessNotFound", businessKey)); + } + } + } + + ServiceList result = InquiryHelper.getServiceListFromKeys(body, findQualifiers, em, keysFound); + + tx.rollback(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(InquiryQuery.FIND_SERVICE, QueryStatus.SUCCESS, procTime); + + return result; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + + public TModelList findTModel(FindTModel body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + try { + new ValidateInquiry(null).validateFindTModel(body, false); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(InquiryQuery.FIND_TMODEL, QueryStatus.FAILED, procTime); + throw drfm; + } + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + if (isAuthenticated()) + this.getEntityPublisher(em, body.getAuthInfo()); + LogFindTModelRequest(body); + org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); + findQualifiers.mapApiFindQualifiers(body.getFindQualifiers()); + + List keysFound = InquiryHelper.findTModel(body, findQualifiers, em); + + TModelList result = InquiryHelper.getTModelListFromKeys(body, findQualifiers, em, keysFound); + + tx.rollback(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(InquiryQuery.FIND_TMODEL, QueryStatus.SUCCESS, procTime); + + return result; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + + public BindingDetail getBindingDetail(GetBindingDetail body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + try { + new ValidateInquiry(null).validateGetBindingDetail(body); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(InquiryQuery.FIND_TMODEL, QueryStatus.FAILED, procTime); + throw drfm; + } + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + if (isAuthenticated()) + this.getEntityPublisher(em, body.getAuthInfo()); + + BindingDetail result = new BindingDetail(); + + List bindingKeyList = body.getBindingKey(); + for (String bindingKey : bindingKeyList) { + org.apache.juddi.model.BindingTemplate modelBindingTemplate = null; + try { + modelBindingTemplate = em.find(org.apache.juddi.model.BindingTemplate.class, bindingKey); + } catch (ClassCastException e) {} + if (modelBindingTemplate == null) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BindingTemplateNotFound", bindingKey)); + + org.uddi.api_v3.BindingTemplate apiBindingTemplate = new org.uddi.api_v3.BindingTemplate(); + + MappingModelToApi.mapBindingTemplate(modelBindingTemplate, apiBindingTemplate); + + result.getBindingTemplate().add(apiBindingTemplate); + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(InquiryQuery.GET_BINDINGDETAIL, QueryStatus.SUCCESS, procTime); + + return result; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + + public BusinessDetail getBusinessDetail(GetBusinessDetail body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + try { + new ValidateInquiry(null).validateGetBusinessDetail(body); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(InquiryQuery.GET_BUSINESSDETAIL, QueryStatus.FAILED, procTime); + throw drfm; + } + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + if (isAuthenticated()) + this.getEntityPublisher(em, body.getAuthInfo()); + + BusinessDetail result = new BusinessDetail(); + + List businessKeyList = body.getBusinessKey(); + for (String businessKey : businessKeyList) { + org.apache.juddi.model.BusinessEntity modelBusinessEntity = null; + try { + modelBusinessEntity = em.find(org.apache.juddi.model.BusinessEntity.class, businessKey); + } catch (ClassCastException e) {} + if (modelBusinessEntity == null) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BusinessNotFound", businessKey)); + + org.uddi.api_v3.BusinessEntity apiBusinessEntity = new org.uddi.api_v3.BusinessEntity(); + + MappingModelToApi.mapBusinessEntity(modelBusinessEntity, apiBusinessEntity); + + result.getBusinessEntity().add(apiBusinessEntity); + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(InquiryQuery.GET_BUSINESSDETAIL, QueryStatus.SUCCESS, procTime); + + return result; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + + public OperationalInfos getOperationalInfo(GetOperationalInfo body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + try { + new ValidateInquiry(null).validateGetOperationalInfo(body); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(InquiryQuery.GET_OPERATIONALINFO, QueryStatus.FAILED, procTime); + throw drfm; + } + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + if (isAuthenticated()) + this.getEntityPublisher(em, body.getAuthInfo()); + + OperationalInfos result = new OperationalInfos(); + + List entityKeyList = body.getEntityKey(); + for (String entityKey : entityKeyList) { + org.apache.juddi.model.UddiEntity modelUddiEntity = null; + try { + modelUddiEntity = em.find(org.apache.juddi.model.UddiEntity.class, entityKey); + } catch (ClassCastException e) {} + if (modelUddiEntity == null) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.EntityNotFound", entityKey)); + + org.uddi.api_v3.OperationalInfo apiOperationalInfo = new org.uddi.api_v3.OperationalInfo(); + + MappingModelToApi.mapOperationalInfo(modelUddiEntity, apiOperationalInfo); + + result.getOperationalInfo().add(apiOperationalInfo); + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(InquiryQuery.GET_OPERATIONALINFO, QueryStatus.SUCCESS, procTime); + + return result; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + + public ServiceDetail getServiceDetail(GetServiceDetail body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + try { + new ValidateInquiry(null).validateGetServiceDetail(body); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(InquiryQuery.GET_SERVICEDETAIL, QueryStatus.FAILED, procTime); + throw drfm; + } + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + if (isAuthenticated()) + this.getEntityPublisher(em, body.getAuthInfo()); + + ServiceDetail result = new ServiceDetail(); + + List serviceKeyList = body.getServiceKey(); + for (String serviceKey : serviceKeyList) { + org.apache.juddi.model.BusinessService modelBusinessService = null; + try { + modelBusinessService = em.find(org.apache.juddi.model.BusinessService.class, serviceKey); + } catch (ClassCastException e){} + if (modelBusinessService == null) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ServiceNotFound", serviceKey)); + + org.uddi.api_v3.BusinessService apiBusinessService = new org.uddi.api_v3.BusinessService(); + + MappingModelToApi.mapBusinessService(modelBusinessService, apiBusinessService); + + result.getBusinessService().add(apiBusinessService); + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(InquiryQuery.GET_SERVICEDETAIL, QueryStatus.SUCCESS, procTime); + + return result; + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + + public TModelDetail getTModelDetail(GetTModelDetail body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + try { + new ValidateInquiry(null).validateGetTModelDetail(body); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(InquiryQuery.GET_TMODELDETAIL, QueryStatus.FAILED, procTime); + throw drfm; + } + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + if (isAuthenticated()) + this.getEntityPublisher(em, body.getAuthInfo()); + + TModelDetail result = new TModelDetail(); + + List tmodelKeyList = body.getTModelKey(); + for (String tmodelKey : tmodelKeyList) { + org.apache.juddi.model.Tmodel modelTModel = null; + try { + modelTModel = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey); + } catch (ClassCastException e) {} + if (modelTModel == null) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.TModelNotFound", tmodelKey)); + + org.uddi.api_v3.TModel apiTModel = new org.uddi.api_v3.TModel(); + + MappingModelToApi.mapTModel(modelTModel, apiTModel); + + result.getTModel().add(apiTModel); + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(InquiryQuery.GET_TMODELDETAIL, QueryStatus.SUCCESS, procTime); + + return result; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + private boolean isAuthenticated() { + boolean result = false; + try { + result = AppConfig.getConfiguration().getBoolean(Property.JUDDI_AUTHENTICATE_INQUIRY); + } catch (ConfigurationException e) { + log.error("Configuration exception occurred retrieving: " + Property.JUDDI_AUTHENTICATE_INQUIRY, e); + } + return result; + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIPublicationImpl.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIPublicationImpl.java similarity index 98% rename from juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIPublicationImpl.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIPublicationImpl.java index b6ace8199..0595ecf60 100644 --- a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIPublicationImpl.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIPublicationImpl.java @@ -1,1603 +1,1603 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.List; -import javax.jws.WebService; -import javax.persistence.EntityManager; -import javax.persistence.EntityTransaction; -import javax.persistence.Query; -import javax.xml.bind.JAXB; -import javax.xml.datatype.DatatypeConfigurationException; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.ws.Holder; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.api.util.PublicationQuery; -import org.apache.juddi.api.util.QueryStatus; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.PersistenceManager; -import org.apache.juddi.config.Property; -import org.apache.juddi.mapping.MappingApiToModel; -import org.apache.juddi.mapping.MappingModelToApi; -import org.apache.juddi.model.BindingTemplate; -import org.apache.juddi.model.BusinessEntity; -import org.apache.juddi.model.BusinessService; -import org.apache.juddi.model.ChangeRecord; -import org.apache.juddi.model.Signature; -import org.apache.juddi.model.Tmodel; -import org.apache.juddi.model.UddiEntityPublisher; -import org.apache.juddi.query.FetchBusinessEntitiesQuery; -import org.apache.juddi.query.FetchTModelsQuery; -import org.apache.juddi.query.FindBusinessByPublisherQuery; -import org.apache.juddi.query.FindPublisherAssertionByBusinessQuery; -import org.apache.juddi.query.FindTModelByPublisherQuery; -import org.apache.juddi.query.TModelQuery; -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.apache.juddi.replication.ReplicationNotifier; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.FatalErrorException; -import org.apache.juddi.v3.error.InvalidValueException; -import org.apache.juddi.validation.ValidatePublish; -import org.uddi.api_v3.AddPublisherAssertions; -import org.uddi.api_v3.AssertionStatusItem; -import org.uddi.api_v3.BindingDetail; -import org.uddi.api_v3.BusinessDetail; -import org.uddi.api_v3.CompletionStatus; -import org.uddi.api_v3.DeleteBinding; -import org.uddi.api_v3.DeleteBusiness; -import org.uddi.api_v3.DeletePublisherAssertions; -import org.uddi.api_v3.DeleteService; -import org.uddi.api_v3.DeleteTModel; -import org.uddi.api_v3.GetRegisteredInfo; -import org.uddi.api_v3.InfoSelection; -import org.uddi.api_v3.ListDescription; -import org.uddi.api_v3.OperationalInfo; -import org.uddi.api_v3.PublisherAssertion; -import org.uddi.api_v3.RegisteredInfo; -import org.uddi.api_v3.SaveBinding; -import org.uddi.api_v3.SaveBusiness; -import org.uddi.api_v3.SaveService; -import org.uddi.api_v3.SaveTModel; -import org.uddi.api_v3.ServiceDetail; -import org.uddi.api_v3.TModel; -import org.uddi.api_v3.TModelDetail; -import org.uddi.repl_v3.ChangeRecordDelete; -import org.uddi.repl_v3.ChangeRecordDeleteAssertion; -import org.uddi.repl_v3.ChangeRecordHide; -import org.uddi.repl_v3.ChangeRecordIDType; -import org.uddi.repl_v3.ChangeRecordNewData; -import org.uddi.repl_v3.ChangeRecordNewDataConditional; -import org.uddi.repl_v3.ChangeRecordPublisherAssertion; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.v3_service.UDDIPublicationPortType; - -/** - * This class implements the UDDI Publication Service - * - * @author Jeff Faath (and many others) - * @author Alex O'Ree added support for - * replication and several bug fixes - */ -@WebService(serviceName = "UDDIPublicationService", - endpointInterface = "org.uddi.v3_service.UDDIPublicationPortType", - targetNamespace = "urn:uddi-org:api_v3_portType") -public class UDDIPublicationImpl extends AuthenticatedService implements UDDIPublicationPortType { - - private static Log log = LogFactory.getLog(UDDIInquiryImpl.class); - private UDDIServiceCounter serviceCounter; - - - public UDDIPublicationImpl() { - super(); - serviceCounter = ServiceCounterLifecycleResource.getServiceCounter(UDDIPublicationImpl.class); - - } - - @Override - public void addPublisherAssertions(AddPublisherAssertions body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); - - new ValidatePublish(publisher).validateAddPublisherAssertions(em, body); - - List apiPubAssertionList = body.getPublisherAssertion(); - List changes = new ArrayList(); - for (org.uddi.api_v3.PublisherAssertion apiPubAssertion : apiPubAssertionList) { - - org.apache.juddi.model.PublisherAssertion modelPubAssertion = new org.apache.juddi.model.PublisherAssertion(); - - MappingApiToModel.mapPublisherAssertion(apiPubAssertion, modelPubAssertion); - - org.apache.juddi.model.PublisherAssertion existingPubAssertion = em.find(modelPubAssertion.getClass(), modelPubAssertion.getId()); - boolean persistNewAssertion = true; - if (existingPubAssertion != null) { - if (modelPubAssertion.getTmodelKey().equalsIgnoreCase(existingPubAssertion.getTmodelKey()) - && modelPubAssertion.getKeyName().equalsIgnoreCase(existingPubAssertion.getKeyName()) - && modelPubAssertion.getKeyValue().equalsIgnoreCase(existingPubAssertion.getKeyValue())) { - // This pub assertion is already been "asserted". Simply need to set the "check" value on the existing (and persistent) assertion - if (publisher.isOwner(existingPubAssertion.getBusinessEntityByFromKey())) { - existingPubAssertion.setFromCheck("true"); - } - if (publisher.isOwner(existingPubAssertion.getBusinessEntityByToKey())) { - existingPubAssertion.setToCheck("true"); - } - //it's also possible that the signatures have changed - removeExistingPublisherAssertionSignatures(existingPubAssertion.getBusinessEntityByFromKey().getEntityKey(), existingPubAssertion.getBusinessEntityByToKey().getEntityKey(), em); - savePushliserAssertionSignatures(existingPubAssertion.getBusinessEntityByFromKey().getEntityKey(), existingPubAssertion.getBusinessEntityByToKey().getEntityKey(), modelPubAssertion.getSignatures(), em); - - em.merge(existingPubAssertion); - persistNewAssertion = false; - changes.add(getChangeRecord_deletePublisherAssertion(apiPubAssertion, getNode(), existingPubAssertion.getToCheck().equalsIgnoreCase("false"), existingPubAssertion.getFromCheck().equalsIgnoreCase("false"), System.currentTimeMillis())); - } else { - // Otherwise, it is a new relationship between these entities. Remove the old one so the new one can be added. - // TODO: the model only seems to allow one assertion per two business (primary key is fromKey and toKey). Spec seems to imply as - // many relationships as desired (the differentiator would be the keyedRef values). - removeExistingPublisherAssertionSignatures(existingPubAssertion.getBusinessEntityByFromKey().getEntityKey(), existingPubAssertion.getBusinessEntityByToKey().getEntityKey(), em); - em.remove(existingPubAssertion); - changes.add(getChangeRecord_deletePublisherAssertion(apiPubAssertion, getNode(), true, true, System.currentTimeMillis())); - } - } - - if (persistNewAssertion) { - org.apache.juddi.model.BusinessEntity beFrom = em.find(org.apache.juddi.model.BusinessEntity.class, modelPubAssertion.getId().getFromKey()); - org.apache.juddi.model.BusinessEntity beTo = em.find(org.apache.juddi.model.BusinessEntity.class, modelPubAssertion.getId().getToKey()); - modelPubAssertion.setBusinessEntityByFromKey(beFrom); - modelPubAssertion.setBusinessEntityByToKey(beTo); - - modelPubAssertion.setFromCheck("false"); - modelPubAssertion.setToCheck("false"); - - if (publisher.isOwner(modelPubAssertion.getBusinessEntityByFromKey())) { - modelPubAssertion.setFromCheck("true"); - } - if (publisher.isOwner(modelPubAssertion.getBusinessEntityByToKey())) { - modelPubAssertion.setToCheck("true"); - } - modelPubAssertion.setModified(new Date()); - savePushliserAssertionSignatures(modelPubAssertion.getBusinessEntityByFromKey().getEntityKey(), modelPubAssertion.getBusinessEntityByToKey().getEntityKey(), modelPubAssertion.getSignatures(), em); - - em.persist(modelPubAssertion); - - changes.add(getChangeRecord_NewAssertion(apiPubAssertion, modelPubAssertion, getNode())); - - } - - } - - tx.commit(); - for (int i = 0; i < changes.size(); i++) { - ReplicationNotifier.enqueue(changes.get(i)); - } - - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.ADD_PUBLISHERASSERTIONS, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.ADD_PUBLISHERASSERTIONS, QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - public void deleteBinding(DeleteBinding body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); - - new ValidatePublish(publisher).validateDeleteBinding(em, body); - - List entityKeyList = body.getBindingKey(); - List changes = new ArrayList(); - for (String entityKey : entityKeyList) { - deleteBinding(entityKey, em); - changes.add(getChangeRecord_deleteBinding(entityKey, getNode())); - } - tx.commit(); - for (int i = 0; i < changes.size(); i++) { - ReplicationNotifier.enqueue(changes.get(i)); - } - - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.DELETE_BINDING, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.DELETE_BINDING, QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - /** - * deletes the referenced object, assuming authorization rules are - * already processed and there is already an open transaction - * - * @param entityKey - * @param em - * @throws DispositionReportFaultMessage - */ - protected void deleteBinding(String entityKey, EntityManager em) throws DispositionReportFaultMessage { - - Object obj = em.find(org.apache.juddi.model.BindingTemplate.class, entityKey); - - ((org.apache.juddi.model.BindingTemplate) obj).getBusinessService().setModifiedIncludingChildren(new Date()); - // JUDDI-421: now the businessEntity parent will have it's modifiedIncludingChildren set - ((org.apache.juddi.model.BindingTemplate) obj).getBusinessService().getBusinessEntity().setModifiedIncludingChildren(new Date()); - - em.remove(obj); - - } - - public void deleteBusiness(DeleteBusiness body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); - - new ValidatePublish(publisher).validateDeleteBusiness(em, body); - - List entityKeyList = body.getBusinessKey(); - List changes = new ArrayList(); - for (String entityKey : entityKeyList) { - deleteBusiness(entityKey, em); - changes.add(getChangeRecord_deleteBusiness(entityKey, getNode())); - } - - tx.commit(); - for (int i = 0; i < changes.size(); i++) { - ReplicationNotifier.enqueue(changes.get(i)); - } - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.DELETE_BUSINESS, QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.DELETE_BUSINESS, QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - /** - * deletes the referenced object, assuming authorization rules are - * already processed and there is already an open transaction - * - * @param entityKey - * @param em - * @throws DispositionReportFaultMessage - */ - protected void deleteBusiness(String key, EntityManager em) throws DispositionReportFaultMessage { - Object obj = em.find(org.apache.juddi.model.BusinessEntity.class, key); - em.remove(obj); - } - - public void deletePublisherAssertions(DeletePublisherAssertions body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); - - new ValidatePublish(publisher).validateDeletePublisherAssertions(em, body); - - List entityList = body.getPublisherAssertion(); - List changes = new ArrayList(); - for (org.uddi.api_v3.PublisherAssertion entity : entityList) { - org.apache.juddi.model.PublisherAssertion modelPubAssertion = new org.apache.juddi.model.PublisherAssertion(); - - MappingApiToModel.mapPublisherAssertion(entity, modelPubAssertion); - - org.apache.juddi.model.PublisherAssertion existingPubAssertion = em.find(org.apache.juddi.model.PublisherAssertion.class, - modelPubAssertion.getId()); - if (existingPubAssertion == null) { - throw new InvalidValueException(new ErrorMessage("E_assertionNotFound")); - } - - boolean fromkey = publisher.isOwner(em.find(BusinessEntity.class, entity.getFromKey())); - boolean tokey = publisher.isOwner(em.find(BusinessEntity.class, entity.getToKey())); - if (fromkey) { - existingPubAssertion.setFromCheck("false"); - } - if (tokey) { - existingPubAssertion.setToCheck("false"); - } - if ("false".equalsIgnoreCase(existingPubAssertion.getToCheck()) - && "false".equalsIgnoreCase(existingPubAssertion.getFromCheck())) { - logger.info("Publisher assertion updated database via replication"); - removeExistingPublisherAssertionSignatures(existingPubAssertion.getBusinessEntityByFromKey().getEntityKey(), existingPubAssertion.getBusinessEntityByToKey().getEntityKey(), em); - em.remove(existingPubAssertion); - } else { - existingPubAssertion.setModified(new Date()); - logger.info("Publisher assertion updated database via replication"); - removeExistingPublisherAssertionSignatures(existingPubAssertion.getBusinessEntityByFromKey().getEntityKey(), existingPubAssertion.getBusinessEntityByToKey().getEntityKey(), em); - savePushliserAssertionSignatures(existingPubAssertion.getBusinessEntityByFromKey().getEntityKey(), - existingPubAssertion.getBusinessEntityByToKey().getEntityKey(), modelPubAssertion.getSignatures(), em); - em.persist(existingPubAssertion); - } - - changes.add(getChangeRecord_deletePublisherAssertion(entity, getNode(), tokey, fromkey, existingPubAssertion.getModified().getTime())); - } - - tx.commit(); - for (int i = 0; i < changes.size(); i++) { - ReplicationNotifier.enqueue(changes.get(i)); - } - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.DELETE_PUBLISHERASSERTIONS, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.DELETE_PUBLISHERASSERTIONS, QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - /** - * deletes the referenced object, assuming authorization rules are - * already processed and there is already an open transaction. this is - * primarily used to support replication calls, i.e. another node just - * changed a PA record and let us know - * - * @param entityKey - * @param em - * @throws DispositionReportFaultMessage - */ - protected void deletePublisherAssertion(org.uddi.repl_v3.ChangeRecordDeleteAssertion entity, EntityManager em) throws DispositionReportFaultMessage { - - org.apache.juddi.model.PublisherAssertion modelPubAssertion = new org.apache.juddi.model.PublisherAssertion(); - - MappingApiToModel.mapPublisherAssertion(entity.getPublisherAssertion(), modelPubAssertion); - - org.apache.juddi.model.PublisherAssertion existingPubAssertion = em.find(org.apache.juddi.model.PublisherAssertion.class, - modelPubAssertion.getId()); - - if (existingPubAssertion == null) { - throw new FatalErrorException(new ErrorMessage("E_assertionNotFound")); - } - boolean fromkey = entity.isFromBusinessCheck();// publisher.isOwner(em.find(BusinessEntity.class, entity.getFromKey())); - boolean tokey = entity.isToBusinessCheck();// publisher.isOwner(em.find(BusinessEntity.class, entity.getToKey())); - if (fromkey) { - existingPubAssertion.setFromCheck("false"); - } - if (tokey) { - existingPubAssertion.setToCheck("false"); - } - if ("false".equalsIgnoreCase(existingPubAssertion.getToCheck()) - && "false".equalsIgnoreCase(existingPubAssertion.getFromCheck())) { - logger.info("Deletion of publisher assertion from database via replication"); - removeExistingPublisherAssertionSignatures(existingPubAssertion.getBusinessEntityByFromKey().getEntityKey(), existingPubAssertion.getBusinessEntityByToKey().getEntityKey(), em); - em.remove(existingPubAssertion); - } else { - existingPubAssertion.setModified(new Date()); - logger.info("Publisher assertion updated database via replication"); - removeExistingPublisherAssertionSignatures(existingPubAssertion.getBusinessEntityByFromKey().getEntityKey(), existingPubAssertion.getBusinessEntityByToKey().getEntityKey(), em); - savePushliserAssertionSignatures(existingPubAssertion.getBusinessEntityByFromKey().getEntityKey(), - existingPubAssertion.getBusinessEntityByToKey().getEntityKey(), modelPubAssertion.getSignatures(), em); - em.persist(existingPubAssertion); - } - - } - - public void deleteService(DeleteService body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); - - new ValidatePublish(publisher).validateDeleteService(em, body); - - List entityKeyList = body.getServiceKey(); - List changes = new ArrayList(); - for (String entityKey : entityKeyList) { - deleteService(entityKey, em); - changes.add(getChangeRecord_deleteService(entityKey, getNode())); - } - - tx.commit(); - for (int i = 0; i < changes.size(); i++) { - ReplicationNotifier.enqueue(changes.get(i)); - } - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.DELETE_SERVICE, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.DELETE_SERVICE, QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - /** - * deletes the referenced object, assuming authorization rules are - * already processed and there is already an open transaction - * - * @param entityKey - * @param em - * @throws DispositionReportFaultMessage - */ - protected void deleteService(String key, EntityManager em) throws DispositionReportFaultMessage { - Object obj = em.find(org.apache.juddi.model.BusinessService.class, key); - //((org.apache.juddi.model.BusinessService) obj).getBusinessEntity().setModifiedIncludingChildren(new Date()); - if (obj != null) { - em.remove(obj); - } else { - logger.warn("Unable to remove service with the key '" + key + "', it doesn't exist in the database"); - } - } - - /** - * {@inheritDoc } - */ - @Override - public void deleteTModel(DeleteTModel body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); - - new ValidatePublish(publisher).validateDeleteTModel(em, body); - - // tModels are only lazily deleted! - List entityKeyList = body.getTModelKey(); - List changes = new ArrayList(); - for (String entityKey : entityKeyList) { - deleteTModel(entityKey, em); - changes.add(getChangeRecord_deleteTModelHide(entityKey, getNode())); - } - - tx.commit(); - - for (int i = 0; i < changes.size(); i++) { - ReplicationNotifier.enqueue(changes.get(i)); - } - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.DELETE_TMODEL, QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.DELETE_TMODEL, QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - /** - * deletes the referenced object, assuming authorization rules are - * already processed and there is already an open transaction - * - * @param entityKey - * @param em - * @throws DispositionReportFaultMessage - */ - protected void deleteTModel(String key, EntityManager em) { - Object obj = em.find(org.apache.juddi.model.Tmodel.class, key); - ((org.apache.juddi.model.Tmodel) obj).setDeleted(true); - } - - /** - * {@inheritDoc } - */ - @Override - public List getAssertionStatusReport(String authInfo, - CompletionStatus completionStatus) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); - - List result = PublicationHelper.getAssertionStatusItemList(publisher, completionStatus, em); - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.GET_ASSERTIONSTATUSREPORT, - QueryStatus.SUCCESS, procTime); - - return result; - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.GET_ASSERTIONSTATUSREPORT, QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - public List getPublisherAssertions(String authInfo) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); - - List result = new ArrayList(0); - - List businessKeysFound = null; - businessKeysFound = FindBusinessByPublisherQuery.select(em, null, publisher, businessKeysFound); - - List pubAssertionList = FindPublisherAssertionByBusinessQuery.select(em, businessKeysFound, null); - if (pubAssertionList != null) { - for (org.apache.juddi.model.PublisherAssertion modelPubAssertion : pubAssertionList) { - org.uddi.api_v3.PublisherAssertion apiPubAssertion = new org.uddi.api_v3.PublisherAssertion(); - - MappingModelToApi.mapPublisherAssertion(modelPubAssertion, apiPubAssertion); - - result.add(apiPubAssertion); - } - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.GET_PUBLISHERASSERTIONS, - QueryStatus.SUCCESS, procTime); - return result; - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.GET_PUBLISHERASSERTIONS, - QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - /** - * {@inheritdoc} - * - */ - public RegisteredInfo getRegisteredInfo(GetRegisteredInfo body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); - - new ValidatePublish(publisher).validateRegisteredInfo(body); - - List businessKeysFound = null; - businessKeysFound = FindBusinessByPublisherQuery.select(em, null, publisher, businessKeysFound); - - List tmodelKeysFound = null; - - if (body.getInfoSelection().equals(InfoSelection.HIDDEN)) { - tmodelKeysFound = FindTModelByPublisherQuery.select(em, null, publisher, tmodelKeysFound, new DynamicQuery.Parameter(TModelQuery.ENTITY_ALIAS + ".deleted", Boolean.TRUE, DynamicQuery.PREDICATE_EQUALS)); - } else if (body.getInfoSelection().equals(InfoSelection.VISIBLE)) { - tmodelKeysFound = FindTModelByPublisherQuery.select(em, null, publisher, tmodelKeysFound, new DynamicQuery.Parameter(TModelQuery.ENTITY_ALIAS + ".deleted", Boolean.FALSE, DynamicQuery.PREDICATE_EQUALS)); - } else { - tmodelKeysFound = FindTModelByPublisherQuery.select(em, null, publisher, tmodelKeysFound); - } - - RegisteredInfo result = new RegisteredInfo(); - - // Sort and retrieve the final results - List queryResults = FetchBusinessEntitiesQuery.select(em, new FindQualifiers(), businessKeysFound, null, null, null); - if (queryResults.size() > 0) { - result.setBusinessInfos(new org.uddi.api_v3.BusinessInfos()); - - for (Object item : queryResults) { - org.apache.juddi.model.BusinessEntity modelBusinessEntity = (org.apache.juddi.model.BusinessEntity) item; - org.uddi.api_v3.BusinessInfo apiBusinessInfo = new org.uddi.api_v3.BusinessInfo(); - - MappingModelToApi.mapBusinessInfo(modelBusinessEntity, apiBusinessInfo); - - result.getBusinessInfos().getBusinessInfo().add(apiBusinessInfo); - } - } - - // Sort and retrieve the final results - queryResults = FetchTModelsQuery.select(em, new FindQualifiers(), tmodelKeysFound, null, null, null); - if (queryResults.size() > 0) { - result.setTModelInfos(new org.uddi.api_v3.TModelInfos()); - - for (Object item : queryResults) { - org.apache.juddi.model.Tmodel modelTModel = (org.apache.juddi.model.Tmodel) item; - org.uddi.api_v3.TModelInfo apiTModelInfo = new org.uddi.api_v3.TModelInfo(); - - MappingModelToApi.mapTModelInfo(modelTModel, apiTModelInfo); - - result.getTModelInfos().getTModelInfo().add(apiTModelInfo); - } - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.GET_REGISTEREDINFO, - QueryStatus.SUCCESS, procTime); - - return result; - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.GET_REGISTEREDINFO, - QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - /** - * {@inheritdoc} - * - */ - public BindingDetail saveBinding(SaveBinding body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); - publisher.populateKeyGeneratorKeys(em); - ValidatePublish validator = new ValidatePublish(publisher); - validator.validateSaveBinding(em, body, null, publisher); - - BindingDetail result = new BindingDetail(); - result.setListDescription(new ListDescription()); - List apiBindingTemplateList = body.getBindingTemplate(); - List changes = new ArrayList(); - - for (org.uddi.api_v3.BindingTemplate apiBindingTemplate : apiBindingTemplateList) { - - org.apache.juddi.model.BindingTemplate modelBindingTemplate = new org.apache.juddi.model.BindingTemplate(); - - org.apache.juddi.model.BusinessService modelBusinessService = new org.apache.juddi.model.BusinessService(); - modelBusinessService.setEntityKey(apiBindingTemplate.getServiceKey()); - - MappingApiToModel.mapBindingTemplate(apiBindingTemplate, modelBindingTemplate, modelBusinessService); - - setOperationalInfo(em, modelBindingTemplate, publisher, true); - - em.persist(modelBindingTemplate); - - result.getBindingTemplate().add(apiBindingTemplate); - result.getListDescription().setActualCount(result.getListDescription().getActualCount() + 1); - result.getListDescription().setIncludeCount(result.getListDescription().getIncludeCount() + 1); - validator.validateSaveBindingMax(em, modelBindingTemplate.getBusinessService().getEntityKey()); - changes.add(getChangeRecord(modelBindingTemplate, apiBindingTemplate, getNode())); - } - - tx.commit(); - for (int i = 0; i < changes.size(); i++) { - ReplicationNotifier.enqueue(changes.get(i)); - } - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.SAVE_BINDING, - QueryStatus.SUCCESS, procTime); - - return result; - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.SAVE_BINDING, - QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - /** - * {@inheritdoc} - * - */ - public BusinessDetail saveBusiness(SaveBusiness body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); - publisher.populateKeyGeneratorKeys(em); - ValidatePublish validator = new ValidatePublish(publisher); - validator.validateSaveBusiness(em, body, null, publisher); - - BusinessDetail result = new BusinessDetail(); - - List apiBusinessEntityList = body.getBusinessEntity(); - List changes = new ArrayList(); - - for (org.uddi.api_v3.BusinessEntity apiBusinessEntity : apiBusinessEntityList) { - - org.apache.juddi.model.BusinessEntity modelBusinessEntity = new org.apache.juddi.model.BusinessEntity(); - - MappingApiToModel.mapBusinessEntity(apiBusinessEntity, modelBusinessEntity); - - setOperationalInfo(em, modelBusinessEntity, publisher); - log.debug("Saving business " + modelBusinessEntity.getEntityKey()); - - em.persist(modelBusinessEntity); - changes.add(getChangeRecord(modelBusinessEntity, apiBusinessEntity, getNode())); - result.getBusinessEntity().add(apiBusinessEntity); - } - - //check how many business this publisher owns. - validator.validateSaveBusinessMax(em); - - tx.commit(); - for (int i = 0; i < changes.size(); i++) { - ReplicationNotifier.enqueue(changes.get(i)); - } - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.SAVE_BUSINESS, - QueryStatus.SUCCESS, procTime); - - return result; - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.SAVE_BUSINESS, - QueryStatus.FAILED, procTime); - throw drfm; - } catch (Exception ex) { - StringWriter sw = new StringWriter(); - if (body != null) { - JAXB.marshal(body, sw); - } - log.fatal("unexpected error!" + sw.toString(), ex); - throw new FatalErrorException(new ErrorMessage("E_fatalError", ex.getMessage())); - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - /** - * {@inheritdoc} - * - */ - public ServiceDetail saveService(SaveService body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); - publisher.populateKeyGeneratorKeys(em); - ValidatePublish validator = new ValidatePublish(publisher); - validator.validateSaveService(em, body, null, publisher); - - ServiceDetail result = new ServiceDetail(); - - List apiBusinessServiceList = body.getBusinessService(); - List changes = new ArrayList(); - for (org.uddi.api_v3.BusinessService apiBusinessService : apiBusinessServiceList) { - - org.apache.juddi.model.BusinessService modelBusinessService = new org.apache.juddi.model.BusinessService(); - org.apache.juddi.model.BusinessEntity modelBusinessEntity = new org.apache.juddi.model.BusinessEntity(); - modelBusinessEntity.setEntityKey(apiBusinessService.getBusinessKey()); - - MappingApiToModel.mapBusinessService(apiBusinessService, modelBusinessService, modelBusinessEntity); - - setOperationalInfo(em, modelBusinessService, publisher, false); - - em.persist(modelBusinessService); - - result.getBusinessService().add(apiBusinessService); - - validator.validateSaveServiceMax(em, modelBusinessService.getBusinessEntity().getEntityKey()); - changes.add(getChangeRecord(modelBusinessService, apiBusinessService, getNode())); - } - - tx.commit(); - for (int i = 0; i < changes.size(); i++) { - ReplicationNotifier.enqueue(changes.get(i)); - } - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.SAVE_SERVICE, - QueryStatus.SUCCESS, procTime); - - return result; - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.SAVE_SERVICE, - QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - /** - * {@inheritdoc} - * - */ - @Override - public TModelDetail saveTModel(SaveTModel body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); - publisher.populateKeyGeneratorKeys(em); - new ValidatePublish(publisher).validateSaveTModel(em, body, null, publisher); - - TModelDetail result = new TModelDetail(); - - List apiTModelList = body.getTModel(); - List changes = new ArrayList(); - for (org.uddi.api_v3.TModel apiTModel : apiTModelList) { - - // Object obj=em.find( org.apache.juddi.model.Tmodel.class, apiTModel.getTModelKey()); - //just making changes to an existing tModel, no worries - org.apache.juddi.model.Tmodel modelTModel = new org.apache.juddi.model.Tmodel(); - - MappingApiToModel.mapTModel(apiTModel, modelTModel); - - setOperationalInfo(em, modelTModel, publisher); - - em.persist(modelTModel); - - result.getTModel().add(apiTModel); - changes.add(getChangeRecord(modelTModel, apiTModel, getNode())); - /* - //TODO JUDDI-915 - if (obj != null) { - - changes.add(getChangeRecord(modelTModel, apiTModel, node)); - } else { - //special case for replication, must setup a new data conditional change record - changes.add(getChangeRecordConditional(modelTModel, apiTModel, node)); - }*/ - - } - - tx.commit(); - for (int i = 0; i < changes.size(); i++) { - ReplicationNotifier.enqueue(changes.get(i)); - } - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.SAVE_TMODEL, - QueryStatus.SUCCESS, procTime); - - return result; - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.SAVE_TMODEL, - QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - /** - * {@inheritdoc} - * - */ - @Override - public void setPublisherAssertions(String authInfo, - Holder> publisherAssertion) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - List changes = new ArrayList(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); - - new ValidatePublish(publisher).validateSetPublisherAssertions(em, publisherAssertion); - - List businessKeysFound = null; - businessKeysFound = FindBusinessByPublisherQuery.select(em, null, publisher, businessKeysFound); - - //TODO this has to be reworked to record what was deleted. - // First, identify all previous assertions that need to be removed - List existingAssertions = FindPublisherAssertionByBusinessQuery.select(em, businessKeysFound, null); - - logger.debug(">>>> Existing assertions " + existingAssertions.size() + ", inbound set " + publisherAssertion.value.size()); - List deleteMe = diff(publisherAssertion.value, existingAssertions); - logger.debug(">>>> DIFF size is " + deleteMe.size()); - for (org.apache.juddi.model.PublisherAssertion del : deleteMe) { - logger.debug(">>>> PROCESSING " + del.getBusinessEntityByFromKey().getEntityKey() + " " + del.getBusinessEntityByToKey().getEntityKey()); - boolean from = false; - if (del.getFromCheck() != null) { - del.getFromCheck().equalsIgnoreCase("true"); - } - boolean to = false; - if (del.getToCheck() != null) { - del.getToCheck().equalsIgnoreCase("true"); - } - if (publisher.isOwner(del.getBusinessEntityByFromKey())) { - from = false; - } - if (publisher.isOwner(del.getBusinessEntityByToKey())) { - to = false; - } - PublisherAssertion api = new PublisherAssertion(); - MappingModelToApi.mapPublisherAssertion(del, api); - - if (!to && !from) { - logger.debug(">>>> DELETE ME " + del.getBusinessEntityByFromKey().getEntityKey() + " " + del.getBusinessEntityByToKey().getEntityKey()); - em.remove(del); - } else { - logger.debug(">>>> MERGING ME " + del.getBusinessEntityByFromKey().getEntityKey() + " " + del.getBusinessEntityByToKey().getEntityKey()); - del.setFromCheck(from ? "true" : "false"); - del.setToCheck(to ? "true" : "false"); - del.setModified(new Date()); - em.merge(del); - } - changes.add(getChangeRecord_deletePublisherAssertion(api, getNode(), to, from, System.currentTimeMillis())); - } - //DeletePublisherAssertionByBusinessQuery.delete(em, businessKeysFound); - - // Slate is clean for all assertions involving this publisher, now we simply need to add the new ones (and they will all be "new"). - /*List apiPubAssertionList = publisherAssertion.value; - - - for (org.uddi.api_v3.PublisherAssertion apiPubAssertion : apiPubAssertionList) { - - org.apache.juddi.model.PublisherAssertion modelPubAssertion = new org.apache.juddi.model.PublisherAssertion(); - - MappingApiToModel.mapPublisherAssertion(apiPubAssertion, modelPubAssertion); - - org.apache.juddi.model.BusinessEntity beFrom = em.find(org.apache.juddi.model.BusinessEntity.class, modelPubAssertion.getId().getFromKey()); - org.apache.juddi.model.BusinessEntity beTo = em.find(org.apache.juddi.model.BusinessEntity.class, modelPubAssertion.getId().getToKey()); - modelPubAssertion.setBusinessEntityByFromKey(beFrom); - modelPubAssertion.setBusinessEntityByToKey(beTo); - - modelPubAssertion.setFromCheck("false"); - modelPubAssertion.setToCheck("false"); - - if (publisher.isOwner(modelPubAssertion.getBusinessEntityByFromKey())) { - modelPubAssertion.setFromCheck("true"); - } - if (publisher.isOwner(modelPubAssertion.getBusinessEntityByToKey())) { - modelPubAssertion.setToCheck("true"); - } - em.persist(modelPubAssertion); - - changes.add(getChangeRecord_NewAssertion(apiPubAssertion, modelPubAssertion, node)); - - }*/ - tx.commit(); - if (!publisherAssertion.value.isEmpty()) { - AddPublisherAssertions addPublisherAssertions = new AddPublisherAssertions(); - addPublisherAssertions.setAuthInfo(authInfo); - addPublisherAssertions.getPublisherAssertion().addAll(publisherAssertion.value); - addPublisherAssertions(addPublisherAssertions); - } - for (int i = 0; i < changes.size(); i++) { - ReplicationNotifier.enqueue(changes.get(i)); - } - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.SET_PUBLISHERASSERTIONS, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(PublicationQuery.SET_PUBLISHERASSERTIONS, - QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - private void setOperationalInfo(EntityManager em, org.apache.juddi.model.BusinessEntity uddiEntity, UddiEntityPublisher publisher) throws DispositionReportFaultMessage { - - uddiEntity.setAuthorizedName(publisher.getAuthorizedName()); - - Date now = new Date(); - uddiEntity.setModified(now); - uddiEntity.setModifiedIncludingChildren(now); - - String nodeId = ""; - try { - nodeId = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID); - } catch (ConfigurationException ce) { - throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval", Property.JUDDI_NODE_ID)); - } - uddiEntity.setNodeId(nodeId); - - org.apache.juddi.model.BusinessEntity existingUddiEntity = em.find(uddiEntity.getClass(), uddiEntity.getEntityKey()); - if (existingUddiEntity != null) { - uddiEntity.setCreated(existingUddiEntity.getCreated()); - } else { - uddiEntity.setCreated(now); - } - - List serviceList = uddiEntity.getBusinessServices(); - for (org.apache.juddi.model.BusinessService service : serviceList) { - setOperationalInfo(em, service, publisher, true); - } - - if (existingUddiEntity != null) { - em.remove(existingUddiEntity); - } - - } - - private void setOperationalInfo(EntityManager em, org.apache.juddi.model.BusinessService uddiEntity, UddiEntityPublisher publisher, boolean isChild) throws DispositionReportFaultMessage { - - uddiEntity.setAuthorizedName(publisher.getAuthorizedName()); - - Date now = new Date(); - uddiEntity.setModified(now); - uddiEntity.setModifiedIncludingChildren(now); - - if (!isChild) { - org.apache.juddi.model.BusinessEntity parent = em.find(org.apache.juddi.model.BusinessEntity.class, uddiEntity.getBusinessEntity().getEntityKey()); - parent.setModifiedIncludingChildren(now); - em.persist(parent); - } - - String nodeId = ""; - try { - nodeId = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID); - } catch (ConfigurationException ce) { - throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval", Property.JUDDI_NODE_ID)); - } - uddiEntity.setNodeId(nodeId); - - org.apache.juddi.model.BusinessService existingUddiEntity = em.find(uddiEntity.getClass(), uddiEntity.getEntityKey()); - if (existingUddiEntity != null) { - uddiEntity.setCreated(existingUddiEntity.getCreated()); - } else { - uddiEntity.setCreated(now); - } - - List bindingList = uddiEntity.getBindingTemplates(); - for (org.apache.juddi.model.BindingTemplate binding : bindingList) { - setOperationalInfo(em, binding, publisher, true); - } - - if (existingUddiEntity != null) { - em.remove(existingUddiEntity); - } - - } - - private void setOperationalInfo(EntityManager em, org.apache.juddi.model.BindingTemplate uddiEntity, UddiEntityPublisher publisher, boolean isChild) throws DispositionReportFaultMessage { - - uddiEntity.setAuthorizedName(publisher.getAuthorizedName()); - - Date now = new Date(); - uddiEntity.setModified(now); - uddiEntity.setModifiedIncludingChildren(now); - - //if (!isChild) { - org.apache.juddi.model.BusinessService parent = em.find(org.apache.juddi.model.BusinessService.class, uddiEntity.getBusinessService().getEntityKey()); - if (parent != null) { - parent.setModifiedIncludingChildren(now); - em.persist(parent); - - // JUDDI-421: now the businessEntity parent will have it's modifiedIncludingChildren set - org.apache.juddi.model.BusinessEntity businessParent = em.find(org.apache.juddi.model.BusinessEntity.class, parent.getBusinessEntity().getEntityKey()); - if (businessParent != null) { - businessParent.setModifiedIncludingChildren(now); - em.persist(businessParent); - } else { - logger.debug("Parent business is null for saved binding template!"); - } - } else { - logger.debug("Parent service is null for saved binding template!"); - } - // } - - String nodeId = ""; - try { - nodeId = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID); - } catch (ConfigurationException ce) { - throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval", Property.JUDDI_NODE_ID)); - } - uddiEntity.setNodeId(nodeId); - - org.apache.juddi.model.BindingTemplate existingUddiEntity = em.find(uddiEntity.getClass(), uddiEntity.getEntityKey()); - if (existingUddiEntity != null) { - uddiEntity.setCreated(existingUddiEntity.getCreated()); - } else { - uddiEntity.setCreated(now); - } - - if (existingUddiEntity != null) { - em.remove(existingUddiEntity); - } - - } - - private void setOperationalInfo(EntityManager em, org.apache.juddi.model.Tmodel uddiEntity, UddiEntityPublisher publisher) throws DispositionReportFaultMessage { - - uddiEntity.setAuthorizedName(publisher.getAuthorizedName()); - - Date now = new Date(); - uddiEntity.setModified(now); - uddiEntity.setModifiedIncludingChildren(now); - - String nodeId = ""; - try { - nodeId = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID); - } catch (ConfigurationException ce) { - throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval", Property.JUDDI_NODE_ID)); - } - uddiEntity.setNodeId(nodeId); - - org.apache.juddi.model.Tmodel existingUddiEntity = em.find(uddiEntity.getClass(), uddiEntity.getEntityKey()); - if (existingUddiEntity != null) { - uddiEntity.setCreated(existingUddiEntity.getCreated()); - } else { - uddiEntity.setCreated(now); - } - - if (existingUddiEntity != null) { - em.remove(existingUddiEntity); - } - - } - - public static ChangeRecord getChangeRecord(BindingTemplate modelBindingTemplate, org.uddi.api_v3.BindingTemplate api, String node) throws DispositionReportFaultMessage { - ChangeRecord cr = new ChangeRecord(); - cr.setEntityKey(modelBindingTemplate.getEntityKey()); - cr.setNodeID(node); - - cr.setRecordType(ChangeRecord.RecordType.ChangeRecordNewData); - org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); - crapi.setChangeID(new ChangeRecordIDType(node, -1L)); - crapi.setChangeRecordNewData(new ChangeRecordNewData()); - crapi.getChangeRecordNewData().setBindingTemplate(api); - crapi.getChangeRecordNewData().setOperationalInfo(new OperationalInfo()); - MappingModelToApi.mapOperationalInfo(modelBindingTemplate, crapi.getChangeRecordNewData().getOperationalInfo()); - StringWriter sw = new StringWriter(); - JAXB.marshal(crapi, sw); - try { - cr.setContents(sw.toString().getBytes("UTF8")); - } catch (UnsupportedEncodingException ex) { - logger.error(ex); - } - return cr; - } - - public static ChangeRecord getChangeRecord(BusinessService model, org.uddi.api_v3.BusinessService api, String node) throws DispositionReportFaultMessage { - ChangeRecord cr = new ChangeRecord(); - cr.setEntityKey(model.getEntityKey()); - cr.setNodeID(node); - - cr.setRecordType(ChangeRecord.RecordType.ChangeRecordNewData); - org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); - crapi.setChangeID(new ChangeRecordIDType(node, -1L)); - crapi.setChangeRecordNewData(new ChangeRecordNewData()); - crapi.getChangeRecordNewData().setBusinessService(api); - crapi.getChangeRecordNewData().setOperationalInfo(new OperationalInfo()); - MappingModelToApi.mapOperationalInfo(model, crapi.getChangeRecordNewData().getOperationalInfo()); - StringWriter sw = new StringWriter(); - JAXB.marshal(crapi, sw); - try { - cr.setContents(sw.toString().getBytes("UTF8")); - } catch (UnsupportedEncodingException ex) { - logger.error(ex); - } - return cr; - } - - public ChangeRecord getChangeRecord_deleteBusiness(String entityKey, String node) { - ChangeRecord cr = new ChangeRecord(); - cr.setEntityKey(entityKey); - cr.setNodeID(node); - - cr.setRecordType(ChangeRecord.RecordType.ChangeRecordDelete); - org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); - crapi.setChangeID(new ChangeRecordIDType(node, -1L)); - crapi.setChangeRecordDelete(new ChangeRecordDelete()); - crapi.getChangeRecordDelete().setBusinessKey(entityKey); - crapi.getChangeRecordDelete().setModified(df.newXMLGregorianCalendar(new GregorianCalendar())); - - StringWriter sw = new StringWriter(); - JAXB.marshal(crapi, sw); - try { - cr.setContents(sw.toString().getBytes("UTF8")); - } catch (UnsupportedEncodingException ex) { - logger.error(ex); - } - return cr; - } - - public ChangeRecord getChangeRecord_deleteService(String entityKey, String node) { - ChangeRecord cr = new ChangeRecord(); - cr.setEntityKey(entityKey); - cr.setNodeID(node); - - cr.setRecordType(ChangeRecord.RecordType.ChangeRecordDelete); - org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); - crapi.setChangeID(new ChangeRecordIDType(node, -1L)); - crapi.setChangeRecordDelete(new ChangeRecordDelete()); - crapi.getChangeRecordDelete().setServiceKey(entityKey); - crapi.getChangeRecordDelete().setModified(df.newXMLGregorianCalendar(new GregorianCalendar())); - - StringWriter sw = new StringWriter(); - JAXB.marshal(crapi, sw); - try { - cr.setContents(sw.toString().getBytes("UTF8")); - } catch (UnsupportedEncodingException ex) { - logger.error(ex); - } - return cr; - } - - /** - * this is for "hiding" a tmodel, not removing it entirely - * - * @param entityKey - * @param node - * @return - */ - public ChangeRecord getChangeRecord_deleteTModelHide(String entityKey, String node) { - ChangeRecord cr = new ChangeRecord(); - cr.setEntityKey(entityKey); - cr.setNodeID(node); - cr.setRecordType(ChangeRecord.RecordType.ChangeRecordHide); - org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); - crapi.setChangeID(new ChangeRecordIDType(node, -1L)); - - crapi.setChangeRecordHide(new ChangeRecordHide()); - crapi.getChangeRecordHide().setTModelKey(entityKey); - crapi.getChangeRecordHide().setModified(df.newXMLGregorianCalendar(new GregorianCalendar())); - - StringWriter sw = new StringWriter(); - JAXB.marshal(crapi, sw); - //JAXB.marshal(crapi, System.out); - try { - cr.setContents(sw.toString().getBytes("UTF8")); - } catch (UnsupportedEncodingException ex) { - logger.error(ex); - } - return cr; - } - - /** - * this is for deleting a tmodel, not hiding it - * - * @param entityKey - * @param node - * @return - */ - public static ChangeRecord getChangeRecord_deleteTModelDelete(String entityKey, String node, DatatypeFactory df) { - ChangeRecord cr = new ChangeRecord(); - cr.setEntityKey(entityKey); - cr.setNodeID(node); - cr.setRecordType(ChangeRecord.RecordType.ChangeRecordDelete); - org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); - crapi.setChangeID(new ChangeRecordIDType(node, -1L)); - - crapi.setChangeRecordDelete(new ChangeRecordDelete()); - crapi.getChangeRecordDelete().setTModelKey(entityKey); - crapi.getChangeRecordDelete().setModified(df.newXMLGregorianCalendar(new GregorianCalendar())); - - StringWriter sw = new StringWriter(); - JAXB.marshal(crapi, sw); - //JAXB.marshal(crapi, System.out); - try { - cr.setContents(sw.toString().getBytes("UTF8")); - } catch (UnsupportedEncodingException ex) { - logger.error(ex); - } - return cr; - } - - public static ChangeRecord getChangeRecord(BusinessEntity modelBusinessEntity, org.uddi.api_v3.BusinessEntity apiBusinessEntity, String node) throws DispositionReportFaultMessage { - ChangeRecord cr = new ChangeRecord(); - cr.setEntityKey(modelBusinessEntity.getEntityKey()); - cr.setNodeID(node); - - cr.setRecordType(ChangeRecord.RecordType.ChangeRecordNewData); - org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); - crapi.setChangeID(new ChangeRecordIDType(node, -1L)); - crapi.setChangeRecordNewData(new ChangeRecordNewData()); - crapi.getChangeRecordNewData().setBusinessEntity(apiBusinessEntity); - crapi.getChangeRecordNewData().setOperationalInfo(new OperationalInfo()); - MappingModelToApi.mapOperationalInfo(modelBusinessEntity, crapi.getChangeRecordNewData().getOperationalInfo()); - StringWriter sw = new StringWriter(); - JAXB.marshal(crapi, sw); - try { - cr.setContents(sw.toString().getBytes("UTF8")); - } catch (UnsupportedEncodingException ex) { - logger.error(ex); - } - return cr; - } - - public static ChangeRecord getChangeRecord(Tmodel modelBusinessEntity, org.uddi.api_v3.TModel apiBusinessEntity, String node) throws DispositionReportFaultMessage { - ChangeRecord cr = new ChangeRecord(); - if (!apiBusinessEntity.getTModelKey().equals(modelBusinessEntity.getEntityKey())) { - throw new FatalErrorException(new ErrorMessage("E_fatalError", "the model and api keys do not match when saving a tmodel!")); - } - cr.setEntityKey(modelBusinessEntity.getEntityKey()); - cr.setNodeID(node); - - cr.setRecordType(ChangeRecord.RecordType.ChangeRecordNewData); - org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); - crapi.setChangeID(new ChangeRecordIDType(node, -1L)); - crapi.setChangeRecordNewData(new ChangeRecordNewData()); - crapi.getChangeRecordNewData().setTModel(apiBusinessEntity); - crapi.getChangeRecordNewData().getTModel().setTModelKey(modelBusinessEntity.getEntityKey()); - crapi.getChangeRecordNewData().setOperationalInfo(new OperationalInfo()); - MappingModelToApi.mapOperationalInfo(modelBusinessEntity, crapi.getChangeRecordNewData().getOperationalInfo()); - StringWriter sw = new StringWriter(); - JAXB.marshal(crapi, sw); - try { - cr.setContents(sw.toString().getBytes("UTF8")); - } catch (UnsupportedEncodingException ex) { - logger.error(ex); - } - return cr; - } - - public ChangeRecord getChangeRecord_deleteBinding(String entityKey, String node) { - ChangeRecord cr = new ChangeRecord(); - cr.setEntityKey(entityKey); - cr.setNodeID(node); - - cr.setRecordType(ChangeRecord.RecordType.ChangeRecordDelete); - org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); - crapi.setChangeID(new ChangeRecordIDType(node, -1L)); - crapi.setChangeRecordDelete(new ChangeRecordDelete()); - crapi.getChangeRecordDelete().setBindingKey(entityKey); - crapi.getChangeRecordDelete().setModified(df.newXMLGregorianCalendar(new GregorianCalendar())); - - StringWriter sw = new StringWriter(); - JAXB.marshal(crapi, sw); - try { - cr.setContents(sw.toString().getBytes("UTF8")); - } catch (UnsupportedEncodingException ex) { - logger.error(ex); - } - return cr; - } - - public ChangeRecord getChangeRecord_deletePublisherAssertion(PublisherAssertion entity, String node, boolean ToBusinessDelete, boolean FromBusinessDelete, long timestamp) { - ChangeRecord cr = new ChangeRecord(); - - cr.setNodeID(node); - - cr.setRecordType(ChangeRecord.RecordType.ChangeRecordDeleteAssertion); - org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); - crapi.setChangeID(new ChangeRecordIDType(node, -1L)); - crapi.setChangeRecordDeleteAssertion(new ChangeRecordDeleteAssertion()); - crapi.getChangeRecordDeleteAssertion().setPublisherAssertion(entity); - crapi.getChangeRecordDeleteAssertion().setToBusinessCheck(ToBusinessDelete); - crapi.getChangeRecordDeleteAssertion().setFromBusinessCheck(FromBusinessDelete); - GregorianCalendar gcal = new GregorianCalendar(); - gcal.setTimeInMillis(timestamp); - crapi.getChangeRecordDeleteAssertion().setModified(df.newXMLGregorianCalendar(gcal)); - - StringWriter sw = new StringWriter(); - JAXB.marshal(crapi, sw); - try { - cr.setContents(sw.toString().getBytes("UTF8")); - } catch (UnsupportedEncodingException ex) { - logger.error(ex); - } - return cr; - } - - public ChangeRecord getChangeRecord_NewAssertion(PublisherAssertion apiPubAssertion, org.apache.juddi.model.PublisherAssertion modelPubAssertion, String node) { - ChangeRecord cr = new ChangeRecord(); - - cr.setNodeID(node); - - cr.setRecordType(ChangeRecord.RecordType.ChangeRecordPublisherAssertion); - org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); - crapi.setChangeID(new ChangeRecordIDType(node, -1L)); - crapi.setChangeRecordPublisherAssertion(new ChangeRecordPublisherAssertion()); - crapi.getChangeRecordPublisherAssertion().setFromBusinessCheck(modelPubAssertion.getFromCheck().equalsIgnoreCase("true")); - crapi.getChangeRecordPublisherAssertion().setToBusinessCheck(modelPubAssertion.getToCheck().equalsIgnoreCase("true")); - crapi.getChangeRecordPublisherAssertion().setPublisherAssertion(apiPubAssertion); - - crapi.getChangeRecordPublisherAssertion().setModified(df.newXMLGregorianCalendar(new GregorianCalendar())); - - StringWriter sw = new StringWriter(); - JAXB.marshal(crapi, sw); - try { - cr.setContents(sw.toString().getBytes("UTF8")); - } catch (UnsupportedEncodingException ex) { - logger.error(ex); - } - return cr; - } - - /** - * - * @param value keep these - * @param existingAssertions return a list of these that are NOT in - * 'value' - * @return - * @throws DispositionReportFaultMessage - */ - private List diff(List value, List existingAssertions) throws DispositionReportFaultMessage { - List ret = new ArrayList(); - if (value == null || value.isEmpty()) { - return existingAssertions; - } - if (existingAssertions == null) { - return new ArrayList(); - } - for (org.apache.juddi.model.PublisherAssertion model : existingAssertions) { - - boolean found = false; - for (PublisherAssertion paapi : value) { - if (model.getBusinessEntityByFromKey().getEntityKey().equalsIgnoreCase(paapi.getFromKey()) - && model.getBusinessEntityByToKey().getEntityKey().equalsIgnoreCase(paapi.getToKey()) - && model.getKeyName().equals(paapi.getKeyedReference().getKeyName()) - && model.getKeyValue().equals(paapi.getKeyedReference().getKeyValue()) - && model.getTmodelKey().equalsIgnoreCase(paapi.getKeyedReference().getTModelKey())) { - found = true; - break; - } - } - if (!found) { - ret.add(model); - } - } - return ret; - } - - private static ChangeRecord getChangeRecordConditional(Tmodel modelTModel, TModel apiTModel, String node) throws DispositionReportFaultMessage { - ChangeRecord cr = new ChangeRecord(); - if (!apiTModel.getTModelKey().equals(modelTModel.getEntityKey())) { - throw new FatalErrorException(new ErrorMessage("E_fatalError", "the model and api keys do not match when saving a tmodel!")); - } - cr.setEntityKey(modelTModel.getEntityKey()); - cr.setNodeID(node); - - cr.setRecordType(ChangeRecord.RecordType.ChangeRecordNewDataConditional); - org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); - crapi.setChangeID(new ChangeRecordIDType(node, -1L)); - crapi.setChangeRecordNewDataConditional(new ChangeRecordNewDataConditional()); - crapi.getChangeRecordNewDataConditional().setChangeRecordNewData(new ChangeRecordNewData()); - crapi.getChangeRecordNewDataConditional().getChangeRecordNewData().setTModel(apiTModel); - crapi.getChangeRecordNewDataConditional().getChangeRecordNewData().getTModel().setTModelKey(modelTModel.getEntityKey()); - crapi.getChangeRecordNewDataConditional().getChangeRecordNewData().setOperationalInfo(new OperationalInfo()); - MappingModelToApi.mapOperationalInfo(modelTModel, crapi.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo()); - StringWriter sw = new StringWriter(); - JAXB.marshal(crapi, sw); - try { - cr.setContents(sw.toString().getBytes("UTF8")); - } catch (UnsupportedEncodingException ex) { - logger.error(ex); - } - return cr; - } - - private void removeExistingPublisherAssertionSignatures(String from, String to, EntityManager em) { - Query createQuery = em.createQuery("delete from Signature pa where pa.publisherAssertionFromKey=:from and pa.publisherAssertionToKey=:to"); - createQuery.setParameter("from", from); - createQuery.setParameter("to", to); - createQuery.executeUpdate(); - } - - private void savePushliserAssertionSignatures(String from, String to, List signatures, EntityManager em) { - if (signatures == null) { - return; - } - for (Signature s : signatures) { - s.setPublisherAssertionFromKey(from); - s.setPublisherAssertionToKey(to); - em.persist(s); - } - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import javax.jws.WebService; +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.persistence.Query; +import javax.xml.bind.JAXB; +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.ws.Holder; +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.api.util.PublicationQuery; +import org.apache.juddi.api.util.QueryStatus; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.PersistenceManager; +import org.apache.juddi.config.Property; +import org.apache.juddi.mapping.MappingApiToModel; +import org.apache.juddi.mapping.MappingModelToApi; +import org.apache.juddi.model.BindingTemplate; +import org.apache.juddi.model.BusinessEntity; +import org.apache.juddi.model.BusinessService; +import org.apache.juddi.model.ChangeRecord; +import org.apache.juddi.model.Signature; +import org.apache.juddi.model.Tmodel; +import org.apache.juddi.model.UddiEntityPublisher; +import org.apache.juddi.query.FetchBusinessEntitiesQuery; +import org.apache.juddi.query.FetchTModelsQuery; +import org.apache.juddi.query.FindBusinessByPublisherQuery; +import org.apache.juddi.query.FindPublisherAssertionByBusinessQuery; +import org.apache.juddi.query.FindTModelByPublisherQuery; +import org.apache.juddi.query.TModelQuery; +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.apache.juddi.replication.ReplicationNotifier; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.FatalErrorException; +import org.apache.juddi.v3.error.InvalidValueException; +import org.apache.juddi.validation.ValidatePublish; +import org.uddi.api_v3.AddPublisherAssertions; +import org.uddi.api_v3.AssertionStatusItem; +import org.uddi.api_v3.BindingDetail; +import org.uddi.api_v3.BusinessDetail; +import org.uddi.api_v3.CompletionStatus; +import org.uddi.api_v3.DeleteBinding; +import org.uddi.api_v3.DeleteBusiness; +import org.uddi.api_v3.DeletePublisherAssertions; +import org.uddi.api_v3.DeleteService; +import org.uddi.api_v3.DeleteTModel; +import org.uddi.api_v3.GetRegisteredInfo; +import org.uddi.api_v3.InfoSelection; +import org.uddi.api_v3.ListDescription; +import org.uddi.api_v3.OperationalInfo; +import org.uddi.api_v3.PublisherAssertion; +import org.uddi.api_v3.RegisteredInfo; +import org.uddi.api_v3.SaveBinding; +import org.uddi.api_v3.SaveBusiness; +import org.uddi.api_v3.SaveService; +import org.uddi.api_v3.SaveTModel; +import org.uddi.api_v3.ServiceDetail; +import org.uddi.api_v3.TModel; +import org.uddi.api_v3.TModelDetail; +import org.uddi.repl_v3.ChangeRecordDelete; +import org.uddi.repl_v3.ChangeRecordDeleteAssertion; +import org.uddi.repl_v3.ChangeRecordHide; +import org.uddi.repl_v3.ChangeRecordIDType; +import org.uddi.repl_v3.ChangeRecordNewData; +import org.uddi.repl_v3.ChangeRecordNewDataConditional; +import org.uddi.repl_v3.ChangeRecordPublisherAssertion; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.v3_service.UDDIPublicationPortType; + +/** + * This class implements the UDDI Publication Service + * + * @author Jeff Faath (and many others) + * @author Alex O'Ree added support for + * replication and several bug fixes + */ +@WebService(serviceName = "UDDIPublicationService", + endpointInterface = "org.uddi.v3_service.UDDIPublicationPortType", + targetNamespace = "urn:uddi-org:api_v3_portType") +public class UDDIPublicationImpl extends AuthenticatedService implements UDDIPublicationPortType { + + private static Log log = LogFactory.getLog(UDDIInquiryImpl.class); + private UDDIServiceCounter serviceCounter; + + + public UDDIPublicationImpl() { + super(); + serviceCounter = ServiceCounterLifecycleResource.getServiceCounter(UDDIPublicationImpl.class); + + } + + @Override + public void addPublisherAssertions(AddPublisherAssertions body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); + + new ValidatePublish(publisher).validateAddPublisherAssertions(em, body); + + List apiPubAssertionList = body.getPublisherAssertion(); + List changes = new ArrayList(); + for (org.uddi.api_v3.PublisherAssertion apiPubAssertion : apiPubAssertionList) { + + org.apache.juddi.model.PublisherAssertion modelPubAssertion = new org.apache.juddi.model.PublisherAssertion(); + + MappingApiToModel.mapPublisherAssertion(apiPubAssertion, modelPubAssertion); + + org.apache.juddi.model.PublisherAssertion existingPubAssertion = em.find(modelPubAssertion.getClass(), modelPubAssertion.getId()); + boolean persistNewAssertion = true; + if (existingPubAssertion != null) { + if (modelPubAssertion.getTmodelKey().equalsIgnoreCase(existingPubAssertion.getTmodelKey()) + && modelPubAssertion.getKeyName().equalsIgnoreCase(existingPubAssertion.getKeyName()) + && modelPubAssertion.getKeyValue().equalsIgnoreCase(existingPubAssertion.getKeyValue())) { + // This pub assertion is already been "asserted". Simply need to set the "check" value on the existing (and persistent) assertion + if (publisher.isOwner(existingPubAssertion.getBusinessEntityByFromKey())) { + existingPubAssertion.setFromCheck("true"); + } + if (publisher.isOwner(existingPubAssertion.getBusinessEntityByToKey())) { + existingPubAssertion.setToCheck("true"); + } + //it's also possible that the signatures have changed + removeExistingPublisherAssertionSignatures(existingPubAssertion.getBusinessEntityByFromKey().getEntityKey(), existingPubAssertion.getBusinessEntityByToKey().getEntityKey(), em); + savePushliserAssertionSignatures(existingPubAssertion.getBusinessEntityByFromKey().getEntityKey(), existingPubAssertion.getBusinessEntityByToKey().getEntityKey(), modelPubAssertion.getSignatures(), em); + + em.merge(existingPubAssertion); + persistNewAssertion = false; + changes.add(getChangeRecord_deletePublisherAssertion(apiPubAssertion, getNode(), existingPubAssertion.getToCheck().equalsIgnoreCase("false"), existingPubAssertion.getFromCheck().equalsIgnoreCase("false"), System.currentTimeMillis())); + } else { + // Otherwise, it is a new relationship between these entities. Remove the old one so the new one can be added. + // TODO: the model only seems to allow one assertion per two business (primary key is fromKey and toKey). Spec seems to imply as + // many relationships as desired (the differentiator would be the keyedRef values). + removeExistingPublisherAssertionSignatures(existingPubAssertion.getBusinessEntityByFromKey().getEntityKey(), existingPubAssertion.getBusinessEntityByToKey().getEntityKey(), em); + em.remove(existingPubAssertion); + changes.add(getChangeRecord_deletePublisherAssertion(apiPubAssertion, getNode(), true, true, System.currentTimeMillis())); + } + } + + if (persistNewAssertion) { + org.apache.juddi.model.BusinessEntity beFrom = em.find(org.apache.juddi.model.BusinessEntity.class, modelPubAssertion.getId().getFromKey()); + org.apache.juddi.model.BusinessEntity beTo = em.find(org.apache.juddi.model.BusinessEntity.class, modelPubAssertion.getId().getToKey()); + modelPubAssertion.setBusinessEntityByFromKey(beFrom); + modelPubAssertion.setBusinessEntityByToKey(beTo); + + modelPubAssertion.setFromCheck("false"); + modelPubAssertion.setToCheck("false"); + + if (publisher.isOwner(modelPubAssertion.getBusinessEntityByFromKey())) { + modelPubAssertion.setFromCheck("true"); + } + if (publisher.isOwner(modelPubAssertion.getBusinessEntityByToKey())) { + modelPubAssertion.setToCheck("true"); + } + modelPubAssertion.setModified(new Date()); + savePushliserAssertionSignatures(modelPubAssertion.getBusinessEntityByFromKey().getEntityKey(), modelPubAssertion.getBusinessEntityByToKey().getEntityKey(), modelPubAssertion.getSignatures(), em); + + em.persist(modelPubAssertion); + + changes.add(getChangeRecord_NewAssertion(apiPubAssertion, modelPubAssertion, getNode())); + + } + + } + + tx.commit(); + for (int i = 0; i < changes.size(); i++) { + ReplicationNotifier.enqueue(changes.get(i)); + } + + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.ADD_PUBLISHERASSERTIONS, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.ADD_PUBLISHERASSERTIONS, QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + public void deleteBinding(DeleteBinding body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); + + new ValidatePublish(publisher).validateDeleteBinding(em, body); + + List entityKeyList = body.getBindingKey(); + List changes = new ArrayList(); + for (String entityKey : entityKeyList) { + deleteBinding(entityKey, em); + changes.add(getChangeRecord_deleteBinding(entityKey, getNode())); + } + tx.commit(); + for (int i = 0; i < changes.size(); i++) { + ReplicationNotifier.enqueue(changes.get(i)); + } + + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.DELETE_BINDING, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.DELETE_BINDING, QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + /** + * deletes the referenced object, assuming authorization rules are + * already processed and there is already an open transaction + * + * @param entityKey + * @param em + * @throws DispositionReportFaultMessage + */ + protected void deleteBinding(String entityKey, EntityManager em) throws DispositionReportFaultMessage { + + Object obj = em.find(org.apache.juddi.model.BindingTemplate.class, entityKey); + + ((org.apache.juddi.model.BindingTemplate) obj).getBusinessService().setModifiedIncludingChildren(new Date()); + // JUDDI-421: now the businessEntity parent will have it's modifiedIncludingChildren set + ((org.apache.juddi.model.BindingTemplate) obj).getBusinessService().getBusinessEntity().setModifiedIncludingChildren(new Date()); + + em.remove(obj); + + } + + public void deleteBusiness(DeleteBusiness body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); + + new ValidatePublish(publisher).validateDeleteBusiness(em, body); + + List entityKeyList = body.getBusinessKey(); + List changes = new ArrayList(); + for (String entityKey : entityKeyList) { + deleteBusiness(entityKey, em); + changes.add(getChangeRecord_deleteBusiness(entityKey, getNode())); + } + + tx.commit(); + for (int i = 0; i < changes.size(); i++) { + ReplicationNotifier.enqueue(changes.get(i)); + } + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.DELETE_BUSINESS, QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.DELETE_BUSINESS, QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + /** + * deletes the referenced object, assuming authorization rules are + * already processed and there is already an open transaction + * + * @param entityKey + * @param em + * @throws DispositionReportFaultMessage + */ + protected void deleteBusiness(String key, EntityManager em) throws DispositionReportFaultMessage { + Object obj = em.find(org.apache.juddi.model.BusinessEntity.class, key); + em.remove(obj); + } + + public void deletePublisherAssertions(DeletePublisherAssertions body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); + + new ValidatePublish(publisher).validateDeletePublisherAssertions(em, body); + + List entityList = body.getPublisherAssertion(); + List changes = new ArrayList(); + for (org.uddi.api_v3.PublisherAssertion entity : entityList) { + org.apache.juddi.model.PublisherAssertion modelPubAssertion = new org.apache.juddi.model.PublisherAssertion(); + + MappingApiToModel.mapPublisherAssertion(entity, modelPubAssertion); + + org.apache.juddi.model.PublisherAssertion existingPubAssertion = em.find(org.apache.juddi.model.PublisherAssertion.class, + modelPubAssertion.getId()); + if (existingPubAssertion == null) { + throw new InvalidValueException(new ErrorMessage("E_assertionNotFound")); + } + + boolean fromkey = publisher.isOwner(em.find(BusinessEntity.class, entity.getFromKey())); + boolean tokey = publisher.isOwner(em.find(BusinessEntity.class, entity.getToKey())); + if (fromkey) { + existingPubAssertion.setFromCheck("false"); + } + if (tokey) { + existingPubAssertion.setToCheck("false"); + } + if ("false".equalsIgnoreCase(existingPubAssertion.getToCheck()) + && "false".equalsIgnoreCase(existingPubAssertion.getFromCheck())) { + logger.info("Publisher assertion updated database via replication"); + removeExistingPublisherAssertionSignatures(existingPubAssertion.getBusinessEntityByFromKey().getEntityKey(), existingPubAssertion.getBusinessEntityByToKey().getEntityKey(), em); + em.remove(existingPubAssertion); + } else { + existingPubAssertion.setModified(new Date()); + logger.info("Publisher assertion updated database via replication"); + removeExistingPublisherAssertionSignatures(existingPubAssertion.getBusinessEntityByFromKey().getEntityKey(), existingPubAssertion.getBusinessEntityByToKey().getEntityKey(), em); + savePushliserAssertionSignatures(existingPubAssertion.getBusinessEntityByFromKey().getEntityKey(), + existingPubAssertion.getBusinessEntityByToKey().getEntityKey(), modelPubAssertion.getSignatures(), em); + em.persist(existingPubAssertion); + } + + changes.add(getChangeRecord_deletePublisherAssertion(entity, getNode(), tokey, fromkey, existingPubAssertion.getModified().getTime())); + } + + tx.commit(); + for (int i = 0; i < changes.size(); i++) { + ReplicationNotifier.enqueue(changes.get(i)); + } + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.DELETE_PUBLISHERASSERTIONS, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.DELETE_PUBLISHERASSERTIONS, QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + /** + * deletes the referenced object, assuming authorization rules are + * already processed and there is already an open transaction. this is + * primarily used to support replication calls, i.e. another node just + * changed a PA record and let us know + * + * @param entityKey + * @param em + * @throws DispositionReportFaultMessage + */ + protected void deletePublisherAssertion(org.uddi.repl_v3.ChangeRecordDeleteAssertion entity, EntityManager em) throws DispositionReportFaultMessage { + + org.apache.juddi.model.PublisherAssertion modelPubAssertion = new org.apache.juddi.model.PublisherAssertion(); + + MappingApiToModel.mapPublisherAssertion(entity.getPublisherAssertion(), modelPubAssertion); + + org.apache.juddi.model.PublisherAssertion existingPubAssertion = em.find(org.apache.juddi.model.PublisherAssertion.class, + modelPubAssertion.getId()); + + if (existingPubAssertion == null) { + throw new FatalErrorException(new ErrorMessage("E_assertionNotFound")); + } + boolean fromkey = entity.isFromBusinessCheck();// publisher.isOwner(em.find(BusinessEntity.class, entity.getFromKey())); + boolean tokey = entity.isToBusinessCheck();// publisher.isOwner(em.find(BusinessEntity.class, entity.getToKey())); + if (fromkey) { + existingPubAssertion.setFromCheck("false"); + } + if (tokey) { + existingPubAssertion.setToCheck("false"); + } + if ("false".equalsIgnoreCase(existingPubAssertion.getToCheck()) + && "false".equalsIgnoreCase(existingPubAssertion.getFromCheck())) { + logger.info("Deletion of publisher assertion from database via replication"); + removeExistingPublisherAssertionSignatures(existingPubAssertion.getBusinessEntityByFromKey().getEntityKey(), existingPubAssertion.getBusinessEntityByToKey().getEntityKey(), em); + em.remove(existingPubAssertion); + } else { + existingPubAssertion.setModified(new Date()); + logger.info("Publisher assertion updated database via replication"); + removeExistingPublisherAssertionSignatures(existingPubAssertion.getBusinessEntityByFromKey().getEntityKey(), existingPubAssertion.getBusinessEntityByToKey().getEntityKey(), em); + savePushliserAssertionSignatures(existingPubAssertion.getBusinessEntityByFromKey().getEntityKey(), + existingPubAssertion.getBusinessEntityByToKey().getEntityKey(), modelPubAssertion.getSignatures(), em); + em.persist(existingPubAssertion); + } + + } + + public void deleteService(DeleteService body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); + + new ValidatePublish(publisher).validateDeleteService(em, body); + + List entityKeyList = body.getServiceKey(); + List changes = new ArrayList(); + for (String entityKey : entityKeyList) { + deleteService(entityKey, em); + changes.add(getChangeRecord_deleteService(entityKey, getNode())); + } + + tx.commit(); + for (int i = 0; i < changes.size(); i++) { + ReplicationNotifier.enqueue(changes.get(i)); + } + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.DELETE_SERVICE, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.DELETE_SERVICE, QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + /** + * deletes the referenced object, assuming authorization rules are + * already processed and there is already an open transaction + * + * @param entityKey + * @param em + * @throws DispositionReportFaultMessage + */ + protected void deleteService(String key, EntityManager em) throws DispositionReportFaultMessage { + Object obj = em.find(org.apache.juddi.model.BusinessService.class, key); + //((org.apache.juddi.model.BusinessService) obj).getBusinessEntity().setModifiedIncludingChildren(new Date()); + if (obj != null) { + em.remove(obj); + } else { + logger.warn("Unable to remove service with the key '" + key + "', it doesn't exist in the database"); + } + } + + /** + * {@inheritDoc } + */ + @Override + public void deleteTModel(DeleteTModel body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); + + new ValidatePublish(publisher).validateDeleteTModel(em, body); + + // tModels are only lazily deleted! + List entityKeyList = body.getTModelKey(); + List changes = new ArrayList(); + for (String entityKey : entityKeyList) { + deleteTModel(entityKey, em); + changes.add(getChangeRecord_deleteTModelHide(entityKey, getNode())); + } + + tx.commit(); + + for (int i = 0; i < changes.size(); i++) { + ReplicationNotifier.enqueue(changes.get(i)); + } + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.DELETE_TMODEL, QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.DELETE_TMODEL, QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + /** + * deletes the referenced object, assuming authorization rules are + * already processed and there is already an open transaction + * + * @param entityKey + * @param em + * @throws DispositionReportFaultMessage + */ + protected void deleteTModel(String key, EntityManager em) { + Object obj = em.find(org.apache.juddi.model.Tmodel.class, key); + ((org.apache.juddi.model.Tmodel) obj).setDeleted(true); + } + + /** + * {@inheritDoc } + */ + @Override + public List getAssertionStatusReport(String authInfo, + CompletionStatus completionStatus) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); + + List result = PublicationHelper.getAssertionStatusItemList(publisher, completionStatus, em); + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.GET_ASSERTIONSTATUSREPORT, + QueryStatus.SUCCESS, procTime); + + return result; + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.GET_ASSERTIONSTATUSREPORT, QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + public List getPublisherAssertions(String authInfo) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); + + List result = new ArrayList(0); + + List businessKeysFound = null; + businessKeysFound = FindBusinessByPublisherQuery.select(em, null, publisher, businessKeysFound); + + List pubAssertionList = FindPublisherAssertionByBusinessQuery.select(em, businessKeysFound, null); + if (pubAssertionList != null) { + for (org.apache.juddi.model.PublisherAssertion modelPubAssertion : pubAssertionList) { + org.uddi.api_v3.PublisherAssertion apiPubAssertion = new org.uddi.api_v3.PublisherAssertion(); + + MappingModelToApi.mapPublisherAssertion(modelPubAssertion, apiPubAssertion); + + result.add(apiPubAssertion); + } + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.GET_PUBLISHERASSERTIONS, + QueryStatus.SUCCESS, procTime); + return result; + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.GET_PUBLISHERASSERTIONS, + QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + /** + * {@inheritdoc} + * + */ + public RegisteredInfo getRegisteredInfo(GetRegisteredInfo body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); + + new ValidatePublish(publisher).validateRegisteredInfo(body); + + List businessKeysFound = null; + businessKeysFound = FindBusinessByPublisherQuery.select(em, null, publisher, businessKeysFound); + + List tmodelKeysFound = null; + + if (body.getInfoSelection().equals(InfoSelection.HIDDEN)) { + tmodelKeysFound = FindTModelByPublisherQuery.select(em, null, publisher, tmodelKeysFound, new DynamicQuery.Parameter(TModelQuery.ENTITY_ALIAS + ".deleted", Boolean.TRUE, DynamicQuery.PREDICATE_EQUALS)); + } else if (body.getInfoSelection().equals(InfoSelection.VISIBLE)) { + tmodelKeysFound = FindTModelByPublisherQuery.select(em, null, publisher, tmodelKeysFound, new DynamicQuery.Parameter(TModelQuery.ENTITY_ALIAS + ".deleted", Boolean.FALSE, DynamicQuery.PREDICATE_EQUALS)); + } else { + tmodelKeysFound = FindTModelByPublisherQuery.select(em, null, publisher, tmodelKeysFound); + } + + RegisteredInfo result = new RegisteredInfo(); + + // Sort and retrieve the final results + List queryResults = FetchBusinessEntitiesQuery.select(em, new FindQualifiers(), businessKeysFound, null, null, null); + if (queryResults.size() > 0) { + result.setBusinessInfos(new org.uddi.api_v3.BusinessInfos()); + + for (Object item : queryResults) { + org.apache.juddi.model.BusinessEntity modelBusinessEntity = (org.apache.juddi.model.BusinessEntity) item; + org.uddi.api_v3.BusinessInfo apiBusinessInfo = new org.uddi.api_v3.BusinessInfo(); + + MappingModelToApi.mapBusinessInfo(modelBusinessEntity, apiBusinessInfo); + + result.getBusinessInfos().getBusinessInfo().add(apiBusinessInfo); + } + } + + // Sort and retrieve the final results + queryResults = FetchTModelsQuery.select(em, new FindQualifiers(), tmodelKeysFound, null, null, null); + if (queryResults.size() > 0) { + result.setTModelInfos(new org.uddi.api_v3.TModelInfos()); + + for (Object item : queryResults) { + org.apache.juddi.model.Tmodel modelTModel = (org.apache.juddi.model.Tmodel) item; + org.uddi.api_v3.TModelInfo apiTModelInfo = new org.uddi.api_v3.TModelInfo(); + + MappingModelToApi.mapTModelInfo(modelTModel, apiTModelInfo); + + result.getTModelInfos().getTModelInfo().add(apiTModelInfo); + } + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.GET_REGISTEREDINFO, + QueryStatus.SUCCESS, procTime); + + return result; + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.GET_REGISTEREDINFO, + QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + /** + * {@inheritdoc} + * + */ + public BindingDetail saveBinding(SaveBinding body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); + publisher.populateKeyGeneratorKeys(em); + ValidatePublish validator = new ValidatePublish(publisher); + validator.validateSaveBinding(em, body, null, publisher); + + BindingDetail result = new BindingDetail(); + result.setListDescription(new ListDescription()); + List apiBindingTemplateList = body.getBindingTemplate(); + List changes = new ArrayList(); + + for (org.uddi.api_v3.BindingTemplate apiBindingTemplate : apiBindingTemplateList) { + + org.apache.juddi.model.BindingTemplate modelBindingTemplate = new org.apache.juddi.model.BindingTemplate(); + + org.apache.juddi.model.BusinessService modelBusinessService = new org.apache.juddi.model.BusinessService(); + modelBusinessService.setEntityKey(apiBindingTemplate.getServiceKey()); + + MappingApiToModel.mapBindingTemplate(apiBindingTemplate, modelBindingTemplate, modelBusinessService); + + setOperationalInfo(em, modelBindingTemplate, publisher, true); + + em.persist(modelBindingTemplate); + + result.getBindingTemplate().add(apiBindingTemplate); + result.getListDescription().setActualCount(result.getListDescription().getActualCount() + 1); + result.getListDescription().setIncludeCount(result.getListDescription().getIncludeCount() + 1); + validator.validateSaveBindingMax(em, modelBindingTemplate.getBusinessService().getEntityKey()); + changes.add(getChangeRecord(modelBindingTemplate, apiBindingTemplate, getNode())); + } + + tx.commit(); + for (int i = 0; i < changes.size(); i++) { + ReplicationNotifier.enqueue(changes.get(i)); + } + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.SAVE_BINDING, + QueryStatus.SUCCESS, procTime); + + return result; + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.SAVE_BINDING, + QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + /** + * {@inheritdoc} + * + */ + public BusinessDetail saveBusiness(SaveBusiness body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); + publisher.populateKeyGeneratorKeys(em); + ValidatePublish validator = new ValidatePublish(publisher); + validator.validateSaveBusiness(em, body, null, publisher); + + BusinessDetail result = new BusinessDetail(); + + List apiBusinessEntityList = body.getBusinessEntity(); + List changes = new ArrayList(); + + for (org.uddi.api_v3.BusinessEntity apiBusinessEntity : apiBusinessEntityList) { + + org.apache.juddi.model.BusinessEntity modelBusinessEntity = new org.apache.juddi.model.BusinessEntity(); + + MappingApiToModel.mapBusinessEntity(apiBusinessEntity, modelBusinessEntity); + + setOperationalInfo(em, modelBusinessEntity, publisher); + log.debug("Saving business " + modelBusinessEntity.getEntityKey()); + + em.persist(modelBusinessEntity); + changes.add(getChangeRecord(modelBusinessEntity, apiBusinessEntity, getNode())); + result.getBusinessEntity().add(apiBusinessEntity); + } + + //check how many business this publisher owns. + validator.validateSaveBusinessMax(em); + + tx.commit(); + for (int i = 0; i < changes.size(); i++) { + ReplicationNotifier.enqueue(changes.get(i)); + } + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.SAVE_BUSINESS, + QueryStatus.SUCCESS, procTime); + + return result; + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.SAVE_BUSINESS, + QueryStatus.FAILED, procTime); + throw drfm; + } catch (Exception ex) { + StringWriter sw = new StringWriter(); + if (body != null) { + JAXB.marshal(body, sw); + } + log.fatal("unexpected error!" + sw.toString(), ex); + throw new FatalErrorException(new ErrorMessage("E_fatalError", ex.getMessage())); + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + /** + * {@inheritdoc} + * + */ + public ServiceDetail saveService(SaveService body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); + publisher.populateKeyGeneratorKeys(em); + ValidatePublish validator = new ValidatePublish(publisher); + validator.validateSaveService(em, body, null, publisher); + + ServiceDetail result = new ServiceDetail(); + + List apiBusinessServiceList = body.getBusinessService(); + List changes = new ArrayList(); + for (org.uddi.api_v3.BusinessService apiBusinessService : apiBusinessServiceList) { + + org.apache.juddi.model.BusinessService modelBusinessService = new org.apache.juddi.model.BusinessService(); + org.apache.juddi.model.BusinessEntity modelBusinessEntity = new org.apache.juddi.model.BusinessEntity(); + modelBusinessEntity.setEntityKey(apiBusinessService.getBusinessKey()); + + MappingApiToModel.mapBusinessService(apiBusinessService, modelBusinessService, modelBusinessEntity); + + setOperationalInfo(em, modelBusinessService, publisher, false); + + em.persist(modelBusinessService); + + result.getBusinessService().add(apiBusinessService); + + validator.validateSaveServiceMax(em, modelBusinessService.getBusinessEntity().getEntityKey()); + changes.add(getChangeRecord(modelBusinessService, apiBusinessService, getNode())); + } + + tx.commit(); + for (int i = 0; i < changes.size(); i++) { + ReplicationNotifier.enqueue(changes.get(i)); + } + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.SAVE_SERVICE, + QueryStatus.SUCCESS, procTime); + + return result; + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.SAVE_SERVICE, + QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + /** + * {@inheritdoc} + * + */ + @Override + public TModelDetail saveTModel(SaveTModel body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); + publisher.populateKeyGeneratorKeys(em); + new ValidatePublish(publisher).validateSaveTModel(em, body, null, publisher); + + TModelDetail result = new TModelDetail(); + + List apiTModelList = body.getTModel(); + List changes = new ArrayList(); + for (org.uddi.api_v3.TModel apiTModel : apiTModelList) { + + // Object obj=em.find( org.apache.juddi.model.Tmodel.class, apiTModel.getTModelKey()); + //just making changes to an existing tModel, no worries + org.apache.juddi.model.Tmodel modelTModel = new org.apache.juddi.model.Tmodel(); + + MappingApiToModel.mapTModel(apiTModel, modelTModel); + + setOperationalInfo(em, modelTModel, publisher); + + em.persist(modelTModel); + + result.getTModel().add(apiTModel); + changes.add(getChangeRecord(modelTModel, apiTModel, getNode())); + /* + //TODO JUDDI-915 + if (obj != null) { + + changes.add(getChangeRecord(modelTModel, apiTModel, node)); + } else { + //special case for replication, must setup a new data conditional change record + changes.add(getChangeRecordConditional(modelTModel, apiTModel, node)); + }*/ + + } + + tx.commit(); + for (int i = 0; i < changes.size(); i++) { + ReplicationNotifier.enqueue(changes.get(i)); + } + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.SAVE_TMODEL, + QueryStatus.SUCCESS, procTime); + + return result; + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.SAVE_TMODEL, + QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + /** + * {@inheritdoc} + * + */ + @Override + public void setPublisherAssertions(String authInfo, + Holder> publisherAssertion) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + List changes = new ArrayList(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); + + new ValidatePublish(publisher).validateSetPublisherAssertions(em, publisherAssertion); + + List businessKeysFound = null; + businessKeysFound = FindBusinessByPublisherQuery.select(em, null, publisher, businessKeysFound); + + //TODO this has to be reworked to record what was deleted. + // First, identify all previous assertions that need to be removed + List existingAssertions = FindPublisherAssertionByBusinessQuery.select(em, businessKeysFound, null); + + logger.debug(">>>> Existing assertions " + existingAssertions.size() + ", inbound set " + publisherAssertion.value.size()); + List deleteMe = diff(publisherAssertion.value, existingAssertions); + logger.debug(">>>> DIFF size is " + deleteMe.size()); + for (org.apache.juddi.model.PublisherAssertion del : deleteMe) { + logger.debug(">>>> PROCESSING " + del.getBusinessEntityByFromKey().getEntityKey() + " " + del.getBusinessEntityByToKey().getEntityKey()); + boolean from = false; + if (del.getFromCheck() != null) { + del.getFromCheck().equalsIgnoreCase("true"); + } + boolean to = false; + if (del.getToCheck() != null) { + del.getToCheck().equalsIgnoreCase("true"); + } + if (publisher.isOwner(del.getBusinessEntityByFromKey())) { + from = false; + } + if (publisher.isOwner(del.getBusinessEntityByToKey())) { + to = false; + } + PublisherAssertion api = new PublisherAssertion(); + MappingModelToApi.mapPublisherAssertion(del, api); + + if (!to && !from) { + logger.debug(">>>> DELETE ME " + del.getBusinessEntityByFromKey().getEntityKey() + " " + del.getBusinessEntityByToKey().getEntityKey()); + em.remove(del); + } else { + logger.debug(">>>> MERGING ME " + del.getBusinessEntityByFromKey().getEntityKey() + " " + del.getBusinessEntityByToKey().getEntityKey()); + del.setFromCheck(from ? "true" : "false"); + del.setToCheck(to ? "true" : "false"); + del.setModified(new Date()); + em.merge(del); + } + changes.add(getChangeRecord_deletePublisherAssertion(api, getNode(), to, from, System.currentTimeMillis())); + } + //DeletePublisherAssertionByBusinessQuery.delete(em, businessKeysFound); + + // Slate is clean for all assertions involving this publisher, now we simply need to add the new ones (and they will all be "new"). + /*List apiPubAssertionList = publisherAssertion.value; + + + for (org.uddi.api_v3.PublisherAssertion apiPubAssertion : apiPubAssertionList) { + + org.apache.juddi.model.PublisherAssertion modelPubAssertion = new org.apache.juddi.model.PublisherAssertion(); + + MappingApiToModel.mapPublisherAssertion(apiPubAssertion, modelPubAssertion); + + org.apache.juddi.model.BusinessEntity beFrom = em.find(org.apache.juddi.model.BusinessEntity.class, modelPubAssertion.getId().getFromKey()); + org.apache.juddi.model.BusinessEntity beTo = em.find(org.apache.juddi.model.BusinessEntity.class, modelPubAssertion.getId().getToKey()); + modelPubAssertion.setBusinessEntityByFromKey(beFrom); + modelPubAssertion.setBusinessEntityByToKey(beTo); + + modelPubAssertion.setFromCheck("false"); + modelPubAssertion.setToCheck("false"); + + if (publisher.isOwner(modelPubAssertion.getBusinessEntityByFromKey())) { + modelPubAssertion.setFromCheck("true"); + } + if (publisher.isOwner(modelPubAssertion.getBusinessEntityByToKey())) { + modelPubAssertion.setToCheck("true"); + } + em.persist(modelPubAssertion); + + changes.add(getChangeRecord_NewAssertion(apiPubAssertion, modelPubAssertion, node)); + + }*/ + tx.commit(); + if (!publisherAssertion.value.isEmpty()) { + AddPublisherAssertions addPublisherAssertions = new AddPublisherAssertions(); + addPublisherAssertions.setAuthInfo(authInfo); + addPublisherAssertions.getPublisherAssertion().addAll(publisherAssertion.value); + addPublisherAssertions(addPublisherAssertions); + } + for (int i = 0; i < changes.size(); i++) { + ReplicationNotifier.enqueue(changes.get(i)); + } + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.SET_PUBLISHERASSERTIONS, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(PublicationQuery.SET_PUBLISHERASSERTIONS, + QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + private void setOperationalInfo(EntityManager em, org.apache.juddi.model.BusinessEntity uddiEntity, UddiEntityPublisher publisher) throws DispositionReportFaultMessage { + + uddiEntity.setAuthorizedName(publisher.getAuthorizedName()); + + Date now = new Date(); + uddiEntity.setModified(now); + uddiEntity.setModifiedIncludingChildren(now); + + String nodeId = ""; + try { + nodeId = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID); + } catch (ConfigurationException ce) { + throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval", Property.JUDDI_NODE_ID)); + } + uddiEntity.setNodeId(nodeId); + + org.apache.juddi.model.BusinessEntity existingUddiEntity = em.find(uddiEntity.getClass(), uddiEntity.getEntityKey()); + if (existingUddiEntity != null) { + uddiEntity.setCreated(existingUddiEntity.getCreated()); + } else { + uddiEntity.setCreated(now); + } + + List serviceList = uddiEntity.getBusinessServices(); + for (org.apache.juddi.model.BusinessService service : serviceList) { + setOperationalInfo(em, service, publisher, true); + } + + if (existingUddiEntity != null) { + em.remove(existingUddiEntity); + } + + } + + private void setOperationalInfo(EntityManager em, org.apache.juddi.model.BusinessService uddiEntity, UddiEntityPublisher publisher, boolean isChild) throws DispositionReportFaultMessage { + + uddiEntity.setAuthorizedName(publisher.getAuthorizedName()); + + Date now = new Date(); + uddiEntity.setModified(now); + uddiEntity.setModifiedIncludingChildren(now); + + if (!isChild) { + org.apache.juddi.model.BusinessEntity parent = em.find(org.apache.juddi.model.BusinessEntity.class, uddiEntity.getBusinessEntity().getEntityKey()); + parent.setModifiedIncludingChildren(now); + em.persist(parent); + } + + String nodeId = ""; + try { + nodeId = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID); + } catch (ConfigurationException ce) { + throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval", Property.JUDDI_NODE_ID)); + } + uddiEntity.setNodeId(nodeId); + + org.apache.juddi.model.BusinessService existingUddiEntity = em.find(uddiEntity.getClass(), uddiEntity.getEntityKey()); + if (existingUddiEntity != null) { + uddiEntity.setCreated(existingUddiEntity.getCreated()); + } else { + uddiEntity.setCreated(now); + } + + List bindingList = uddiEntity.getBindingTemplates(); + for (org.apache.juddi.model.BindingTemplate binding : bindingList) { + setOperationalInfo(em, binding, publisher, true); + } + + if (existingUddiEntity != null) { + em.remove(existingUddiEntity); + } + + } + + private void setOperationalInfo(EntityManager em, org.apache.juddi.model.BindingTemplate uddiEntity, UddiEntityPublisher publisher, boolean isChild) throws DispositionReportFaultMessage { + + uddiEntity.setAuthorizedName(publisher.getAuthorizedName()); + + Date now = new Date(); + uddiEntity.setModified(now); + uddiEntity.setModifiedIncludingChildren(now); + + //if (!isChild) { + org.apache.juddi.model.BusinessService parent = em.find(org.apache.juddi.model.BusinessService.class, uddiEntity.getBusinessService().getEntityKey()); + if (parent != null) { + parent.setModifiedIncludingChildren(now); + em.persist(parent); + + // JUDDI-421: now the businessEntity parent will have it's modifiedIncludingChildren set + org.apache.juddi.model.BusinessEntity businessParent = em.find(org.apache.juddi.model.BusinessEntity.class, parent.getBusinessEntity().getEntityKey()); + if (businessParent != null) { + businessParent.setModifiedIncludingChildren(now); + em.persist(businessParent); + } else { + logger.debug("Parent business is null for saved binding template!"); + } + } else { + logger.debug("Parent service is null for saved binding template!"); + } + // } + + String nodeId = ""; + try { + nodeId = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID); + } catch (ConfigurationException ce) { + throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval", Property.JUDDI_NODE_ID)); + } + uddiEntity.setNodeId(nodeId); + + org.apache.juddi.model.BindingTemplate existingUddiEntity = em.find(uddiEntity.getClass(), uddiEntity.getEntityKey()); + if (existingUddiEntity != null) { + uddiEntity.setCreated(existingUddiEntity.getCreated()); + } else { + uddiEntity.setCreated(now); + } + + if (existingUddiEntity != null) { + em.remove(existingUddiEntity); + } + + } + + private void setOperationalInfo(EntityManager em, org.apache.juddi.model.Tmodel uddiEntity, UddiEntityPublisher publisher) throws DispositionReportFaultMessage { + + uddiEntity.setAuthorizedName(publisher.getAuthorizedName()); + + Date now = new Date(); + uddiEntity.setModified(now); + uddiEntity.setModifiedIncludingChildren(now); + + String nodeId = ""; + try { + nodeId = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID); + } catch (ConfigurationException ce) { + throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval", Property.JUDDI_NODE_ID)); + } + uddiEntity.setNodeId(nodeId); + + org.apache.juddi.model.Tmodel existingUddiEntity = em.find(uddiEntity.getClass(), uddiEntity.getEntityKey()); + if (existingUddiEntity != null) { + uddiEntity.setCreated(existingUddiEntity.getCreated()); + } else { + uddiEntity.setCreated(now); + } + + if (existingUddiEntity != null) { + em.remove(existingUddiEntity); + } + + } + + public static ChangeRecord getChangeRecord(BindingTemplate modelBindingTemplate, org.uddi.api_v3.BindingTemplate api, String node) throws DispositionReportFaultMessage { + ChangeRecord cr = new ChangeRecord(); + cr.setEntityKey(modelBindingTemplate.getEntityKey()); + cr.setNodeID(node); + + cr.setRecordType(ChangeRecord.RecordType.ChangeRecordNewData); + org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); + crapi.setChangeID(new ChangeRecordIDType(node, -1L)); + crapi.setChangeRecordNewData(new ChangeRecordNewData()); + crapi.getChangeRecordNewData().setBindingTemplate(api); + crapi.getChangeRecordNewData().setOperationalInfo(new OperationalInfo()); + MappingModelToApi.mapOperationalInfo(modelBindingTemplate, crapi.getChangeRecordNewData().getOperationalInfo()); + StringWriter sw = new StringWriter(); + JAXB.marshal(crapi, sw); + try { + cr.setContents(sw.toString().getBytes("UTF8")); + } catch (UnsupportedEncodingException ex) { + logger.error(ex); + } + return cr; + } + + public static ChangeRecord getChangeRecord(BusinessService model, org.uddi.api_v3.BusinessService api, String node) throws DispositionReportFaultMessage { + ChangeRecord cr = new ChangeRecord(); + cr.setEntityKey(model.getEntityKey()); + cr.setNodeID(node); + + cr.setRecordType(ChangeRecord.RecordType.ChangeRecordNewData); + org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); + crapi.setChangeID(new ChangeRecordIDType(node, -1L)); + crapi.setChangeRecordNewData(new ChangeRecordNewData()); + crapi.getChangeRecordNewData().setBusinessService(api); + crapi.getChangeRecordNewData().setOperationalInfo(new OperationalInfo()); + MappingModelToApi.mapOperationalInfo(model, crapi.getChangeRecordNewData().getOperationalInfo()); + StringWriter sw = new StringWriter(); + JAXB.marshal(crapi, sw); + try { + cr.setContents(sw.toString().getBytes("UTF8")); + } catch (UnsupportedEncodingException ex) { + logger.error(ex); + } + return cr; + } + + public ChangeRecord getChangeRecord_deleteBusiness(String entityKey, String node) { + ChangeRecord cr = new ChangeRecord(); + cr.setEntityKey(entityKey); + cr.setNodeID(node); + + cr.setRecordType(ChangeRecord.RecordType.ChangeRecordDelete); + org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); + crapi.setChangeID(new ChangeRecordIDType(node, -1L)); + crapi.setChangeRecordDelete(new ChangeRecordDelete()); + crapi.getChangeRecordDelete().setBusinessKey(entityKey); + crapi.getChangeRecordDelete().setModified(df.newXMLGregorianCalendar(new GregorianCalendar())); + + StringWriter sw = new StringWriter(); + JAXB.marshal(crapi, sw); + try { + cr.setContents(sw.toString().getBytes("UTF8")); + } catch (UnsupportedEncodingException ex) { + logger.error(ex); + } + return cr; + } + + public ChangeRecord getChangeRecord_deleteService(String entityKey, String node) { + ChangeRecord cr = new ChangeRecord(); + cr.setEntityKey(entityKey); + cr.setNodeID(node); + + cr.setRecordType(ChangeRecord.RecordType.ChangeRecordDelete); + org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); + crapi.setChangeID(new ChangeRecordIDType(node, -1L)); + crapi.setChangeRecordDelete(new ChangeRecordDelete()); + crapi.getChangeRecordDelete().setServiceKey(entityKey); + crapi.getChangeRecordDelete().setModified(df.newXMLGregorianCalendar(new GregorianCalendar())); + + StringWriter sw = new StringWriter(); + JAXB.marshal(crapi, sw); + try { + cr.setContents(sw.toString().getBytes("UTF8")); + } catch (UnsupportedEncodingException ex) { + logger.error(ex); + } + return cr; + } + + /** + * this is for "hiding" a tmodel, not removing it entirely + * + * @param entityKey + * @param node + * @return + */ + public ChangeRecord getChangeRecord_deleteTModelHide(String entityKey, String node) { + ChangeRecord cr = new ChangeRecord(); + cr.setEntityKey(entityKey); + cr.setNodeID(node); + cr.setRecordType(ChangeRecord.RecordType.ChangeRecordHide); + org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); + crapi.setChangeID(new ChangeRecordIDType(node, -1L)); + + crapi.setChangeRecordHide(new ChangeRecordHide()); + crapi.getChangeRecordHide().setTModelKey(entityKey); + crapi.getChangeRecordHide().setModified(df.newXMLGregorianCalendar(new GregorianCalendar())); + + StringWriter sw = new StringWriter(); + JAXB.marshal(crapi, sw); + //JAXB.marshal(crapi, System.out); + try { + cr.setContents(sw.toString().getBytes("UTF8")); + } catch (UnsupportedEncodingException ex) { + logger.error(ex); + } + return cr; + } + + /** + * this is for deleting a tmodel, not hiding it + * + * @param entityKey + * @param node + * @return + */ + public static ChangeRecord getChangeRecord_deleteTModelDelete(String entityKey, String node, DatatypeFactory df) { + ChangeRecord cr = new ChangeRecord(); + cr.setEntityKey(entityKey); + cr.setNodeID(node); + cr.setRecordType(ChangeRecord.RecordType.ChangeRecordDelete); + org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); + crapi.setChangeID(new ChangeRecordIDType(node, -1L)); + + crapi.setChangeRecordDelete(new ChangeRecordDelete()); + crapi.getChangeRecordDelete().setTModelKey(entityKey); + crapi.getChangeRecordDelete().setModified(df.newXMLGregorianCalendar(new GregorianCalendar())); + + StringWriter sw = new StringWriter(); + JAXB.marshal(crapi, sw); + //JAXB.marshal(crapi, System.out); + try { + cr.setContents(sw.toString().getBytes("UTF8")); + } catch (UnsupportedEncodingException ex) { + logger.error(ex); + } + return cr; + } + + public static ChangeRecord getChangeRecord(BusinessEntity modelBusinessEntity, org.uddi.api_v3.BusinessEntity apiBusinessEntity, String node) throws DispositionReportFaultMessage { + ChangeRecord cr = new ChangeRecord(); + cr.setEntityKey(modelBusinessEntity.getEntityKey()); + cr.setNodeID(node); + + cr.setRecordType(ChangeRecord.RecordType.ChangeRecordNewData); + org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); + crapi.setChangeID(new ChangeRecordIDType(node, -1L)); + crapi.setChangeRecordNewData(new ChangeRecordNewData()); + crapi.getChangeRecordNewData().setBusinessEntity(apiBusinessEntity); + crapi.getChangeRecordNewData().setOperationalInfo(new OperationalInfo()); + MappingModelToApi.mapOperationalInfo(modelBusinessEntity, crapi.getChangeRecordNewData().getOperationalInfo()); + StringWriter sw = new StringWriter(); + JAXB.marshal(crapi, sw); + try { + cr.setContents(sw.toString().getBytes("UTF8")); + } catch (UnsupportedEncodingException ex) { + logger.error(ex); + } + return cr; + } + + public static ChangeRecord getChangeRecord(Tmodel modelBusinessEntity, org.uddi.api_v3.TModel apiBusinessEntity, String node) throws DispositionReportFaultMessage { + ChangeRecord cr = new ChangeRecord(); + if (!apiBusinessEntity.getTModelKey().equals(modelBusinessEntity.getEntityKey())) { + throw new FatalErrorException(new ErrorMessage("E_fatalError", "the model and api keys do not match when saving a tmodel!")); + } + cr.setEntityKey(modelBusinessEntity.getEntityKey()); + cr.setNodeID(node); + + cr.setRecordType(ChangeRecord.RecordType.ChangeRecordNewData); + org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); + crapi.setChangeID(new ChangeRecordIDType(node, -1L)); + crapi.setChangeRecordNewData(new ChangeRecordNewData()); + crapi.getChangeRecordNewData().setTModel(apiBusinessEntity); + crapi.getChangeRecordNewData().getTModel().setTModelKey(modelBusinessEntity.getEntityKey()); + crapi.getChangeRecordNewData().setOperationalInfo(new OperationalInfo()); + MappingModelToApi.mapOperationalInfo(modelBusinessEntity, crapi.getChangeRecordNewData().getOperationalInfo()); + StringWriter sw = new StringWriter(); + JAXB.marshal(crapi, sw); + try { + cr.setContents(sw.toString().getBytes("UTF8")); + } catch (UnsupportedEncodingException ex) { + logger.error(ex); + } + return cr; + } + + public ChangeRecord getChangeRecord_deleteBinding(String entityKey, String node) { + ChangeRecord cr = new ChangeRecord(); + cr.setEntityKey(entityKey); + cr.setNodeID(node); + + cr.setRecordType(ChangeRecord.RecordType.ChangeRecordDelete); + org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); + crapi.setChangeID(new ChangeRecordIDType(node, -1L)); + crapi.setChangeRecordDelete(new ChangeRecordDelete()); + crapi.getChangeRecordDelete().setBindingKey(entityKey); + crapi.getChangeRecordDelete().setModified(df.newXMLGregorianCalendar(new GregorianCalendar())); + + StringWriter sw = new StringWriter(); + JAXB.marshal(crapi, sw); + try { + cr.setContents(sw.toString().getBytes("UTF8")); + } catch (UnsupportedEncodingException ex) { + logger.error(ex); + } + return cr; + } + + public ChangeRecord getChangeRecord_deletePublisherAssertion(PublisherAssertion entity, String node, boolean ToBusinessDelete, boolean FromBusinessDelete, long timestamp) { + ChangeRecord cr = new ChangeRecord(); + + cr.setNodeID(node); + + cr.setRecordType(ChangeRecord.RecordType.ChangeRecordDeleteAssertion); + org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); + crapi.setChangeID(new ChangeRecordIDType(node, -1L)); + crapi.setChangeRecordDeleteAssertion(new ChangeRecordDeleteAssertion()); + crapi.getChangeRecordDeleteAssertion().setPublisherAssertion(entity); + crapi.getChangeRecordDeleteAssertion().setToBusinessCheck(ToBusinessDelete); + crapi.getChangeRecordDeleteAssertion().setFromBusinessCheck(FromBusinessDelete); + GregorianCalendar gcal = new GregorianCalendar(); + gcal.setTimeInMillis(timestamp); + crapi.getChangeRecordDeleteAssertion().setModified(df.newXMLGregorianCalendar(gcal)); + + StringWriter sw = new StringWriter(); + JAXB.marshal(crapi, sw); + try { + cr.setContents(sw.toString().getBytes("UTF8")); + } catch (UnsupportedEncodingException ex) { + logger.error(ex); + } + return cr; + } + + public ChangeRecord getChangeRecord_NewAssertion(PublisherAssertion apiPubAssertion, org.apache.juddi.model.PublisherAssertion modelPubAssertion, String node) { + ChangeRecord cr = new ChangeRecord(); + + cr.setNodeID(node); + + cr.setRecordType(ChangeRecord.RecordType.ChangeRecordPublisherAssertion); + org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); + crapi.setChangeID(new ChangeRecordIDType(node, -1L)); + crapi.setChangeRecordPublisherAssertion(new ChangeRecordPublisherAssertion()); + crapi.getChangeRecordPublisherAssertion().setFromBusinessCheck(modelPubAssertion.getFromCheck().equalsIgnoreCase("true")); + crapi.getChangeRecordPublisherAssertion().setToBusinessCheck(modelPubAssertion.getToCheck().equalsIgnoreCase("true")); + crapi.getChangeRecordPublisherAssertion().setPublisherAssertion(apiPubAssertion); + + crapi.getChangeRecordPublisherAssertion().setModified(df.newXMLGregorianCalendar(new GregorianCalendar())); + + StringWriter sw = new StringWriter(); + JAXB.marshal(crapi, sw); + try { + cr.setContents(sw.toString().getBytes("UTF8")); + } catch (UnsupportedEncodingException ex) { + logger.error(ex); + } + return cr; + } + + /** + * + * @param value keep these + * @param existingAssertions return a list of these that are NOT in + * 'value' + * @return + * @throws DispositionReportFaultMessage + */ + private List diff(List value, List existingAssertions) throws DispositionReportFaultMessage { + List ret = new ArrayList(); + if (value == null || value.isEmpty()) { + return existingAssertions; + } + if (existingAssertions == null) { + return new ArrayList(); + } + for (org.apache.juddi.model.PublisherAssertion model : existingAssertions) { + + boolean found = false; + for (PublisherAssertion paapi : value) { + if (model.getBusinessEntityByFromKey().getEntityKey().equalsIgnoreCase(paapi.getFromKey()) + && model.getBusinessEntityByToKey().getEntityKey().equalsIgnoreCase(paapi.getToKey()) + && model.getKeyName().equals(paapi.getKeyedReference().getKeyName()) + && model.getKeyValue().equals(paapi.getKeyedReference().getKeyValue()) + && model.getTmodelKey().equalsIgnoreCase(paapi.getKeyedReference().getTModelKey())) { + found = true; + break; + } + } + if (!found) { + ret.add(model); + } + } + return ret; + } + + private static ChangeRecord getChangeRecordConditional(Tmodel modelTModel, TModel apiTModel, String node) throws DispositionReportFaultMessage { + ChangeRecord cr = new ChangeRecord(); + if (!apiTModel.getTModelKey().equals(modelTModel.getEntityKey())) { + throw new FatalErrorException(new ErrorMessage("E_fatalError", "the model and api keys do not match when saving a tmodel!")); + } + cr.setEntityKey(modelTModel.getEntityKey()); + cr.setNodeID(node); + + cr.setRecordType(ChangeRecord.RecordType.ChangeRecordNewDataConditional); + org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord(); + crapi.setChangeID(new ChangeRecordIDType(node, -1L)); + crapi.setChangeRecordNewDataConditional(new ChangeRecordNewDataConditional()); + crapi.getChangeRecordNewDataConditional().setChangeRecordNewData(new ChangeRecordNewData()); + crapi.getChangeRecordNewDataConditional().getChangeRecordNewData().setTModel(apiTModel); + crapi.getChangeRecordNewDataConditional().getChangeRecordNewData().getTModel().setTModelKey(modelTModel.getEntityKey()); + crapi.getChangeRecordNewDataConditional().getChangeRecordNewData().setOperationalInfo(new OperationalInfo()); + MappingModelToApi.mapOperationalInfo(modelTModel, crapi.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo()); + StringWriter sw = new StringWriter(); + JAXB.marshal(crapi, sw); + try { + cr.setContents(sw.toString().getBytes("UTF8")); + } catch (UnsupportedEncodingException ex) { + logger.error(ex); + } + return cr; + } + + private void removeExistingPublisherAssertionSignatures(String from, String to, EntityManager em) { + Query createQuery = em.createQuery("delete from Signature pa where pa.publisherAssertionFromKey=:from and pa.publisherAssertionToKey=:to"); + createQuery.setParameter("from", from); + createQuery.setParameter("to", to); + createQuery.executeUpdate(); + } + + private void savePushliserAssertionSignatures(String from, String to, List signatures, EntityManager em) { + if (signatures == null) { + return; + } + for (Signature s : signatures) { + s.setPublisherAssertionFromKey(from); + s.setPublisherAssertionToKey(to); + em.persist(s); + } + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIReplicationImpl.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIReplicationImpl.java similarity index 98% rename from juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIReplicationImpl.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIReplicationImpl.java index 49dc39113..08bbe1efe 100644 --- a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIReplicationImpl.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIReplicationImpl.java @@ -1,1376 +1,1376 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; -import java.math.BigInteger; -import java.rmi.RemoteException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Queue; -import java.util.Set; -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.ConcurrentLinkedQueue; -import javax.jws.WebParam; -import javax.jws.WebResult; -import javax.jws.WebService; -import javax.jws.soap.SOAPBinding; -import javax.persistence.EntityManager; -import javax.persistence.EntityTransaction; -import javax.persistence.Query; -import javax.xml.bind.JAXB; -import javax.xml.bind.annotation.XmlSeeAlso; -import javax.xml.ws.BindingProvider; -import org.apache.juddi.api.util.QueryStatus; -import org.apache.juddi.api.util.ReplicationQuery; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.PersistenceManager; -import org.apache.juddi.config.Property; -import org.apache.juddi.mapping.MappingApiToModel; -import org.apache.juddi.mapping.MappingModelToApi; -import org.apache.juddi.model.BindingTemplate; -import org.apache.juddi.model.BusinessEntity; -import org.apache.juddi.model.BusinessService; -import org.apache.juddi.model.Operator; -import org.apache.juddi.model.PublisherAssertion; -import org.apache.juddi.model.PublisherAssertionId; -import org.apache.juddi.model.Tmodel; -import org.apache.juddi.model.UddiEntity; -import org.apache.juddi.replication.ReplicationNotifier; -import static org.apache.juddi.replication.ReplicationNotifier.FetchEdges; -import org.apache.juddi.v3.client.UDDIService; -import org.apache.juddi.v3.client.cryptor.TransportSecurityHelper; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.FatalErrorException; -import org.apache.juddi.v3.error.TransferNotAllowedException; -import org.apache.juddi.validation.ValidateReplication; -import org.uddi.custody_v3.TransferEntities; -import org.uddi.repl_v3.ChangeRecord; -import org.uddi.repl_v3.ChangeRecordAcknowledgement; -import org.uddi.repl_v3.ChangeRecordIDType; -import org.uddi.repl_v3.ChangeRecords; -import org.uddi.repl_v3.CommunicationGraph.Edge; -import org.uddi.repl_v3.DoPing; -import org.uddi.repl_v3.GetChangeRecords; -import org.uddi.repl_v3.HighWaterMarkVectorType; -import org.uddi.repl_v3.NotifyChangeRecordsAvailable; -import org.uddi.repl_v3.ReplicationConfiguration; -import org.uddi.repl_v3.TransferCustody; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.v3_service.UDDIReplicationPortType; - -/** - * UDDI Replication defines four APIs. The first two presented here are used to - * perform replication and issue notifications. The latter ancillary APIs - * provide support for other aspects of UDDI Replication. - *
    - *
  • get_changeRecords
  • - *
  • notify_changeRecordsAvailable
  • - *
  • do_ping
  • - *
  • get_highWaterMarks
- * - * @author Alex O'Ree - */ -@WebService(serviceName = "UDDI_Replication_PortType", targetNamespace = "urn:uddi-org:api_v3_portType", - endpointInterface = "org.uddi.v3_service.UDDIReplicationPortType") -@XmlSeeAlso({ - org.uddi.custody_v3.ObjectFactory.class, - org.uddi.repl_v3.ObjectFactory.class, - org.uddi.subr_v3.ObjectFactory.class, - org.uddi.api_v3.ObjectFactory.class, - org.uddi.vscache_v3.ObjectFactory.class, - org.uddi.vs_v3.ObjectFactory.class, - org.uddi.sub_v3.ObjectFactory.class, - org.w3._2000._09.xmldsig_.ObjectFactory.class, - org.uddi.policy_v3.ObjectFactory.class, - org.uddi.policy_v3_instanceparms.ObjectFactory.class -}) -public class UDDIReplicationImpl extends AuthenticatedService implements UDDIReplicationPortType { - - static void notifyConfigurationChange(ReplicationConfiguration oldConfig, ReplicationConfiguration newConfig, AuthenticatedService service) { - - //if the config is different - Set oldnodes = getNodes(oldConfig); - Set newNodes = getNodes(newConfig); - - Set addedNodes = diffNodeList(oldnodes, newNodes); - if (queue == null) { - queue = new ConcurrentLinkedQueue(); - } - for (String s : addedNodes) { - if (!s.equals(service.getNode())) { - logger.info("This node: " + service.getNode() + ". New replication node queue for synchronization: " + s); - HighWaterMarkVectorType highWaterMarkVectorType = new HighWaterMarkVectorType(); - highWaterMarkVectorType.getHighWaterMark().add(new ChangeRecordIDType(s, 0L)); - queue.add(new NotifyChangeRecordsAvailable(s, highWaterMarkVectorType)); - } - } - - } - - private static Set getNodes(ReplicationConfiguration oldConfig) { - Set ret = new HashSet(); - if (oldConfig == null) { - return ret; - } - for (org.uddi.repl_v3.Operator o : oldConfig.getOperator()) { - ret.add(o.getOperatorNodeID()); - } - if (oldConfig.getCommunicationGraph() != null) { - ret.addAll(oldConfig.getCommunicationGraph().getNode()); - } - return ret; - } - - /** - * returns items in "newNodes" that are not in "oldNodes" - * - * @param oldnodes - * @param newNodes - * @return - */ - private static Set diffNodeList(Set oldnodes, Set newNodes) { - Set diff = new HashSet(); - Iterator iterator = newNodes.iterator(); - while (iterator.hasNext()) { - String lhs = iterator.next(); - Iterator iterator1 = oldnodes.iterator(); - boolean found = false; - while (iterator1.hasNext()) { - String rhs = iterator1.next(); - if (rhs.equalsIgnoreCase(lhs)) { - found = true; - break; - } - } - if (!found) { - diff.add(lhs); - } - - } - return diff; - } - - private UDDIServiceCounter serviceCounter; - - private static PullTimerTask timer = null; - private long startBuffer; - private long interval; - - private static UDDIPublicationImpl pub = null; - - public UDDIReplicationImpl() { - super(); - try { - this.interval = AppConfig.getConfiguration().getLong(Property.JUDDI_REPLICATION_INTERVAL, 5000L); - this.startBuffer = AppConfig.getConfiguration().getLong(Property.JUDDI_REPLICATION_START_BUFFER, 5000L); - } catch (Exception ex) { - logger.warn("Config error!", ex); - } - - serviceCounter = ServiceCounterLifecycleResource.getServiceCounter(UDDIReplicationImpl.class); - init(); - - } - - private synchronized void init() { - if (pub == null) { - pub = new UDDIPublicationImpl(); - } - if (queue == null) { - queue = new ConcurrentLinkedQueue(); - } - timer = new PullTimerTask(); - - } - - - /** - * handles when a remote node tells me that there's an update(s) - * available - */ - private class PullTimerTask extends TimerTask { - - private Timer timer = null; - - public PullTimerTask() { - super(); - timer = new Timer(true); - timer.scheduleAtFixedRate(this, startBuffer, interval); - } - boolean firstrun = true; - - @Override - public void run() { - if (firstrun) { - enqueueAllReceivingNodes(); - firstrun = false; - } - - if (!queue.isEmpty()) { - logger.info("Replication change puller thread started. Queue size: " + queue.size()); - } - //ok someone told me there's a change available - while (!queue.isEmpty()) { - NotifyChangeRecordsAvailable poll = queue.poll(); - if (poll != null && !poll.getNotifyingNode().equalsIgnoreCase(getNode())) { - UDDIReplicationPortType replicationClient = getReplicationClient(poll.getNotifyingNode()); - if (replicationClient == null) { - logger.fatal("unable to obtain a replication client to node " + poll); - } else { - try { - //get the high water marks for this node - //ok now get all the changes - - //done replace with last known record from the given node - //for (int xx = 0; xx < poll.getChangesAvailable().getHighWaterMark().size(); xx++) { - // logger.info("Node " + poll.getChangesAvailable().getHighWaterMark().get(xx).getNodeID() - // + " USN " + poll.getChangesAvailable().getHighWaterMark().get(xx).getOriginatingUSN()); - //} - Set nodesHitThisCycle = new HashSet(); - for (int xx = 0; xx < poll.getChangesAvailable().getHighWaterMark().size(); xx++) { - int recordsreturned = 21; - while (recordsreturned >= 20) { - if (nodesHitThisCycle.contains(poll.getChangesAvailable().getHighWaterMark().get(xx).getNodeID())) { - logger.info("i've already hit the node " + poll.getChangesAvailable().getHighWaterMark().get(xx).getNodeID() + " this cycle, skipping"); - break; - } - if (poll.getChangesAvailable().getHighWaterMark().get(xx).getNodeID().equalsIgnoreCase(getNode())) { - logger.info("ignoring updates that were generated here " + poll.getChangesAvailable().getHighWaterMark().get(xx).getOriginatingUSN() + " sent by " + poll.getNotifyingNode() + " this node is " + getNode()); - break; - } - nodesHitThisCycle.add(poll.getChangesAvailable().getHighWaterMark().get(xx).getNodeID()); - GetChangeRecords body = new GetChangeRecords(); - body.setRequestingNode(getNode()); - body.setResponseLimitCount(BigInteger.valueOf(100L)); - - body.setChangesAlreadySeen(getLastChangeRecordFrom(poll.getChangesAvailable().getHighWaterMark().get(xx).getNodeID())); - logger.info("fetching updates from " + poll.getNotifyingNode() + " since " + body.getChangesAlreadySeen().getHighWaterMark().get(0).getNodeID() + ":" + body.getChangesAlreadySeen().getHighWaterMark().get(0).getOriginatingUSN() + ", items still in the queue: " + queue.size()); - //JAXB.marshal(body, System.out); - List records - = replicationClient.getChangeRecords(body).getChangeRecord(); - //ok now we need to persist the change records - logger.info("Change records retrieved from " + poll.getNotifyingNode() + ", " + records.size()); - for (int i = 0; i < records.size(); i++) { - logger.info("Change records retrieved " + records.get(i).getChangeID().getNodeID() + " USN " + records.get(i).getChangeID().getOriginatingUSN()); - persistChangeRecord(records.get(i)); - } - recordsreturned = records.size(); - } - } - } catch (Exception ex) { - logger.error("Error caught fetching replication changes from " + poll + " @" + ((BindingProvider) replicationClient).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY), ex); - } - } - } else { - if (poll == null) { - logger.warn("strange, popped a null object"); - } else if (poll.getNotifyingNode().equalsIgnoreCase(getNode())) { - logger.warn("strange, popped an object from the queue but it was from myself. This probably indicates a configuration error! ignoring...first record: " + poll.getChangesAvailable().getHighWaterMark().get(0).getNodeID()+":" + poll.getChangesAvailable().getHighWaterMark().get(0).getOriginatingUSN()); - } - } - } - } - - @Override - public boolean cancel() { - timer.cancel(); - return super.cancel(); - } - - /** - * someone told me there's a change available, we retrieved it - * and are processing the changes locally. - * - * @param rec - */ - private void persistChangeRecord(ChangeRecord rec) { - if (rec == null) { - return; - } - logger.debug("_______________________Remote change request " + rec.getChangeID().getNodeID() + ":" + rec.getChangeID().getOriginatingUSN()); - - if (rec.getChangeID().getNodeID().equalsIgnoreCase(getNode())) { - logger.info("Just received a change record that i created, ignoring...."); - return; - } - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - org.apache.juddi.model.ChangeRecord mapChangeRecord = null; - /** - * In nodes that support pre-bundled replication - * responses, the recipient of the get_changeRecords - * message MAY return more change records than requested - * by the caller. In this scenario, the caller MUST also - * be prepared to deal with such redundant changes where - * a USN is less than the USN specified in the - * changesAlreadySeen highWaterMarkVector. - */ - - try { - tx.begin(); - //check to see if we have this update already - Query createQuery = em.createQuery("select c from ChangeRecord c where c.nodeID=:node and c.originatingUSN=:oid"); - createQuery.setParameter("node", rec.getChangeID().getNodeID()); - createQuery.setParameter("oid", rec.getChangeID().getOriginatingUSN()); - Object existingrecord = null; - try { - existingrecord = createQuery.getSingleResult(); - } catch (Exception ex) { - logger.debug("error checking to see if change record exists already (expected failure)", ex); - } - if (existingrecord != null) { - logger.info("I've already processed change record " + rec.getChangeID().getNodeID() + " " + rec.getChangeID().getOriginatingUSN()); - return; - } - //if it didn't come from here and i haven't seen it yet - ReplicationNotifier.EnqueueRetransmit(rec); - //the remotechange record rec must also be persisted!! - mapChangeRecord = MappingApiToModel.mapChangeRecord(rec); - mapChangeRecord.setId(null); - mapChangeRecord.setIsAppliedLocally(true); - em.persist(mapChangeRecord); - tx.commit(); - logger.info("Remote CR saved, it was from " + mapChangeRecord.getNodeID() //this is the origin of the change - + " USN:" + mapChangeRecord.getOriginatingUSN() - + " Type:" + mapChangeRecord.getRecordType().name() - + " Key:" + mapChangeRecord.getEntityKey() - + " Local id from sender:" + mapChangeRecord.getId()); - tx = em.getTransaction(); - tx.begin(); - // - - if (rec.getChangeRecordDelete() != null) { - if (rec.getChangeRecordDelete() != null && rec.getChangeRecordDelete().getBindingKey() != null && !"".equalsIgnoreCase(rec.getChangeRecordDelete().getBindingKey())) { - //delete a binding template - UddiEntity ue = em.find(BindingTemplate.class, rec.getChangeRecordDelete().getBindingKey()); - validateNodeIdMisMatches(ue, getNode()); - pub.deleteBinding(rec.getChangeRecordDelete().getBindingKey(), em); - } - if (rec.getChangeRecordDelete() != null && rec.getChangeRecordDelete().getBusinessKey() != null && !"".equalsIgnoreCase(rec.getChangeRecordDelete().getBusinessKey())) { - //delete a business - UddiEntity ue = em.find(BusinessEntity.class, rec.getChangeRecordDelete().getBusinessKey()); - validateNodeIdMisMatches(ue, getNode()); - pub.deleteBusiness(rec.getChangeRecordDelete().getBusinessKey(), em); - } - if (rec.getChangeRecordDelete() != null && rec.getChangeRecordDelete().getServiceKey() != null && !"".equalsIgnoreCase(rec.getChangeRecordDelete().getServiceKey())) { - UddiEntity ue = em.find(BusinessService.class, rec.getChangeRecordDelete().getServiceKey()); - validateNodeIdMisMatches(ue, getNode()); - //delete a service - pub.deleteService(rec.getChangeRecordDelete().getServiceKey(), em); - } - if (rec.getChangeRecordDelete() != null && rec.getChangeRecordDelete().getTModelKey() != null && !"".equalsIgnoreCase(rec.getChangeRecordDelete().getTModelKey())) { - //delete a tmodel - /** - * The changeRecordDelete for a - * tModel does not correspond to - * any API described in this - * specification and should only - * appear in the replication - * stream as the result of an - * administrative function to - * permanently remove a tModel. - */ - UddiEntity tm = em.find(Tmodel.class, rec.getChangeRecordDelete().getTModelKey()); - if (tm != null) { - validateNodeIdMisMatches(tm, getNode()); - em.remove(tm); - } else { - logger.error("failed to adminstratively delete tmodel because it doesn't exist. " + rec.getChangeRecordDelete().getTModelKey()); - } - //pub.deleteTModel(rec.getChangeRecordDelete().getTModelKey(), em); - } - } - if (rec.getChangeRecordDeleteAssertion() != null && rec.getChangeRecordDeleteAssertion().getPublisherAssertion() != null) { - //delete a pa template - pub.deletePublisherAssertion(rec.getChangeRecordDeleteAssertion(), em); - } - -// - // - if (rec.getChangeRecordNewData() != null) { - - //The operationalInfo element MUST contain the operational information associated with the indicated new data. - if (rec.getChangeRecordNewData().getOperationalInfo() == null) { - logger.warn("Inbound replication data does not have the required OperationalInfo element and is NOT spec compliant. Data will be ignored"); - } else { - if (rec.getChangeRecordNewData().getOperationalInfo().getNodeID() == null) { - throw new Exception("Inbound replication data is missiong node id! Change will not be applied"); - } - if (rec.getChangeRecordNewData().getOperationalInfo().getNodeID().equalsIgnoreCase(getNode())) { - logger.warn("Inbound replication data is modifying locally owned data. This is not allowed, except for custody transfer"); - } - if (rec.getChangeRecordNewData().getBindingTemplate() != null) { - //fetch the binding template if it exists already - //if it exists, - // confirm the owning node, it shouldn't be the local node id, if it is, throw - // the owning node should be the same as it was before - - BusinessService model = em.find(org.apache.juddi.model.BusinessService.class, rec.getChangeRecordNewData().getBindingTemplate().getServiceKey()); - if (model == null) { - logger.error("Replication error, attempting to insert a binding where the service doesn't exist yet"); - } else { - validateNodeIdMatches(rec.getChangeRecordNewData().getOperationalInfo().getNodeID(), model.getNodeId()); - - org.apache.juddi.model.BindingTemplate bt = em.find(org.apache.juddi.model.BindingTemplate.class, rec.getChangeRecordNewData().getBindingTemplate().getBindingKey()); - if (bt != null) { - //ValidateNodeIdMatches(node, bt.getNodeId()); - em.remove(bt); - } - bt = new BindingTemplate(); - MappingApiToModel.mapBindingTemplate(rec.getChangeRecordNewData().getBindingTemplate(), bt, model); - MappingApiToModel.mapOperationalInfo(bt, rec.getChangeRecordNewData().getOperationalInfo()); - // MappingApiToModel.mapOperationalInfoIncludingChildren(model, rec.getChangeRecordNewData().getOperationalInfo()); - em.persist(bt); - } - - } else if (rec.getChangeRecordNewData().getBusinessEntity() != null) { - - BusinessEntity model = em.find(org.apache.juddi.model.BusinessEntity.class, rec.getChangeRecordNewData().getBusinessEntity().getBusinessKey()); - if (model != null) { - //if the owner of the new data is me, and the update didn't originate from me - if (rec.getChangeRecordNewData().getOperationalInfo().getNodeID().equals(getNode()) - && !model.getNodeId().equals(getNode())) { - if (model.getIsTransferInProgress()) { - //allow the transfer - MappingApiToModel.mapBusinessEntity(rec.getChangeRecordNewData().getBusinessEntity(), model); - MappingApiToModel.mapOperationalInfo(model, rec.getChangeRecordNewData().getOperationalInfo()); - MappingApiToModel.mapOperationalInfoIncludingChildren(model, rec.getChangeRecordNewData().getOperationalInfo()); - model.setIsTransferInProgress(false); - em.merge(model); - } else { - //block it, unexpected transfer - throw new Exception("Unexpected entity transfer to to node " + getNode() + " from " + rec.getChangeID().getNodeID()); - } - - } else if (rec.getChangeRecordNewData().getOperationalInfo().getNodeID().equals(getNode()) - && model.getNodeId().equals(getNode())) { - //if destination is here and it's staying here, then this is strange also - //someone else updated one of my records - throw new Exception("unexpected modification of records that this server owns, " + model.getEntityKey()); - } else if (!rec.getChangeRecordNewData().getOperationalInfo().getNodeID().equals(getNode()) - && model.getNodeId().equals(getNode())) { - //this is also strange, destination is elsewhere however it's owned by me. - throw new Exception("unexpected transfer from this node to elsewhere, possible that the key in question exists at two places prior to replication sync, " + model.getEntityKey()); - - } else if (!rec.getChangeRecordNewData().getOperationalInfo().getNodeID().equals(getNode()) - && !model.getNodeId().equals(getNode())) { - //changes on a remote node, for an existing item - MappingApiToModel.mapBusinessEntity(rec.getChangeRecordNewData().getBusinessEntity(), model); - MappingApiToModel.mapOperationalInfoIncludingChildren(model, rec.getChangeRecordNewData().getOperationalInfo()); - em.merge(model); - - } - - } else { - model = new BusinessEntity(); - MappingApiToModel.mapBusinessEntity(rec.getChangeRecordNewData().getBusinessEntity(), model); - MappingApiToModel.mapOperationalInfoIncludingChildren(model, rec.getChangeRecordNewData().getOperationalInfo()); - em.persist(model); - } - } - if (rec.getChangeRecordNewData().getBusinessService() != null) { - BusinessEntity find = em.find(org.apache.juddi.model.BusinessEntity.class, rec.getChangeRecordNewData().getBusinessService().getBusinessKey()); - if (find == null) { - logger.error("Replication error, attempting to insert a service where the business doesn't exist yet"); - } else { - - org.apache.juddi.model.BusinessService model = null; - model = em.find(org.apache.juddi.model.BusinessService.class, rec.getChangeRecordNewData().getBusinessService().getServiceKey()); - if (model != null) { - validateNodeIdMatches(rec.getChangeRecordNewData().getOperationalInfo().getNodeID(), model.getNodeId()); - em.remove(model); - } - - model = new org.apache.juddi.model.BusinessService(); - MappingApiToModel.mapBusinessService(rec.getChangeRecordNewData().getBusinessService(), model, find); - MappingApiToModel.mapOperationalInfo(model, rec.getChangeRecordNewData().getOperationalInfo()); - MappingApiToModel.mapOperationalInfoIncludingChildren(model, rec.getChangeRecordNewData().getOperationalInfo()); - - em.persist(model); - } - - } else if (rec.getChangeRecordNewData().getTModel() != null) { - - Tmodel model = em.find(org.apache.juddi.model.Tmodel.class, rec.getChangeRecordNewData().getTModel().getTModelKey()); - if (model != null) { - //in the case of a transfer - //if the new entity is being transfer to ME, accept and i didn't previously own it, but only if the local record is flagged as transferable - //meaning, only accept if i'm expecting a transfer - if (rec.getChangeRecordNewData().getOperationalInfo().getNodeID().equals(getNode()) - && !model.getNodeId().equals(getNode())) { - if (model.getIsTransferInProgress()) { - //allow the transfer - em.remove(model); - model = new Tmodel(); - MappingApiToModel.mapTModel(rec.getChangeRecordNewData().getTModel(), model); - MappingApiToModel.mapOperationalInfo(model, rec.getChangeRecordNewData().getOperationalInfo()); - model.setIsTransferInProgress(false); - em.persist(model); - } else { - //block it, unexpected transfer - throw new Exception("Unexpected entity transfer to this node from " + rec.getChangeID().getNodeID()); - } - - } else if (rec.getChangeRecordNewData().getOperationalInfo().getNodeID().equals(getNode()) - && model.getNodeId().equals(getNode())) { - //if destination is here and it's staying here, then this is strange also - //someone else updated one of my records - throw new Exception("unexpected modification of records that this server owns, " + model.getEntityKey()); - } else if (!rec.getChangeRecordNewData().getOperationalInfo().getNodeID().equals(getNode()) - && model.getNodeId().equals(getNode())) { - //this is also strange, destination is elsewhere however it's owned by me. - throw new Exception("unexpected transfer from this node to elsewhere, possible that the key in question exists at two places prior to replication sync, " + model.getEntityKey()); - - } else if (!rec.getChangeRecordNewData().getOperationalInfo().getNodeID().equals(getNode()) - && !model.getNodeId().equals(getNode())) { - //changes on a remote node, for an existing item - em.remove(model); - model = new Tmodel(); - MappingApiToModel.mapTModel(rec.getChangeRecordNewData().getTModel(), model); - - MappingApiToModel.mapOperationalInfo(model, rec.getChangeRecordNewData().getOperationalInfo()); - - em.persist(model); - - } - } else { - model = new Tmodel(); - MappingApiToModel.mapTModel(rec.getChangeRecordNewData().getTModel(), model); - - MappingApiToModel.mapOperationalInfo(model, rec.getChangeRecordNewData().getOperationalInfo()); - - em.persist(model); - } - } - - } - - } -// - - // changeRecordNull no action needed - // changeRecordHide tmodel only - // - if (rec.getChangeRecordHide() != null) { - /* - A changeRecordHide element corresponds to the behavior of hiding a tModel described in the delete_tModel in the Publish API section of this Specification. A tModel listed in a changeRecordHide should be marked as hidden, so that it is not returned in response to a find_tModel API call. - - The changeRecordHide MUST contain a modified timestamp to allow multi-node registries to calculate consistent modifiedIncludingChildren timestamps as described in Section 3.8 operationalInfo Structure. - */ - String key = rec.getChangeRecordHide().getTModelKey(); - org.apache.juddi.model.Tmodel existing = em.find(org.apache.juddi.model.Tmodel.class, key); - if (existing == null) { - logger.error("Unexpected delete/hide tmodel message received for non existing key " + key); - } else { - //no one else can delete/hide my tmodel - validateNodeIdMisMatches(existing, getNode()); - existing.setDeleted(true); - existing.setModified(rec.getChangeRecordHide().getModified().toGregorianCalendar().getTime()); - existing.setModifiedIncludingChildren(rec.getChangeRecordHide().getModified().toGregorianCalendar().getTime()); - em.persist(existing); - } - } -// - - // - if (rec.getChangeRecordPublisherAssertion() != null) { - - logger.info("Repl CR Publisher Assertion"); - //TODO are publisher assertions owned by a given node? - PublisherAssertionId paid = new PublisherAssertionId(rec.getChangeRecordPublisherAssertion().getPublisherAssertion().getFromKey(), rec.getChangeRecordPublisherAssertion().getPublisherAssertion().getToKey()); - org.apache.juddi.model.PublisherAssertion model = em.find(org.apache.juddi.model.PublisherAssertion.class, paid); - if (model != null) { - logger.info("Repl CR Publisher Assertion - Existing"); - - if (rec.getChangeRecordPublisherAssertion().isFromBusinessCheck()) { - model.setFromCheck("true"); - } else { - model.setFromCheck("false"); - } - - if (rec.getChangeRecordPublisherAssertion().isToBusinessCheck()) { - model.setToCheck("true"); - } else { - model.setToCheck("false"); - } - - model.setKeyName(rec.getChangeRecordPublisherAssertion().getPublisherAssertion().getKeyedReference().getKeyName()); - model.setKeyValue(rec.getChangeRecordPublisherAssertion().getPublisherAssertion().getKeyedReference().getKeyValue()); - model.setTmodelKey(rec.getChangeRecordPublisherAssertion().getPublisherAssertion().getKeyedReference().getTModelKey()); - model.setModified(rec.getChangeRecordPublisherAssertion().getModified().toGregorianCalendar().getTime()); - //model.setSignatures(MappingApiToModel.mapApiSignaturesToModelSignatures(rec.getChangeRecordPublisherAssertion().getPublisherAssertion().getSignature())); - if ("false".equalsIgnoreCase(model.getFromCheck()) - && "false".equalsIgnoreCase(model.getToCheck())) { - logger.warn("!!!New publisher assertion is both false and false, strange. no need to save it then!"); - em.remove(model); - } - em.merge(model); - } else { - logger.info("Repl CR Publisher Assertion - new PA"); - - model = new PublisherAssertion(); - MappingApiToModel.mapPublisherAssertion(rec.getChangeRecordPublisherAssertion().getPublisherAssertion(), model); - model.setBusinessEntityByFromKey(null); - model.setBusinessEntityByToKey(null); - model.setBusinessEntityByFromKey(em.find(BusinessEntity.class, rec.getChangeRecordPublisherAssertion().getPublisherAssertion().getFromKey())); - model.setBusinessEntityByToKey(em.find(BusinessEntity.class, rec.getChangeRecordPublisherAssertion().getPublisherAssertion().getToKey())); - - if (rec.getChangeRecordPublisherAssertion().isFromBusinessCheck()) { - model.setFromCheck("true"); - } else { - model.setFromCheck("false"); - } - - if (rec.getChangeRecordPublisherAssertion().isToBusinessCheck()) { - model.setToCheck("true"); - } else { - model.setToCheck("false"); - } - model.setModified(rec.getChangeRecordPublisherAssertion().getModified().toGregorianCalendar().getTime()); - em.persist(model); - } - } -// - - if (rec.isAcknowledgementRequested()) { - ChangeRecord posack = new ChangeRecord(); - posack.setChangeRecordAcknowledgement(new ChangeRecordAcknowledgement()); - posack.getChangeRecordAcknowledgement().setAcknowledgedChange(rec.getChangeID()); - posack.setAcknowledgementRequested(false); - ReplicationNotifier.enqueue(MappingApiToModel.mapChangeRecord(posack)); - } - if (rec.getChangeRecordNewDataConditional() != null) { - - if (rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo().getNodeID() == null) { - throw new Exception("Inbound replication data is missiong node id!"); - } - - //The operationalInfo element MUST contain the operational information associated with the indicated new data. - if (rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo() == null) { - logger.warn("Inbound replication data does not have the required OperationalInfo element and is NOT spec compliant. Data will be ignored"); - } else { - if (rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBindingTemplate() != null) { - //fetch the binding template if it exists already - //if it exists, - // confirm the owning node, it shouldn't be the local node id, if it is, throw - // the owning node should be the same as it was before - - BusinessService model = em.find(org.apache.juddi.model.BusinessService.class, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBindingTemplate().getServiceKey()); - if (model == null) { - logger.error("Replication error, attempting to insert a binding where the service doesn't exist yet"); - } else { - - org.apache.juddi.model.BindingTemplate bt = em.find(org.apache.juddi.model.BindingTemplate.class, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBindingTemplate().getBindingKey()); - if (bt != null) { - validateNodeIdMatches(rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo().getNodeID(), bt.getNodeId()); - - em.remove(bt); - } - bt = new BindingTemplate(); - MappingApiToModel.mapBindingTemplate(rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBindingTemplate(), bt, model); - MappingApiToModel.mapOperationalInfo(bt, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo()); - // MappingApiToModel.mapOperationalInfoIncludingChildren(model, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo()); - em.persist(bt); - } - - } else if (rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBusinessEntity() != null) { - - BusinessEntity model = em.find(org.apache.juddi.model.BusinessEntity.class, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBusinessEntity().getBusinessKey()); - if (model != null) { - validateNodeIdMatches(rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo().getNodeID(), model.getNodeId()); - //TODO revisit access control rules - em.remove(model); - } - model = new BusinessEntity(); - MappingApiToModel.mapBusinessEntity(rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBusinessEntity(), model); - // MappingApiToModel.mapOperationalInfo(model, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo()); - - MappingApiToModel.mapOperationalInfoIncludingChildren(model, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo()); - logger.warn("Name size on save is " + model.getBusinessNames().size()); - em.persist(model); - - } - if (rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBusinessService() != null) { - BusinessEntity find = em.find(org.apache.juddi.model.BusinessEntity.class, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBusinessService().getBusinessKey()); - if (find == null) { - logger.error("Replication error, attempting to insert a service where the business doesn't exist yet"); - } else { - - org.apache.juddi.model.BusinessService model = null; - model = em.find(org.apache.juddi.model.BusinessService.class, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBusinessService().getServiceKey()); - if (model != null) { - validateNodeIdMatches(rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo().getNodeID(), model.getNodeId()); - em.remove(model); - } - - model = new org.apache.juddi.model.BusinessService(); - MappingApiToModel.mapBusinessService(rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBusinessService(), model, find); - MappingApiToModel.mapOperationalInfo(model, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo()); - MappingApiToModel.mapOperationalInfoIncludingChildren(model, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo()); - - em.persist(model); - } - - } else if (rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getTModel() != null) { - - Tmodel model = em.find(org.apache.juddi.model.Tmodel.class, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getTModel().getTModelKey()); - if (model != null) { - validateNodeIdMatches(rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo().getNodeID(), model.getNodeId()); - em.remove(model); - } - model = new Tmodel(); - MappingApiToModel.mapTModel(rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getTModel(), model); - - MappingApiToModel.mapOperationalInfo(model, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo()); - - em.persist(model); - } - - } - - } - if (rec.getChangeRecordNull() != null) { - //No action required - - } - if (rec.getChangeRecordCorrection() != null) { - //TODO implement - - } - if (rec.getChangeRecordConditionFailed() != null) { - //TODO implement - - } - tx.commit(); - - } catch (Exception drfm) { - - logger.warn("Error applying the change record! ", drfm); - StringWriter sw = new StringWriter(); - JAXB.marshal(rec, sw); - logger.warn("This is the record that failed to persist: " + sw.toString()); - if (tx.isActive()) { - tx.rollback(); - } - if (mapChangeRecord != null) { - //set the change record's isApplied to false - try { - tx = em.getTransaction(); - tx.begin(); - mapChangeRecord.setIsAppliedLocally(false); - em.merge(mapChangeRecord); - tx.commit(); - } catch (Exception e) { - logger.error("error updating change record!!", e); - if (tx.isActive()) { - tx.rollback(); - } - } - } else { - logger.fatal("whoa! change record is null when saving a remote change record, this is unexpected and should be reported"); - } - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - private HighWaterMarkVectorType getLastChangeRecordFrom(String sourcenode) { - HighWaterMarkVectorType ret = new HighWaterMarkVectorType(); - ChangeRecordIDType cid = new ChangeRecordIDType(); - cid.setNodeID(sourcenode); - cid.setOriginatingUSN(0L); - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - //Long id = 0L; - try { - cid.setOriginatingUSN((Long) em.createQuery("select MAX(e.originatingUSN) from ChangeRecord e where e.nodeID = :node") - .setParameter("node", sourcenode) - .getSingleResult()); - } catch (Exception ex) { - logger.info("unexpected error searching for last record from " + sourcenode, ex); - } - - tx.rollback(); - - } catch (Exception drfm) { - logger.warn("error caught fetching newest record from node " + sourcenode, drfm); - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - logger.info("Highest known record for " + sourcenode + " is " + cid.getOriginatingUSN()); - ret.getHighWaterMark().add(cid); - - return ret; - } - - private void enqueueAllReceivingNodes() { - if (queue == null) { - queue = new ConcurrentLinkedQueue(); - } - //get the replication config - //get everyone we are expecting to receive data from, then enqueue them for pulling - ReplicationConfiguration repcfg = ReplicationNotifier.FetchEdges(); - if (repcfg == null) { - return; - } - Set allnodes = new HashSet(); - for (int i = 0; i < repcfg.getOperator().size(); i++) { - allnodes.add(repcfg.getOperator().get(i).getOperatorNodeID()); - } - Set receivers = new HashSet(); - if (repcfg.getCommunicationGraph() == null - || repcfg.getCommunicationGraph().getEdge().isEmpty()) { - //no edges or graph defined, default to the operator list - for (org.uddi.repl_v3.Operator o : repcfg.getOperator()) { - //no need to tell myself about a change at myself - if (!o.getOperatorNodeID().equalsIgnoreCase(getNode())) { - receivers.add(o.getOperatorNodeID()); - } - } - } else { - //repcfg.getCommunicationGraph() - Iterator iterator = repcfg.getCommunicationGraph().getEdge().iterator(); - while (iterator.hasNext()) { - Edge next = iterator.next(); - - if (next.getMessageReceiver().equalsIgnoreCase(getNode())) { - receivers.add(next.getMessageSender()); - } - - } - - } - for (String s : receivers) { - //this is a list of nodes that this node is expecting updates from - //here are we ticking the notification engine to ping the remove service for updates - for (String nodeping : allnodes) { - queue.add(new NotifyChangeRecordsAvailable(s, getLastChangeRecordFrom(nodeping))); - //for each node we are expecting data from, go fetch it, along the way, we'll request all data for all nodes - //that we know about - } - - } - } - - } - - /** - * used to check for alterations on *this node's data from another node, - * which isn't allowed - * - * @param ue - * @param node - * @throws Exception - */ - private static void validateNodeIdMisMatches(UddiEntity ue, String node) throws Exception { - if (ue == null) { - return;//object doesn't exist - } - if (ue.getNodeId().equals(node)) { - throw new Exception("Alert! attempt to alter locally owned entity " + ue.getEntityKey() + " owned by " + ue.getAuthorizedName() + "@" + ue.getNodeId()); - } - } - - /** - * use to validate that changed data maintained ownership, except for - * business entities and tmodels since they allow transfer - * - * @param newNodeId - * @param currentOwningNode - * @throws Exception - */ - private void validateNodeIdMatches(String newNodeId, String currentOwningNode) throws Exception { - if (newNodeId == null || currentOwningNode == null) { - throw new Exception("either the local node ID is null or the inbound replication data's node id is null"); - } - //only time this is allowed is custody transfer - if (!newNodeId.equals(currentOwningNode)) { - logger.info("AUDIT, custody transfer from node, " + currentOwningNode + " to " + newNodeId + " current node is " + getNode()); - //throw new Exception("node id mismatch!"); - } - - //if i already have a record and "own it" and the remote node has a record with the same key, reject the update - //1.5.8 - /** - * Each node has custody of a portion of the aggregate data - * managed by the registry of which it is a part. Each datum is - * by definition in the custody of exactly one such node. A - * datum in this context can be a businessEntity, a - * businessService, a bindingTemplate, a tModel, or a - * publisherAssertion. Changes to a datum in the registry MUST - * originate at the node which is the custodian of the datum. - * The registry defines the policy for data custody and, if - * allowed, the custodian node for a given datum can be changed; - * such custody transfer processes are discussed in Section 5.4 - * Custody and Ownership Transfer API. - */ - //so someone else attempted to update one of my records, reject it - if (newNodeId.equals(getNode())) { - //throw new Exception("node id mismatch! this node already has a record for key " + newDataOperationalInfo.getEntityKey() + " and I'm the authority for it."); - } - } - - private synchronized UDDIReplicationPortType getReplicationClient(String node) { - if (cache.containsKey(node)) { - return cache.get(node); - } - UDDIService svc = new UDDIService(); - UDDIReplicationPortType replicationClient = svc.getUDDIReplicationPort(); - TransportSecurityHelper.applyTransportSecurity((BindingProvider) replicationClient); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - StringBuilder sql = new StringBuilder(); - sql.append("select c from ReplicationConfiguration c order by c.serialNumber desc"); - //sql.toString(); - Query qry = em.createQuery(sql.toString()); - qry.setMaxResults(1); - - org.apache.juddi.model.ReplicationConfiguration resultList = (org.apache.juddi.model.ReplicationConfiguration) qry.getSingleResult(); - for (Operator o : resultList.getOperator()) { - if (o.getOperatorNodeID().equalsIgnoreCase(node)) { - ((BindingProvider) replicationClient).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, o.getSoapReplicationURL()); - cache.put(node, replicationClient); - return replicationClient; - } - } - tx.rollback(); - - } catch (Exception ex) { - logger.fatal("Node not found!" + node, ex); - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - //em.close(); - return null; - - } - private Map cache = new HashMap(); - - /** - * @since 3.3 - * @param body - * @return - * @throws DispositionReportFaultMessage - */ - public String doPing(DoPing body) throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(ReplicationQuery.DO_PING, QueryStatus.SUCCESS, procTime); - - return getNode(); - - } - - @SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE) - @WebResult(name = "changeRecords", targetNamespace = "urn:uddi-org:repl_v3", partName = "body") - // @WebMethod(operationName = "get_changeRecords", action = "get_changeRecords") - @Override - public org.uddi.repl_v3.ChangeRecords getChangeRecords( - @WebParam(partName = "body", name = "get_changeRecords", targetNamespace = "urn:uddi-org:repl_v3") org.uddi.repl_v3.GetChangeRecords body - ) throws DispositionReportFaultMessage, RemoteException { - long startTime = System.currentTimeMillis(); - String requestingNode = body.getRequestingNode(); - HighWaterMarkVectorType changesAlreadySeen = body.getChangesAlreadySeen(); - BigInteger responseLimitCount = body.getResponseLimitCount(); - HighWaterMarkVectorType responseLimitVector = body.getResponseLimitVector(); - - new ValidateReplication(null).validateGetChangeRecords(requestingNode, changesAlreadySeen, responseLimitCount, responseLimitVector, FetchEdges(), ctx); - - //TODO should we validate that "requestingNode" is in the replication config? - List ret = new ArrayList(); - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - - /** - * More specifically, the recipient determines the particular - * change records that are returned by comparing the originating - * USNs in the caller’s high water mark vector with the - * originating USNs of each of the changes the recipient has - * seen from others or generated by itself. The recipient SHOULD - * only return change records that have originating USNs that - * are greater than those listed in the changesAlreadySeen - * highWaterMarkVector and less than the limit required by - * either the responseLimitCount or the responseLimitVector. - * - * - * Part of the message is a high water mark vector that contains - * for each node of the registry the originating USN of the most - * recent change record that has been successfully processed by - * the invocating node - */ - try { - int maxrecords = AppConfig.getConfiguration().getInt(Property.JUDDI_REPLICATION_GET_CHANGE_RECORDS_MAX, 100); - if (responseLimitCount != null) { - maxrecords = responseLimitCount.intValue(); - } - tx.begin(); - Long firstrecord = 0L; - Long lastrecord = null; - Query createQuery = null; -//SELECT t0.id, t0.change_contents, t0.entity_key, t0.appliedlocal, t0.node_id, t0.orginating_usn, t0.record_type FROM j3_chg_record t0 WHERE (t0.id > NULL AND t0.node_id = ?) ORDER BY t0.id ASC - if (changesAlreadySeen != null) { - //this is basically a lower limit (i.e. the newest record that was processed by the requestor - //therefore we want the oldest record stored locally to return to the requestor for processing - for (int i = 0; i < changesAlreadySeen.getHighWaterMark().size(); i++) { - firstrecord = changesAlreadySeen.getHighWaterMark().get(i).getOriginatingUSN(); - if (firstrecord == null) { - firstrecord = 0L; - } - if (changesAlreadySeen.getHighWaterMark().get(i).getNodeID().equals(getNode())) { - //special case, search by database id - createQuery = em.createQuery("select e from ChangeRecord e where " - + "(e.id > :inbound AND e.nodeID = :node) " - + "order by e.id ASC"); - - } else { - createQuery = em.createQuery("select e from ChangeRecord e where " - + "e.originatingUSN > :inbound AND e.nodeID = :node " - + "order by e.originatingUSN ASC"); - } - logger.info("Query db for replication changes, lower index is " + (firstrecord) + " last index " + lastrecord + " record limit " + maxrecords); - logger.info("This node is " + getNode() + ", request is for data originated from " + changesAlreadySeen.getHighWaterMark().get(i).getNodeID() + " and it's being sent back to " + requestingNode); - - createQuery.setMaxResults(maxrecords); - createQuery.setParameter("inbound", firstrecord); - createQuery.setParameter("node", changesAlreadySeen.getHighWaterMark().get(i).getNodeID()); - List records = (List) createQuery.getResultList(); - logger.info(records.size() + " CR records returned from query"); - for (int x = 0; x < records.size(); x++) { - ChangeRecord r = MappingModelToApi.mapChangeRecord(records.get(x)); - //if (!Excluded(changesAlreadySeen, r)) { - ret.add(r); - //} - - } - } - } /*if (responseLimitVector != null) { - //using responseLimitVector, indicating for each node in the graph the first change originating there that he does not wish to be returned. - //upper limit basically - for (int i = 0; i < responseLimitVector.getHighWaterMark().size(); i++) { - //if (responseLimitVector.getHighWaterMark().get(i).getNodeID().equals(node)) { - lastrecord = responseLimitVector.getHighWaterMark().get(i).getOriginatingUSN(); - //} - } - }*/ else { - if (firstrecord == null) { - firstrecord = 0L; - } - //assume that they just want records that originated from here? - logger.info("Query db for replication changes, lower index is " + (firstrecord) + " last index " + lastrecord + " record limit " + maxrecords); - logger.info("This node is " + getNode() + " requesting node " + requestingNode); - - if (lastrecord != null) { - createQuery = em.createQuery("select e from ChangeRecord e where " - + "(e.id > :inbound AND e.nodeID = :node AND e.id < :lastrecord) " - + "order by e.id ASC"); - createQuery.setParameter("lastrecord", lastrecord); - } else { - createQuery = em.createQuery("select e from ChangeRecord e where " - + "(e.id > :inbound AND e.nodeID = :node) " - + "order by e.id ASC"); - } - createQuery.setMaxResults(maxrecords); - createQuery.setParameter("inbound", firstrecord); - createQuery.setParameter("node", getNode()); - - List records = (List) createQuery.getResultList(); - logger.info(records.size() + " CR records returned from query"); - for (int i = 0; i < records.size(); i++) { - ChangeRecord r = MappingModelToApi.mapChangeRecord(records.get(i)); - //if (!Excluded(changesAlreadySeen, r)) { - ret.add(r); - //} - - } - } - tx.rollback(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(ReplicationQuery.GET_CHANGERECORDS, - QueryStatus.SUCCESS, procTime); - - } catch (Exception ex) { - logger.fatal("Error, this node is: " + getNode(), ex); - throw new FatalErrorException(new ErrorMessage("E_fatalError", ex.getMessage())); - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - logger.info("Change records returned for " + requestingNode + ": " + ret.size()); - //JAXB.marshal(ret, System.out); - ChangeRecords x = new ChangeRecords(); - x.getChangeRecord().addAll(ret); - //JAXB.marshal(x, System.out); - return x; - } - - /** - * This UDDI API message provides a means to obtain a list of - * highWaterMark element containing the highest known USN for all nodes - * in the replication graph. If there is no graph, we just return the - * local bits - * - * @return - * @throws DispositionReportFaultMessage - */ - @Override - public List getHighWaterMarks() - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - List ret = new ArrayList(); - - //fetch from database the highest known watermark - ReplicationConfiguration FetchEdges = FetchEdges(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - HashMap map = new HashMap(); - try { - tx.begin(); - if (FetchEdges != null) { - Iterator it = FetchEdges.getCommunicationGraph().getNode().iterator(); - while (it.hasNext()) { - String nextNode = it.next(); - if (!nextNode.equals(getNode())) { - if (!map.containsKey(nextNode)) { - Long id = 0L; - try { - id = (Long) em.createQuery("select e.originatingUSN from ChangeRecord e where e.nodeID = :node order by e.originatingUSN desc").setParameter("node", nextNode).setMaxResults(1).getSingleResult(); - } catch (Exception ex) { - logger.debug(ex); - } - if (id == null) { - id = 0L; - //per the spec - } - map.put(nextNode, id); - - } - } - } - } - //dont forget this node - Query setMaxResults = em.createQuery("select (e.id) from ChangeRecord e where e.nodeID = :node order by e.id desc") - .setParameter("node", getNode()).setMaxResults(1); - Long id =null; - if (setMaxResults.getResultList().isEmpty()) { - //this can happen at or near startup - id = 0L; - } else { - id = (Long) em.createQuery("select (e.id) from ChangeRecord e where e.nodeID = :node order by e.id desc") - .setParameter("node", getNode()).setMaxResults(1).getSingleResult(); - } - ChangeRecordIDType x = new ChangeRecordIDType(); - x.setNodeID(getNode()); - x.setOriginatingUSN(id); - ret.add(x); - - tx.rollback(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(ReplicationQuery.GET_HIGHWATERMARKS, QueryStatus.SUCCESS, procTime); - - } catch (Exception drfm) { - logger.fatal("Error, this node is: " + getNode(), drfm); - throw new FatalErrorException(new ErrorMessage("E_fatalError", drfm.getMessage())); - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - Iterator> iterator = map.entrySet().iterator(); - while (iterator.hasNext()) { - Map.Entry next = iterator.next(); - ret.add(new ChangeRecordIDType(next.getKey(), next.getValue())); - } - return ret; - } - - /** - * this means that another node has a change and we need to pick up the - * change and apply it to our local database. - * - * @param body - * @throws DispositionReportFaultMessage - */ - @Override - public void notifyChangeRecordsAvailable(NotifyChangeRecordsAvailable body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - //some other node just told us there's new records available, call - //getChangeRecords from the remote node asynch - new ValidateReplication(null).validateNotifyChangeRecordsAvailable(body, ctx); - - logger.info(body.getNotifyingNode() + " just told me that there are change records available, enqueuing...size is " + queue.size() + " this node is " + getNode()); - //if (!queue.contains(body.getNotifyingNode())) { - queue.add(body); - //} - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(ReplicationQuery.NOTIFY_CHANGERECORDSAVAILABLE, - QueryStatus.SUCCESS, procTime); - } - private static Queue queue = null; - - /** - * transfers custody of an entity from node1/user1 to node2/user2 - * - * assume this node is node 2. - * - * user1 on node1 requests a transfer token. node 1 issues the token. - * - * user1 now has a transfer token for their stuff user now takes the - * token to node 2 and calls transferEntities - * - * - * @param body - * @throws DispositionReportFaultMessage - */ - @Override - public void transferCustody(TransferCustody body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - logger.info("Inbound transfer request (via replication api, node to node"); - try { - tx.begin(); - //*this node is transfering data to another node - //ValidateReplication.unsupportedAPICall(); - //a remote node just told me to give up control of some of my entities - - //EntityTransaction tx = em.getTransaction(); - //confirm i have a replication config - boolean ok = false; - ReplicationConfiguration FetchEdges = ReplicationNotifier.FetchEdges(); - if (FetchEdges != null) { - for (int i = 0; i < FetchEdges.getOperator().size(); i++) { - //confirm that the destination node is in the replication config - if (FetchEdges.getOperator().get(i).getOperatorNodeID().equals(body.getTransferOperationalInfo().getNodeID())) { - ok = true; - break; - } - } - } - if (!ok) { - throw new TransferNotAllowedException(new ErrorMessage("E_transferNotAllowedUnknownNode")); - } - - new ValidateReplication(null).validateTransfer(em, body); - - TransferEntities te = new TransferEntities(); - te.setKeyBag(body.getKeyBag()); - te.setTransferToken(body.getTransferToken()); - te.setAuthInfo(null); - //make the change - //enqueue in replication notifier - //discard the token - logger.debug("request validated, processing transfer"); - List executeTransfer = new UDDICustodyTransferImpl().executeTransfer(te, em, body.getTransferOperationalInfo().getAuthorizedName(), body.getTransferOperationalInfo().getNodeID()); - - for (ChangeRecord c : executeTransfer) { - try { - c.setChangeID(new ChangeRecordIDType()); - c.getChangeID().setNodeID(getNode()); - c.getChangeID().setOriginatingUSN(null); - ReplicationNotifier.enqueue(MappingApiToModel.mapChangeRecord(c)); - } catch (UnsupportedEncodingException ex) { - logger.error("", ex); - } - } - /** - * The custodial node must verify that it has granted - * permission to transfer the entities identified and - * that this permission is still valid. This operation - * is comprised of two steps: - * - * 1. Verification that the transferToken was issued by - * it, that it has not expired, that it represents the - * authority to transfer no more and no less than those - * entities identified by the businessKey and tModelKey - * elements and that all these entities are still valid - * and not yet transferred. The transferToken is - * invalidated if any of these conditions are not met. - * - * 2. If the conditions above are met, the custodial - * node will prevent any further changes to the entities - * identified by the businessKey and tModelKey elements - * identified. The entity will remain in this state - * until the replication stream indicates it has been - * successfully processed via the replication stream. - * Upon successful verification of the custody transfer - * request by the custodial node, an empty message is - * returned by it indicating the success of the request - * and acknowledging the custody transfer. Following the - * issue of the empty message, the custodial node will - * submit into the replication stream a - * changeRecordNewData providing in the operationalInfo, - * the nodeID accepting custody of the datum and the - * authorizedName of the publisher accepting ownership. - * The acknowledgmentRequested attribute of this change - * record MUST be set to "true". - * - * - * - * Finally, the custodial node invalidates the - * transferToken in order to prevent additional calls of - * the transfer_entities API. - */ - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(ReplicationQuery.TRANSFER_CUSTODY, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage d) { - logger.error("Unable to process node to node custody transfer ", d); - throw d; - } finally { - if (em != null && em.isOpen()) { - em.close(); - } - if (tx.isActive()) { - tx.rollback(); - } - } - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.math.BigInteger; +import java.rmi.RemoteException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.Set; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.ConcurrentLinkedQueue; +import javax.jws.WebParam; +import javax.jws.WebResult; +import javax.jws.WebService; +import javax.jws.soap.SOAPBinding; +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.persistence.Query; +import javax.xml.bind.JAXB; +import javax.xml.bind.annotation.XmlSeeAlso; +import javax.xml.ws.BindingProvider; +import org.apache.juddi.api.util.QueryStatus; +import org.apache.juddi.api.util.ReplicationQuery; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.PersistenceManager; +import org.apache.juddi.config.Property; +import org.apache.juddi.mapping.MappingApiToModel; +import org.apache.juddi.mapping.MappingModelToApi; +import org.apache.juddi.model.BindingTemplate; +import org.apache.juddi.model.BusinessEntity; +import org.apache.juddi.model.BusinessService; +import org.apache.juddi.model.Operator; +import org.apache.juddi.model.PublisherAssertion; +import org.apache.juddi.model.PublisherAssertionId; +import org.apache.juddi.model.Tmodel; +import org.apache.juddi.model.UddiEntity; +import org.apache.juddi.replication.ReplicationNotifier; +import static org.apache.juddi.replication.ReplicationNotifier.FetchEdges; +import org.apache.juddi.v3.client.UDDIService; +import org.apache.juddi.v3.client.cryptor.TransportSecurityHelper; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.FatalErrorException; +import org.apache.juddi.v3.error.TransferNotAllowedException; +import org.apache.juddi.validation.ValidateReplication; +import org.uddi.custody_v3.TransferEntities; +import org.uddi.repl_v3.ChangeRecord; +import org.uddi.repl_v3.ChangeRecordAcknowledgement; +import org.uddi.repl_v3.ChangeRecordIDType; +import org.uddi.repl_v3.ChangeRecords; +import org.uddi.repl_v3.CommunicationGraph.Edge; +import org.uddi.repl_v3.DoPing; +import org.uddi.repl_v3.GetChangeRecords; +import org.uddi.repl_v3.HighWaterMarkVectorType; +import org.uddi.repl_v3.NotifyChangeRecordsAvailable; +import org.uddi.repl_v3.ReplicationConfiguration; +import org.uddi.repl_v3.TransferCustody; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.v3_service.UDDIReplicationPortType; + +/** + * UDDI Replication defines four APIs. The first two presented here are used to + * perform replication and issue notifications. The latter ancillary APIs + * provide support for other aspects of UDDI Replication. + *
    + *
  • get_changeRecords
  • + *
  • notify_changeRecordsAvailable
  • + *
  • do_ping
  • + *
  • get_highWaterMarks
+ * + * @author Alex O'Ree + */ +@WebService(serviceName = "UDDI_Replication_PortType", targetNamespace = "urn:uddi-org:api_v3_portType", + endpointInterface = "org.uddi.v3_service.UDDIReplicationPortType") +@XmlSeeAlso({ + org.uddi.custody_v3.ObjectFactory.class, + org.uddi.repl_v3.ObjectFactory.class, + org.uddi.subr_v3.ObjectFactory.class, + org.uddi.api_v3.ObjectFactory.class, + org.uddi.vscache_v3.ObjectFactory.class, + org.uddi.vs_v3.ObjectFactory.class, + org.uddi.sub_v3.ObjectFactory.class, + org.w3._2000._09.xmldsig_.ObjectFactory.class, + org.uddi.policy_v3.ObjectFactory.class, + org.uddi.policy_v3_instanceparms.ObjectFactory.class +}) +public class UDDIReplicationImpl extends AuthenticatedService implements UDDIReplicationPortType { + + static void notifyConfigurationChange(ReplicationConfiguration oldConfig, ReplicationConfiguration newConfig, AuthenticatedService service) { + + //if the config is different + Set oldnodes = getNodes(oldConfig); + Set newNodes = getNodes(newConfig); + + Set addedNodes = diffNodeList(oldnodes, newNodes); + if (queue == null) { + queue = new ConcurrentLinkedQueue(); + } + for (String s : addedNodes) { + if (!s.equals(service.getNode())) { + logger.info("This node: " + service.getNode() + ". New replication node queue for synchronization: " + s); + HighWaterMarkVectorType highWaterMarkVectorType = new HighWaterMarkVectorType(); + highWaterMarkVectorType.getHighWaterMark().add(new ChangeRecordIDType(s, 0L)); + queue.add(new NotifyChangeRecordsAvailable(s, highWaterMarkVectorType)); + } + } + + } + + private static Set getNodes(ReplicationConfiguration oldConfig) { + Set ret = new HashSet(); + if (oldConfig == null) { + return ret; + } + for (org.uddi.repl_v3.Operator o : oldConfig.getOperator()) { + ret.add(o.getOperatorNodeID()); + } + if (oldConfig.getCommunicationGraph() != null) { + ret.addAll(oldConfig.getCommunicationGraph().getNode()); + } + return ret; + } + + /** + * returns items in "newNodes" that are not in "oldNodes" + * + * @param oldnodes + * @param newNodes + * @return + */ + private static Set diffNodeList(Set oldnodes, Set newNodes) { + Set diff = new HashSet(); + Iterator iterator = newNodes.iterator(); + while (iterator.hasNext()) { + String lhs = iterator.next(); + Iterator iterator1 = oldnodes.iterator(); + boolean found = false; + while (iterator1.hasNext()) { + String rhs = iterator1.next(); + if (rhs.equalsIgnoreCase(lhs)) { + found = true; + break; + } + } + if (!found) { + diff.add(lhs); + } + + } + return diff; + } + + private UDDIServiceCounter serviceCounter; + + private static PullTimerTask timer = null; + private long startBuffer; + private long interval; + + private static UDDIPublicationImpl pub = null; + + public UDDIReplicationImpl() { + super(); + try { + this.interval = AppConfig.getConfiguration().getLong(Property.JUDDI_REPLICATION_INTERVAL, 5000L); + this.startBuffer = AppConfig.getConfiguration().getLong(Property.JUDDI_REPLICATION_START_BUFFER, 5000L); + } catch (Exception ex) { + logger.warn("Config error!", ex); + } + + serviceCounter = ServiceCounterLifecycleResource.getServiceCounter(UDDIReplicationImpl.class); + init(); + + } + + private synchronized void init() { + if (pub == null) { + pub = new UDDIPublicationImpl(); + } + if (queue == null) { + queue = new ConcurrentLinkedQueue(); + } + timer = new PullTimerTask(); + + } + + + /** + * handles when a remote node tells me that there's an update(s) + * available + */ + private class PullTimerTask extends TimerTask { + + private Timer timer = null; + + public PullTimerTask() { + super(); + timer = new Timer(true); + timer.scheduleAtFixedRate(this, startBuffer, interval); + } + boolean firstrun = true; + + @Override + public void run() { + if (firstrun) { + enqueueAllReceivingNodes(); + firstrun = false; + } + + if (!queue.isEmpty()) { + logger.info("Replication change puller thread started. Queue size: " + queue.size()); + } + //ok someone told me there's a change available + while (!queue.isEmpty()) { + NotifyChangeRecordsAvailable poll = queue.poll(); + if (poll != null && !poll.getNotifyingNode().equalsIgnoreCase(getNode())) { + UDDIReplicationPortType replicationClient = getReplicationClient(poll.getNotifyingNode()); + if (replicationClient == null) { + logger.fatal("unable to obtain a replication client to node " + poll); + } else { + try { + //get the high water marks for this node + //ok now get all the changes + + //done replace with last known record from the given node + //for (int xx = 0; xx < poll.getChangesAvailable().getHighWaterMark().size(); xx++) { + // logger.info("Node " + poll.getChangesAvailable().getHighWaterMark().get(xx).getNodeID() + // + " USN " + poll.getChangesAvailable().getHighWaterMark().get(xx).getOriginatingUSN()); + //} + Set nodesHitThisCycle = new HashSet(); + for (int xx = 0; xx < poll.getChangesAvailable().getHighWaterMark().size(); xx++) { + int recordsreturned = 21; + while (recordsreturned >= 20) { + if (nodesHitThisCycle.contains(poll.getChangesAvailable().getHighWaterMark().get(xx).getNodeID())) { + logger.info("i've already hit the node " + poll.getChangesAvailable().getHighWaterMark().get(xx).getNodeID() + " this cycle, skipping"); + break; + } + if (poll.getChangesAvailable().getHighWaterMark().get(xx).getNodeID().equalsIgnoreCase(getNode())) { + logger.info("ignoring updates that were generated here " + poll.getChangesAvailable().getHighWaterMark().get(xx).getOriginatingUSN() + " sent by " + poll.getNotifyingNode() + " this node is " + getNode()); + break; + } + nodesHitThisCycle.add(poll.getChangesAvailable().getHighWaterMark().get(xx).getNodeID()); + GetChangeRecords body = new GetChangeRecords(); + body.setRequestingNode(getNode()); + body.setResponseLimitCount(BigInteger.valueOf(100L)); + + body.setChangesAlreadySeen(getLastChangeRecordFrom(poll.getChangesAvailable().getHighWaterMark().get(xx).getNodeID())); + logger.info("fetching updates from " + poll.getNotifyingNode() + " since " + body.getChangesAlreadySeen().getHighWaterMark().get(0).getNodeID() + ":" + body.getChangesAlreadySeen().getHighWaterMark().get(0).getOriginatingUSN() + ", items still in the queue: " + queue.size()); + //JAXB.marshal(body, System.out); + List records + = replicationClient.getChangeRecords(body).getChangeRecord(); + //ok now we need to persist the change records + logger.info("Change records retrieved from " + poll.getNotifyingNode() + ", " + records.size()); + for (int i = 0; i < records.size(); i++) { + logger.info("Change records retrieved " + records.get(i).getChangeID().getNodeID() + " USN " + records.get(i).getChangeID().getOriginatingUSN()); + persistChangeRecord(records.get(i)); + } + recordsreturned = records.size(); + } + } + } catch (Exception ex) { + logger.error("Error caught fetching replication changes from " + poll + " @" + ((BindingProvider) replicationClient).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY), ex); + } + } + } else { + if (poll == null) { + logger.warn("strange, popped a null object"); + } else if (poll.getNotifyingNode().equalsIgnoreCase(getNode())) { + logger.warn("strange, popped an object from the queue but it was from myself. This probably indicates a configuration error! ignoring...first record: " + poll.getChangesAvailable().getHighWaterMark().get(0).getNodeID()+":" + poll.getChangesAvailable().getHighWaterMark().get(0).getOriginatingUSN()); + } + } + } + } + + @Override + public boolean cancel() { + timer.cancel(); + return super.cancel(); + } + + /** + * someone told me there's a change available, we retrieved it + * and are processing the changes locally. + * + * @param rec + */ + private void persistChangeRecord(ChangeRecord rec) { + if (rec == null) { + return; + } + logger.debug("_______________________Remote change request " + rec.getChangeID().getNodeID() + ":" + rec.getChangeID().getOriginatingUSN()); + + if (rec.getChangeID().getNodeID().equalsIgnoreCase(getNode())) { + logger.info("Just received a change record that i created, ignoring...."); + return; + } + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + org.apache.juddi.model.ChangeRecord mapChangeRecord = null; + /** + * In nodes that support pre-bundled replication + * responses, the recipient of the get_changeRecords + * message MAY return more change records than requested + * by the caller. In this scenario, the caller MUST also + * be prepared to deal with such redundant changes where + * a USN is less than the USN specified in the + * changesAlreadySeen highWaterMarkVector. + */ + + try { + tx.begin(); + //check to see if we have this update already + Query createQuery = em.createQuery("select c from ChangeRecord c where c.nodeID=:node and c.originatingUSN=:oid"); + createQuery.setParameter("node", rec.getChangeID().getNodeID()); + createQuery.setParameter("oid", rec.getChangeID().getOriginatingUSN()); + Object existingrecord = null; + try { + existingrecord = createQuery.getSingleResult(); + } catch (Exception ex) { + logger.debug("error checking to see if change record exists already (expected failure)", ex); + } + if (existingrecord != null) { + logger.info("I've already processed change record " + rec.getChangeID().getNodeID() + " " + rec.getChangeID().getOriginatingUSN()); + return; + } + //if it didn't come from here and i haven't seen it yet + ReplicationNotifier.EnqueueRetransmit(rec); + //the remotechange record rec must also be persisted!! + mapChangeRecord = MappingApiToModel.mapChangeRecord(rec); + mapChangeRecord.setId(null); + mapChangeRecord.setIsAppliedLocally(true); + em.persist(mapChangeRecord); + tx.commit(); + logger.info("Remote CR saved, it was from " + mapChangeRecord.getNodeID() //this is the origin of the change + + " USN:" + mapChangeRecord.getOriginatingUSN() + + " Type:" + mapChangeRecord.getRecordType().name() + + " Key:" + mapChangeRecord.getEntityKey() + + " Local id from sender:" + mapChangeRecord.getId()); + tx = em.getTransaction(); + tx.begin(); + // + + if (rec.getChangeRecordDelete() != null) { + if (rec.getChangeRecordDelete() != null && rec.getChangeRecordDelete().getBindingKey() != null && !"".equalsIgnoreCase(rec.getChangeRecordDelete().getBindingKey())) { + //delete a binding template + UddiEntity ue = em.find(BindingTemplate.class, rec.getChangeRecordDelete().getBindingKey()); + validateNodeIdMisMatches(ue, getNode()); + pub.deleteBinding(rec.getChangeRecordDelete().getBindingKey(), em); + } + if (rec.getChangeRecordDelete() != null && rec.getChangeRecordDelete().getBusinessKey() != null && !"".equalsIgnoreCase(rec.getChangeRecordDelete().getBusinessKey())) { + //delete a business + UddiEntity ue = em.find(BusinessEntity.class, rec.getChangeRecordDelete().getBusinessKey()); + validateNodeIdMisMatches(ue, getNode()); + pub.deleteBusiness(rec.getChangeRecordDelete().getBusinessKey(), em); + } + if (rec.getChangeRecordDelete() != null && rec.getChangeRecordDelete().getServiceKey() != null && !"".equalsIgnoreCase(rec.getChangeRecordDelete().getServiceKey())) { + UddiEntity ue = em.find(BusinessService.class, rec.getChangeRecordDelete().getServiceKey()); + validateNodeIdMisMatches(ue, getNode()); + //delete a service + pub.deleteService(rec.getChangeRecordDelete().getServiceKey(), em); + } + if (rec.getChangeRecordDelete() != null && rec.getChangeRecordDelete().getTModelKey() != null && !"".equalsIgnoreCase(rec.getChangeRecordDelete().getTModelKey())) { + //delete a tmodel + /** + * The changeRecordDelete for a + * tModel does not correspond to + * any API described in this + * specification and should only + * appear in the replication + * stream as the result of an + * administrative function to + * permanently remove a tModel. + */ + UddiEntity tm = em.find(Tmodel.class, rec.getChangeRecordDelete().getTModelKey()); + if (tm != null) { + validateNodeIdMisMatches(tm, getNode()); + em.remove(tm); + } else { + logger.error("failed to adminstratively delete tmodel because it doesn't exist. " + rec.getChangeRecordDelete().getTModelKey()); + } + //pub.deleteTModel(rec.getChangeRecordDelete().getTModelKey(), em); + } + } + if (rec.getChangeRecordDeleteAssertion() != null && rec.getChangeRecordDeleteAssertion().getPublisherAssertion() != null) { + //delete a pa template + pub.deletePublisherAssertion(rec.getChangeRecordDeleteAssertion(), em); + } + +// + // + if (rec.getChangeRecordNewData() != null) { + + //The operationalInfo element MUST contain the operational information associated with the indicated new data. + if (rec.getChangeRecordNewData().getOperationalInfo() == null) { + logger.warn("Inbound replication data does not have the required OperationalInfo element and is NOT spec compliant. Data will be ignored"); + } else { + if (rec.getChangeRecordNewData().getOperationalInfo().getNodeID() == null) { + throw new Exception("Inbound replication data is missiong node id! Change will not be applied"); + } + if (rec.getChangeRecordNewData().getOperationalInfo().getNodeID().equalsIgnoreCase(getNode())) { + logger.warn("Inbound replication data is modifying locally owned data. This is not allowed, except for custody transfer"); + } + if (rec.getChangeRecordNewData().getBindingTemplate() != null) { + //fetch the binding template if it exists already + //if it exists, + // confirm the owning node, it shouldn't be the local node id, if it is, throw + // the owning node should be the same as it was before + + BusinessService model = em.find(org.apache.juddi.model.BusinessService.class, rec.getChangeRecordNewData().getBindingTemplate().getServiceKey()); + if (model == null) { + logger.error("Replication error, attempting to insert a binding where the service doesn't exist yet"); + } else { + validateNodeIdMatches(rec.getChangeRecordNewData().getOperationalInfo().getNodeID(), model.getNodeId()); + + org.apache.juddi.model.BindingTemplate bt = em.find(org.apache.juddi.model.BindingTemplate.class, rec.getChangeRecordNewData().getBindingTemplate().getBindingKey()); + if (bt != null) { + //ValidateNodeIdMatches(node, bt.getNodeId()); + em.remove(bt); + } + bt = new BindingTemplate(); + MappingApiToModel.mapBindingTemplate(rec.getChangeRecordNewData().getBindingTemplate(), bt, model); + MappingApiToModel.mapOperationalInfo(bt, rec.getChangeRecordNewData().getOperationalInfo()); + // MappingApiToModel.mapOperationalInfoIncludingChildren(model, rec.getChangeRecordNewData().getOperationalInfo()); + em.persist(bt); + } + + } else if (rec.getChangeRecordNewData().getBusinessEntity() != null) { + + BusinessEntity model = em.find(org.apache.juddi.model.BusinessEntity.class, rec.getChangeRecordNewData().getBusinessEntity().getBusinessKey()); + if (model != null) { + //if the owner of the new data is me, and the update didn't originate from me + if (rec.getChangeRecordNewData().getOperationalInfo().getNodeID().equals(getNode()) + && !model.getNodeId().equals(getNode())) { + if (model.getIsTransferInProgress()) { + //allow the transfer + MappingApiToModel.mapBusinessEntity(rec.getChangeRecordNewData().getBusinessEntity(), model); + MappingApiToModel.mapOperationalInfo(model, rec.getChangeRecordNewData().getOperationalInfo()); + MappingApiToModel.mapOperationalInfoIncludingChildren(model, rec.getChangeRecordNewData().getOperationalInfo()); + model.setIsTransferInProgress(false); + em.merge(model); + } else { + //block it, unexpected transfer + throw new Exception("Unexpected entity transfer to to node " + getNode() + " from " + rec.getChangeID().getNodeID()); + } + + } else if (rec.getChangeRecordNewData().getOperationalInfo().getNodeID().equals(getNode()) + && model.getNodeId().equals(getNode())) { + //if destination is here and it's staying here, then this is strange also + //someone else updated one of my records + throw new Exception("unexpected modification of records that this server owns, " + model.getEntityKey()); + } else if (!rec.getChangeRecordNewData().getOperationalInfo().getNodeID().equals(getNode()) + && model.getNodeId().equals(getNode())) { + //this is also strange, destination is elsewhere however it's owned by me. + throw new Exception("unexpected transfer from this node to elsewhere, possible that the key in question exists at two places prior to replication sync, " + model.getEntityKey()); + + } else if (!rec.getChangeRecordNewData().getOperationalInfo().getNodeID().equals(getNode()) + && !model.getNodeId().equals(getNode())) { + //changes on a remote node, for an existing item + MappingApiToModel.mapBusinessEntity(rec.getChangeRecordNewData().getBusinessEntity(), model); + MappingApiToModel.mapOperationalInfoIncludingChildren(model, rec.getChangeRecordNewData().getOperationalInfo()); + em.merge(model); + + } + + } else { + model = new BusinessEntity(); + MappingApiToModel.mapBusinessEntity(rec.getChangeRecordNewData().getBusinessEntity(), model); + MappingApiToModel.mapOperationalInfoIncludingChildren(model, rec.getChangeRecordNewData().getOperationalInfo()); + em.persist(model); + } + } + if (rec.getChangeRecordNewData().getBusinessService() != null) { + BusinessEntity find = em.find(org.apache.juddi.model.BusinessEntity.class, rec.getChangeRecordNewData().getBusinessService().getBusinessKey()); + if (find == null) { + logger.error("Replication error, attempting to insert a service where the business doesn't exist yet"); + } else { + + org.apache.juddi.model.BusinessService model = null; + model = em.find(org.apache.juddi.model.BusinessService.class, rec.getChangeRecordNewData().getBusinessService().getServiceKey()); + if (model != null) { + validateNodeIdMatches(rec.getChangeRecordNewData().getOperationalInfo().getNodeID(), model.getNodeId()); + em.remove(model); + } + + model = new org.apache.juddi.model.BusinessService(); + MappingApiToModel.mapBusinessService(rec.getChangeRecordNewData().getBusinessService(), model, find); + MappingApiToModel.mapOperationalInfo(model, rec.getChangeRecordNewData().getOperationalInfo()); + MappingApiToModel.mapOperationalInfoIncludingChildren(model, rec.getChangeRecordNewData().getOperationalInfo()); + + em.persist(model); + } + + } else if (rec.getChangeRecordNewData().getTModel() != null) { + + Tmodel model = em.find(org.apache.juddi.model.Tmodel.class, rec.getChangeRecordNewData().getTModel().getTModelKey()); + if (model != null) { + //in the case of a transfer + //if the new entity is being transfer to ME, accept and i didn't previously own it, but only if the local record is flagged as transferable + //meaning, only accept if i'm expecting a transfer + if (rec.getChangeRecordNewData().getOperationalInfo().getNodeID().equals(getNode()) + && !model.getNodeId().equals(getNode())) { + if (model.getIsTransferInProgress()) { + //allow the transfer + em.remove(model); + model = new Tmodel(); + MappingApiToModel.mapTModel(rec.getChangeRecordNewData().getTModel(), model); + MappingApiToModel.mapOperationalInfo(model, rec.getChangeRecordNewData().getOperationalInfo()); + model.setIsTransferInProgress(false); + em.persist(model); + } else { + //block it, unexpected transfer + throw new Exception("Unexpected entity transfer to this node from " + rec.getChangeID().getNodeID()); + } + + } else if (rec.getChangeRecordNewData().getOperationalInfo().getNodeID().equals(getNode()) + && model.getNodeId().equals(getNode())) { + //if destination is here and it's staying here, then this is strange also + //someone else updated one of my records + throw new Exception("unexpected modification of records that this server owns, " + model.getEntityKey()); + } else if (!rec.getChangeRecordNewData().getOperationalInfo().getNodeID().equals(getNode()) + && model.getNodeId().equals(getNode())) { + //this is also strange, destination is elsewhere however it's owned by me. + throw new Exception("unexpected transfer from this node to elsewhere, possible that the key in question exists at two places prior to replication sync, " + model.getEntityKey()); + + } else if (!rec.getChangeRecordNewData().getOperationalInfo().getNodeID().equals(getNode()) + && !model.getNodeId().equals(getNode())) { + //changes on a remote node, for an existing item + em.remove(model); + model = new Tmodel(); + MappingApiToModel.mapTModel(rec.getChangeRecordNewData().getTModel(), model); + + MappingApiToModel.mapOperationalInfo(model, rec.getChangeRecordNewData().getOperationalInfo()); + + em.persist(model); + + } + } else { + model = new Tmodel(); + MappingApiToModel.mapTModel(rec.getChangeRecordNewData().getTModel(), model); + + MappingApiToModel.mapOperationalInfo(model, rec.getChangeRecordNewData().getOperationalInfo()); + + em.persist(model); + } + } + + } + + } +// + + // changeRecordNull no action needed + // changeRecordHide tmodel only + // + if (rec.getChangeRecordHide() != null) { + /* + A changeRecordHide element corresponds to the behavior of hiding a tModel described in the delete_tModel in the Publish API section of this Specification. A tModel listed in a changeRecordHide should be marked as hidden, so that it is not returned in response to a find_tModel API call. + + The changeRecordHide MUST contain a modified timestamp to allow multi-node registries to calculate consistent modifiedIncludingChildren timestamps as described in Section 3.8 operationalInfo Structure. + */ + String key = rec.getChangeRecordHide().getTModelKey(); + org.apache.juddi.model.Tmodel existing = em.find(org.apache.juddi.model.Tmodel.class, key); + if (existing == null) { + logger.error("Unexpected delete/hide tmodel message received for non existing key " + key); + } else { + //no one else can delete/hide my tmodel + validateNodeIdMisMatches(existing, getNode()); + existing.setDeleted(true); + existing.setModified(rec.getChangeRecordHide().getModified().toGregorianCalendar().getTime()); + existing.setModifiedIncludingChildren(rec.getChangeRecordHide().getModified().toGregorianCalendar().getTime()); + em.persist(existing); + } + } +// + + // + if (rec.getChangeRecordPublisherAssertion() != null) { + + logger.info("Repl CR Publisher Assertion"); + //TODO are publisher assertions owned by a given node? + PublisherAssertionId paid = new PublisherAssertionId(rec.getChangeRecordPublisherAssertion().getPublisherAssertion().getFromKey(), rec.getChangeRecordPublisherAssertion().getPublisherAssertion().getToKey()); + org.apache.juddi.model.PublisherAssertion model = em.find(org.apache.juddi.model.PublisherAssertion.class, paid); + if (model != null) { + logger.info("Repl CR Publisher Assertion - Existing"); + + if (rec.getChangeRecordPublisherAssertion().isFromBusinessCheck()) { + model.setFromCheck("true"); + } else { + model.setFromCheck("false"); + } + + if (rec.getChangeRecordPublisherAssertion().isToBusinessCheck()) { + model.setToCheck("true"); + } else { + model.setToCheck("false"); + } + + model.setKeyName(rec.getChangeRecordPublisherAssertion().getPublisherAssertion().getKeyedReference().getKeyName()); + model.setKeyValue(rec.getChangeRecordPublisherAssertion().getPublisherAssertion().getKeyedReference().getKeyValue()); + model.setTmodelKey(rec.getChangeRecordPublisherAssertion().getPublisherAssertion().getKeyedReference().getTModelKey()); + model.setModified(rec.getChangeRecordPublisherAssertion().getModified().toGregorianCalendar().getTime()); + //model.setSignatures(MappingApiToModel.mapApiSignaturesToModelSignatures(rec.getChangeRecordPublisherAssertion().getPublisherAssertion().getSignature())); + if ("false".equalsIgnoreCase(model.getFromCheck()) + && "false".equalsIgnoreCase(model.getToCheck())) { + logger.warn("!!!New publisher assertion is both false and false, strange. no need to save it then!"); + em.remove(model); + } + em.merge(model); + } else { + logger.info("Repl CR Publisher Assertion - new PA"); + + model = new PublisherAssertion(); + MappingApiToModel.mapPublisherAssertion(rec.getChangeRecordPublisherAssertion().getPublisherAssertion(), model); + model.setBusinessEntityByFromKey(null); + model.setBusinessEntityByToKey(null); + model.setBusinessEntityByFromKey(em.find(BusinessEntity.class, rec.getChangeRecordPublisherAssertion().getPublisherAssertion().getFromKey())); + model.setBusinessEntityByToKey(em.find(BusinessEntity.class, rec.getChangeRecordPublisherAssertion().getPublisherAssertion().getToKey())); + + if (rec.getChangeRecordPublisherAssertion().isFromBusinessCheck()) { + model.setFromCheck("true"); + } else { + model.setFromCheck("false"); + } + + if (rec.getChangeRecordPublisherAssertion().isToBusinessCheck()) { + model.setToCheck("true"); + } else { + model.setToCheck("false"); + } + model.setModified(rec.getChangeRecordPublisherAssertion().getModified().toGregorianCalendar().getTime()); + em.persist(model); + } + } +// + + if (rec.isAcknowledgementRequested()) { + ChangeRecord posack = new ChangeRecord(); + posack.setChangeRecordAcknowledgement(new ChangeRecordAcknowledgement()); + posack.getChangeRecordAcknowledgement().setAcknowledgedChange(rec.getChangeID()); + posack.setAcknowledgementRequested(false); + ReplicationNotifier.enqueue(MappingApiToModel.mapChangeRecord(posack)); + } + if (rec.getChangeRecordNewDataConditional() != null) { + + if (rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo().getNodeID() == null) { + throw new Exception("Inbound replication data is missiong node id!"); + } + + //The operationalInfo element MUST contain the operational information associated with the indicated new data. + if (rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo() == null) { + logger.warn("Inbound replication data does not have the required OperationalInfo element and is NOT spec compliant. Data will be ignored"); + } else { + if (rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBindingTemplate() != null) { + //fetch the binding template if it exists already + //if it exists, + // confirm the owning node, it shouldn't be the local node id, if it is, throw + // the owning node should be the same as it was before + + BusinessService model = em.find(org.apache.juddi.model.BusinessService.class, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBindingTemplate().getServiceKey()); + if (model == null) { + logger.error("Replication error, attempting to insert a binding where the service doesn't exist yet"); + } else { + + org.apache.juddi.model.BindingTemplate bt = em.find(org.apache.juddi.model.BindingTemplate.class, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBindingTemplate().getBindingKey()); + if (bt != null) { + validateNodeIdMatches(rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo().getNodeID(), bt.getNodeId()); + + em.remove(bt); + } + bt = new BindingTemplate(); + MappingApiToModel.mapBindingTemplate(rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBindingTemplate(), bt, model); + MappingApiToModel.mapOperationalInfo(bt, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo()); + // MappingApiToModel.mapOperationalInfoIncludingChildren(model, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo()); + em.persist(bt); + } + + } else if (rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBusinessEntity() != null) { + + BusinessEntity model = em.find(org.apache.juddi.model.BusinessEntity.class, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBusinessEntity().getBusinessKey()); + if (model != null) { + validateNodeIdMatches(rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo().getNodeID(), model.getNodeId()); + //TODO revisit access control rules + em.remove(model); + } + model = new BusinessEntity(); + MappingApiToModel.mapBusinessEntity(rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBusinessEntity(), model); + // MappingApiToModel.mapOperationalInfo(model, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo()); + + MappingApiToModel.mapOperationalInfoIncludingChildren(model, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo()); + logger.warn("Name size on save is " + model.getBusinessNames().size()); + em.persist(model); + + } + if (rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBusinessService() != null) { + BusinessEntity find = em.find(org.apache.juddi.model.BusinessEntity.class, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBusinessService().getBusinessKey()); + if (find == null) { + logger.error("Replication error, attempting to insert a service where the business doesn't exist yet"); + } else { + + org.apache.juddi.model.BusinessService model = null; + model = em.find(org.apache.juddi.model.BusinessService.class, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBusinessService().getServiceKey()); + if (model != null) { + validateNodeIdMatches(rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo().getNodeID(), model.getNodeId()); + em.remove(model); + } + + model = new org.apache.juddi.model.BusinessService(); + MappingApiToModel.mapBusinessService(rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getBusinessService(), model, find); + MappingApiToModel.mapOperationalInfo(model, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo()); + MappingApiToModel.mapOperationalInfoIncludingChildren(model, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo()); + + em.persist(model); + } + + } else if (rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getTModel() != null) { + + Tmodel model = em.find(org.apache.juddi.model.Tmodel.class, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getTModel().getTModelKey()); + if (model != null) { + validateNodeIdMatches(rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo().getNodeID(), model.getNodeId()); + em.remove(model); + } + model = new Tmodel(); + MappingApiToModel.mapTModel(rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getTModel(), model); + + MappingApiToModel.mapOperationalInfo(model, rec.getChangeRecordNewDataConditional().getChangeRecordNewData().getOperationalInfo()); + + em.persist(model); + } + + } + + } + if (rec.getChangeRecordNull() != null) { + //No action required + + } + if (rec.getChangeRecordCorrection() != null) { + //TODO implement + + } + if (rec.getChangeRecordConditionFailed() != null) { + //TODO implement + + } + tx.commit(); + + } catch (Exception drfm) { + + logger.warn("Error applying the change record! ", drfm); + StringWriter sw = new StringWriter(); + JAXB.marshal(rec, sw); + logger.warn("This is the record that failed to persist: " + sw.toString()); + if (tx.isActive()) { + tx.rollback(); + } + if (mapChangeRecord != null) { + //set the change record's isApplied to false + try { + tx = em.getTransaction(); + tx.begin(); + mapChangeRecord.setIsAppliedLocally(false); + em.merge(mapChangeRecord); + tx.commit(); + } catch (Exception e) { + logger.error("error updating change record!!", e); + if (tx.isActive()) { + tx.rollback(); + } + } + } else { + logger.fatal("whoa! change record is null when saving a remote change record, this is unexpected and should be reported"); + } + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + private HighWaterMarkVectorType getLastChangeRecordFrom(String sourcenode) { + HighWaterMarkVectorType ret = new HighWaterMarkVectorType(); + ChangeRecordIDType cid = new ChangeRecordIDType(); + cid.setNodeID(sourcenode); + cid.setOriginatingUSN(0L); + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + //Long id = 0L; + try { + cid.setOriginatingUSN((Long) em.createQuery("select MAX(e.originatingUSN) from ChangeRecord e where e.nodeID = :node") + .setParameter("node", sourcenode) + .getSingleResult()); + } catch (Exception ex) { + logger.info("unexpected error searching for last record from " + sourcenode, ex); + } + + tx.rollback(); + + } catch (Exception drfm) { + logger.warn("error caught fetching newest record from node " + sourcenode, drfm); + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + logger.info("Highest known record for " + sourcenode + " is " + cid.getOriginatingUSN()); + ret.getHighWaterMark().add(cid); + + return ret; + } + + private void enqueueAllReceivingNodes() { + if (queue == null) { + queue = new ConcurrentLinkedQueue(); + } + //get the replication config + //get everyone we are expecting to receive data from, then enqueue them for pulling + ReplicationConfiguration repcfg = ReplicationNotifier.FetchEdges(); + if (repcfg == null) { + return; + } + Set allnodes = new HashSet(); + for (int i = 0; i < repcfg.getOperator().size(); i++) { + allnodes.add(repcfg.getOperator().get(i).getOperatorNodeID()); + } + Set receivers = new HashSet(); + if (repcfg.getCommunicationGraph() == null + || repcfg.getCommunicationGraph().getEdge().isEmpty()) { + //no edges or graph defined, default to the operator list + for (org.uddi.repl_v3.Operator o : repcfg.getOperator()) { + //no need to tell myself about a change at myself + if (!o.getOperatorNodeID().equalsIgnoreCase(getNode())) { + receivers.add(o.getOperatorNodeID()); + } + } + } else { + //repcfg.getCommunicationGraph() + Iterator iterator = repcfg.getCommunicationGraph().getEdge().iterator(); + while (iterator.hasNext()) { + Edge next = iterator.next(); + + if (next.getMessageReceiver().equalsIgnoreCase(getNode())) { + receivers.add(next.getMessageSender()); + } + + } + + } + for (String s : receivers) { + //this is a list of nodes that this node is expecting updates from + //here are we ticking the notification engine to ping the remove service for updates + for (String nodeping : allnodes) { + queue.add(new NotifyChangeRecordsAvailable(s, getLastChangeRecordFrom(nodeping))); + //for each node we are expecting data from, go fetch it, along the way, we'll request all data for all nodes + //that we know about + } + + } + } + + } + + /** + * used to check for alterations on *this node's data from another node, + * which isn't allowed + * + * @param ue + * @param node + * @throws Exception + */ + private static void validateNodeIdMisMatches(UddiEntity ue, String node) throws Exception { + if (ue == null) { + return;//object doesn't exist + } + if (ue.getNodeId().equals(node)) { + throw new Exception("Alert! attempt to alter locally owned entity " + ue.getEntityKey() + " owned by " + ue.getAuthorizedName() + "@" + ue.getNodeId()); + } + } + + /** + * use to validate that changed data maintained ownership, except for + * business entities and tmodels since they allow transfer + * + * @param newNodeId + * @param currentOwningNode + * @throws Exception + */ + private void validateNodeIdMatches(String newNodeId, String currentOwningNode) throws Exception { + if (newNodeId == null || currentOwningNode == null) { + throw new Exception("either the local node ID is null or the inbound replication data's node id is null"); + } + //only time this is allowed is custody transfer + if (!newNodeId.equals(currentOwningNode)) { + logger.info("AUDIT, custody transfer from node, " + currentOwningNode + " to " + newNodeId + " current node is " + getNode()); + //throw new Exception("node id mismatch!"); + } + + //if i already have a record and "own it" and the remote node has a record with the same key, reject the update + //1.5.8 + /** + * Each node has custody of a portion of the aggregate data + * managed by the registry of which it is a part. Each datum is + * by definition in the custody of exactly one such node. A + * datum in this context can be a businessEntity, a + * businessService, a bindingTemplate, a tModel, or a + * publisherAssertion. Changes to a datum in the registry MUST + * originate at the node which is the custodian of the datum. + * The registry defines the policy for data custody and, if + * allowed, the custodian node for a given datum can be changed; + * such custody transfer processes are discussed in Section 5.4 + * Custody and Ownership Transfer API. + */ + //so someone else attempted to update one of my records, reject it + if (newNodeId.equals(getNode())) { + //throw new Exception("node id mismatch! this node already has a record for key " + newDataOperationalInfo.getEntityKey() + " and I'm the authority for it."); + } + } + + private synchronized UDDIReplicationPortType getReplicationClient(String node) { + if (cache.containsKey(node)) { + return cache.get(node); + } + UDDIService svc = new UDDIService(); + UDDIReplicationPortType replicationClient = svc.getUDDIReplicationPort(); + TransportSecurityHelper.applyTransportSecurity((BindingProvider) replicationClient); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + StringBuilder sql = new StringBuilder(); + sql.append("select c from ReplicationConfiguration c order by c.serialNumber desc"); + //sql.toString(); + Query qry = em.createQuery(sql.toString()); + qry.setMaxResults(1); + + org.apache.juddi.model.ReplicationConfiguration resultList = (org.apache.juddi.model.ReplicationConfiguration) qry.getSingleResult(); + for (Operator o : resultList.getOperator()) { + if (o.getOperatorNodeID().equalsIgnoreCase(node)) { + ((BindingProvider) replicationClient).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, o.getSoapReplicationURL()); + cache.put(node, replicationClient); + return replicationClient; + } + } + tx.rollback(); + + } catch (Exception ex) { + logger.fatal("Node not found!" + node, ex); + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + //em.close(); + return null; + + } + private Map cache = new HashMap(); + + /** + * @since 3.3 + * @param body + * @return + * @throws DispositionReportFaultMessage + */ + public String doPing(DoPing body) throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(ReplicationQuery.DO_PING, QueryStatus.SUCCESS, procTime); + + return getNode(); + + } + + @SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE) + @WebResult(name = "changeRecords", targetNamespace = "urn:uddi-org:repl_v3", partName = "body") + // @WebMethod(operationName = "get_changeRecords", action = "get_changeRecords") + @Override + public org.uddi.repl_v3.ChangeRecords getChangeRecords( + @WebParam(partName = "body", name = "get_changeRecords", targetNamespace = "urn:uddi-org:repl_v3") org.uddi.repl_v3.GetChangeRecords body + ) throws DispositionReportFaultMessage, RemoteException { + long startTime = System.currentTimeMillis(); + String requestingNode = body.getRequestingNode(); + HighWaterMarkVectorType changesAlreadySeen = body.getChangesAlreadySeen(); + BigInteger responseLimitCount = body.getResponseLimitCount(); + HighWaterMarkVectorType responseLimitVector = body.getResponseLimitVector(); + + new ValidateReplication(null).validateGetChangeRecords(requestingNode, changesAlreadySeen, responseLimitCount, responseLimitVector, FetchEdges(), ctx); + + //TODO should we validate that "requestingNode" is in the replication config? + List ret = new ArrayList(); + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + + /** + * More specifically, the recipient determines the particular + * change records that are returned by comparing the originating + * USNs in the caller’s high water mark vector with the + * originating USNs of each of the changes the recipient has + * seen from others or generated by itself. The recipient SHOULD + * only return change records that have originating USNs that + * are greater than those listed in the changesAlreadySeen + * highWaterMarkVector and less than the limit required by + * either the responseLimitCount or the responseLimitVector. + * + * + * Part of the message is a high water mark vector that contains + * for each node of the registry the originating USN of the most + * recent change record that has been successfully processed by + * the invocating node + */ + try { + int maxrecords = AppConfig.getConfiguration().getInt(Property.JUDDI_REPLICATION_GET_CHANGE_RECORDS_MAX, 100); + if (responseLimitCount != null) { + maxrecords = responseLimitCount.intValue(); + } + tx.begin(); + Long firstrecord = 0L; + Long lastrecord = null; + Query createQuery = null; +//SELECT t0.id, t0.change_contents, t0.entity_key, t0.appliedlocal, t0.node_id, t0.orginating_usn, t0.record_type FROM j3_chg_record t0 WHERE (t0.id > NULL AND t0.node_id = ?) ORDER BY t0.id ASC + if (changesAlreadySeen != null) { + //this is basically a lower limit (i.e. the newest record that was processed by the requestor + //therefore we want the oldest record stored locally to return to the requestor for processing + for (int i = 0; i < changesAlreadySeen.getHighWaterMark().size(); i++) { + firstrecord = changesAlreadySeen.getHighWaterMark().get(i).getOriginatingUSN(); + if (firstrecord == null) { + firstrecord = 0L; + } + if (changesAlreadySeen.getHighWaterMark().get(i).getNodeID().equals(getNode())) { + //special case, search by database id + createQuery = em.createQuery("select e from ChangeRecord e where " + + "(e.id > :inbound AND e.nodeID = :node) " + + "order by e.id ASC"); + + } else { + createQuery = em.createQuery("select e from ChangeRecord e where " + + "e.originatingUSN > :inbound AND e.nodeID = :node " + + "order by e.originatingUSN ASC"); + } + logger.info("Query db for replication changes, lower index is " + (firstrecord) + " last index " + lastrecord + " record limit " + maxrecords); + logger.info("This node is " + getNode() + ", request is for data originated from " + changesAlreadySeen.getHighWaterMark().get(i).getNodeID() + " and it's being sent back to " + requestingNode); + + createQuery.setMaxResults(maxrecords); + createQuery.setParameter("inbound", firstrecord); + createQuery.setParameter("node", changesAlreadySeen.getHighWaterMark().get(i).getNodeID()); + List records = (List) createQuery.getResultList(); + logger.info(records.size() + " CR records returned from query"); + for (int x = 0; x < records.size(); x++) { + ChangeRecord r = MappingModelToApi.mapChangeRecord(records.get(x)); + //if (!Excluded(changesAlreadySeen, r)) { + ret.add(r); + //} + + } + } + } /*if (responseLimitVector != null) { + //using responseLimitVector, indicating for each node in the graph the first change originating there that he does not wish to be returned. + //upper limit basically + for (int i = 0; i < responseLimitVector.getHighWaterMark().size(); i++) { + //if (responseLimitVector.getHighWaterMark().get(i).getNodeID().equals(node)) { + lastrecord = responseLimitVector.getHighWaterMark().get(i).getOriginatingUSN(); + //} + } + }*/ else { + if (firstrecord == null) { + firstrecord = 0L; + } + //assume that they just want records that originated from here? + logger.info("Query db for replication changes, lower index is " + (firstrecord) + " last index " + lastrecord + " record limit " + maxrecords); + logger.info("This node is " + getNode() + " requesting node " + requestingNode); + + if (lastrecord != null) { + createQuery = em.createQuery("select e from ChangeRecord e where " + + "(e.id > :inbound AND e.nodeID = :node AND e.id < :lastrecord) " + + "order by e.id ASC"); + createQuery.setParameter("lastrecord", lastrecord); + } else { + createQuery = em.createQuery("select e from ChangeRecord e where " + + "(e.id > :inbound AND e.nodeID = :node) " + + "order by e.id ASC"); + } + createQuery.setMaxResults(maxrecords); + createQuery.setParameter("inbound", firstrecord); + createQuery.setParameter("node", getNode()); + + List records = (List) createQuery.getResultList(); + logger.info(records.size() + " CR records returned from query"); + for (int i = 0; i < records.size(); i++) { + ChangeRecord r = MappingModelToApi.mapChangeRecord(records.get(i)); + //if (!Excluded(changesAlreadySeen, r)) { + ret.add(r); + //} + + } + } + tx.rollback(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(ReplicationQuery.GET_CHANGERECORDS, + QueryStatus.SUCCESS, procTime); + + } catch (Exception ex) { + logger.fatal("Error, this node is: " + getNode(), ex); + throw new FatalErrorException(new ErrorMessage("E_fatalError", ex.getMessage())); + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + logger.info("Change records returned for " + requestingNode + ": " + ret.size()); + //JAXB.marshal(ret, System.out); + ChangeRecords x = new ChangeRecords(); + x.getChangeRecord().addAll(ret); + //JAXB.marshal(x, System.out); + return x; + } + + /** + * This UDDI API message provides a means to obtain a list of + * highWaterMark element containing the highest known USN for all nodes + * in the replication graph. If there is no graph, we just return the + * local bits + * + * @return + * @throws DispositionReportFaultMessage + */ + @Override + public List getHighWaterMarks() + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + List ret = new ArrayList(); + + //fetch from database the highest known watermark + ReplicationConfiguration FetchEdges = FetchEdges(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + HashMap map = new HashMap(); + try { + tx.begin(); + if (FetchEdges != null) { + Iterator it = FetchEdges.getCommunicationGraph().getNode().iterator(); + while (it.hasNext()) { + String nextNode = it.next(); + if (!nextNode.equals(getNode())) { + if (!map.containsKey(nextNode)) { + Long id = 0L; + try { + id = (Long) em.createQuery("select e.originatingUSN from ChangeRecord e where e.nodeID = :node order by e.originatingUSN desc").setParameter("node", nextNode).setMaxResults(1).getSingleResult(); + } catch (Exception ex) { + logger.debug(ex); + } + if (id == null) { + id = 0L; + //per the spec + } + map.put(nextNode, id); + + } + } + } + } + //dont forget this node + Query setMaxResults = em.createQuery("select (e.id) from ChangeRecord e where e.nodeID = :node order by e.id desc") + .setParameter("node", getNode()).setMaxResults(1); + Long id =null; + if (setMaxResults.getResultList().isEmpty()) { + //this can happen at or near startup + id = 0L; + } else { + id = (Long) em.createQuery("select (e.id) from ChangeRecord e where e.nodeID = :node order by e.id desc") + .setParameter("node", getNode()).setMaxResults(1).getSingleResult(); + } + ChangeRecordIDType x = new ChangeRecordIDType(); + x.setNodeID(getNode()); + x.setOriginatingUSN(id); + ret.add(x); + + tx.rollback(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(ReplicationQuery.GET_HIGHWATERMARKS, QueryStatus.SUCCESS, procTime); + + } catch (Exception drfm) { + logger.fatal("Error, this node is: " + getNode(), drfm); + throw new FatalErrorException(new ErrorMessage("E_fatalError", drfm.getMessage())); + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + Iterator> iterator = map.entrySet().iterator(); + while (iterator.hasNext()) { + Map.Entry next = iterator.next(); + ret.add(new ChangeRecordIDType(next.getKey(), next.getValue())); + } + return ret; + } + + /** + * this means that another node has a change and we need to pick up the + * change and apply it to our local database. + * + * @param body + * @throws DispositionReportFaultMessage + */ + @Override + public void notifyChangeRecordsAvailable(NotifyChangeRecordsAvailable body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + //some other node just told us there's new records available, call + //getChangeRecords from the remote node asynch + new ValidateReplication(null).validateNotifyChangeRecordsAvailable(body, ctx); + + logger.info(body.getNotifyingNode() + " just told me that there are change records available, enqueuing...size is " + queue.size() + " this node is " + getNode()); + //if (!queue.contains(body.getNotifyingNode())) { + queue.add(body); + //} + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(ReplicationQuery.NOTIFY_CHANGERECORDSAVAILABLE, + QueryStatus.SUCCESS, procTime); + } + private static Queue queue = null; + + /** + * transfers custody of an entity from node1/user1 to node2/user2 + * + * assume this node is node 2. + * + * user1 on node1 requests a transfer token. node 1 issues the token. + * + * user1 now has a transfer token for their stuff user now takes the + * token to node 2 and calls transferEntities + * + * + * @param body + * @throws DispositionReportFaultMessage + */ + @Override + public void transferCustody(TransferCustody body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + logger.info("Inbound transfer request (via replication api, node to node"); + try { + tx.begin(); + //*this node is transfering data to another node + //ValidateReplication.unsupportedAPICall(); + //a remote node just told me to give up control of some of my entities + + //EntityTransaction tx = em.getTransaction(); + //confirm i have a replication config + boolean ok = false; + ReplicationConfiguration FetchEdges = ReplicationNotifier.FetchEdges(); + if (FetchEdges != null) { + for (int i = 0; i < FetchEdges.getOperator().size(); i++) { + //confirm that the destination node is in the replication config + if (FetchEdges.getOperator().get(i).getOperatorNodeID().equals(body.getTransferOperationalInfo().getNodeID())) { + ok = true; + break; + } + } + } + if (!ok) { + throw new TransferNotAllowedException(new ErrorMessage("E_transferNotAllowedUnknownNode")); + } + + new ValidateReplication(null).validateTransfer(em, body); + + TransferEntities te = new TransferEntities(); + te.setKeyBag(body.getKeyBag()); + te.setTransferToken(body.getTransferToken()); + te.setAuthInfo(null); + //make the change + //enqueue in replication notifier + //discard the token + logger.debug("request validated, processing transfer"); + List executeTransfer = new UDDICustodyTransferImpl().executeTransfer(te, em, body.getTransferOperationalInfo().getAuthorizedName(), body.getTransferOperationalInfo().getNodeID()); + + for (ChangeRecord c : executeTransfer) { + try { + c.setChangeID(new ChangeRecordIDType()); + c.getChangeID().setNodeID(getNode()); + c.getChangeID().setOriginatingUSN(null); + ReplicationNotifier.enqueue(MappingApiToModel.mapChangeRecord(c)); + } catch (UnsupportedEncodingException ex) { + logger.error("", ex); + } + } + /** + * The custodial node must verify that it has granted + * permission to transfer the entities identified and + * that this permission is still valid. This operation + * is comprised of two steps: + * + * 1. Verification that the transferToken was issued by + * it, that it has not expired, that it represents the + * authority to transfer no more and no less than those + * entities identified by the businessKey and tModelKey + * elements and that all these entities are still valid + * and not yet transferred. The transferToken is + * invalidated if any of these conditions are not met. + * + * 2. If the conditions above are met, the custodial + * node will prevent any further changes to the entities + * identified by the businessKey and tModelKey elements + * identified. The entity will remain in this state + * until the replication stream indicates it has been + * successfully processed via the replication stream. + * Upon successful verification of the custody transfer + * request by the custodial node, an empty message is + * returned by it indicating the success of the request + * and acknowledging the custody transfer. Following the + * issue of the empty message, the custodial node will + * submit into the replication stream a + * changeRecordNewData providing in the operationalInfo, + * the nodeID accepting custody of the datum and the + * authorizedName of the publisher accepting ownership. + * The acknowledgmentRequested attribute of this change + * record MUST be set to "true". + * + * + * + * Finally, the custodial node invalidates the + * transferToken in order to prevent additional calls of + * the transfer_entities API. + */ + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(ReplicationQuery.TRANSFER_CUSTODY, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage d) { + logger.error("Unable to process node to node custody transfer ", d); + throw d; + } finally { + if (em != null && em.isOpen()) { + em.close(); + } + if (tx.isActive()) { + tx.rollback(); + } + } + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDISecurityImpl.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDISecurityImpl.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/api/impl/UDDISecurityImpl.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDISecurityImpl.java index c2bf48fb2..7f2f3ef0f 100644 --- a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDISecurityImpl.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDISecurityImpl.java @@ -1,175 +1,175 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.util.Date; -import java.util.UUID; - -import javax.jws.WebService; -import javax.persistence.EntityManager; -import javax.persistence.EntityTransaction; -import javax.xml.ws.WebServiceContext; - -import org.uddi.api_v3.AuthToken; -import org.uddi.api_v3.DiscardAuthToken; -import org.uddi.api_v3.GetAuthToken; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.v3_service.UDDISecurityPortType; - -import org.apache.juddi.api.util.QueryStatus; -import org.apache.juddi.api.util.SecurityQuery; -import org.apache.juddi.config.PersistenceManager; -import org.apache.juddi.mapping.MappingModelToApi; -import org.apache.juddi.model.Publisher; -import org.apache.juddi.v3.auth.Authenticator; -import org.apache.juddi.v3.auth.AuthenticatorFactory; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.UnknownUserException; - -/** - * This class implements the UDDI Security Service and basically handles all authentication requests - * for jUDDI. These authentication requests are routed to the appropriately configured - * authenticator for validation, then persisted in the database until they either - * expire or are discarded. - * @author Jeff Faath (and many others) - */ -@WebService(serviceName="UDDISecurityService", - endpointInterface="org.uddi.v3_service.UDDISecurityPortType", - targetNamespace = "urn:uddi-org:api_v3_portType") -public class UDDISecurityImpl extends AuthenticatedService implements UDDISecurityPortType { - - public static final String AUTH_TOKEN_PREFIX = "authtoken:"; - private UDDIServiceCounter serviceCounter; - - public UDDISecurityImpl() { - super(); - serviceCounter = ServiceCounterLifecycleResource.getServiceCounter(UDDISecurityImpl.class); - } - - /** - * used for unit tests only - * @param ctx - */ - protected UDDISecurityImpl(WebServiceContext ctx) { - super(); - this.ctx = ctx; - serviceCounter = ServiceCounterLifecycleResource.getServiceCounter(UDDISecurityImpl.class); - } - - public void discardAuthToken(DiscardAuthToken body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - this.getEntityPublisher(em, body.getAuthInfo()); - - org.apache.juddi.model.AuthToken modelAuthToken = em.find(org.apache.juddi.model.AuthToken.class, body.getAuthInfo()); - if (modelAuthToken != null) { - modelAuthToken.setLastUsed(new Date()); - modelAuthToken.setNumberOfUses(modelAuthToken.getNumberOfUses() + 1); - modelAuthToken.setTokenState(AUTHTOKEN_RETIRED); - logger.info("AUDIT: AuthToken discarded for " + modelAuthToken.getAuthorizedName() + " from " + getRequestorsIPAddress()); - } - - tx.commit(); - - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(SecurityQuery.DISCARD_AUTHTOKEN, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - logger.info("AUDIT: AuthToken discard request aborted, issued from " + getRequestorsIPAddress()); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(SecurityQuery.DISCARD_AUTHTOKEN, - QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - - public AuthToken getAuthToken(GetAuthToken body) - throws DispositionReportFaultMessage { - - logger.info("AUDIT: AuthToken request for " + body.getUserID() + " from " + getRequestorsIPAddress()); - Authenticator authenticator = AuthenticatorFactory.getAuthenticator(); - - String publisherId = authenticator.authenticate(body.getUserID(), body.getCred()); - - return getAuthToken(publisherId); - } - - public AuthToken getAuthToken(String publisherId) throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - if (publisherId == null || publisherId.length() == 0) - throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidCredentials", publisherId)); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - //Check if this publisher exists - Publisher publisher = em.find(Publisher.class, publisherId); - if (publisher == null) - throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidCredentials", publisherId)); - - // Generate auth token and store it! - String authInfo = AUTH_TOKEN_PREFIX + UUID.randomUUID(); - org.apache.juddi.model.AuthToken modelAuthToken = new org.apache.juddi.model.AuthToken(); - modelAuthToken.setAuthToken(authInfo); - modelAuthToken.setCreated(new Date()); - modelAuthToken.setLastUsed(new Date()); - modelAuthToken.setAuthorizedName(publisherId); - modelAuthToken.setNumberOfUses(0); - modelAuthToken.setTokenState(AUTHTOKEN_ACTIVE); - modelAuthToken.setIPAddress(this.getRequestorsIPAddress()); - em.persist(modelAuthToken); - - org.uddi.api_v3.AuthToken apiAuthToken = new org.uddi.api_v3.AuthToken(); - - MappingModelToApi.mapAuthToken(modelAuthToken, apiAuthToken); - - tx.commit(); - logger.info("AUDIT: AuthToken issued for " + modelAuthToken.getAuthorizedName() + " from " + getRequestorsIPAddress()); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(SecurityQuery.GET_AUTHTOKEN, - QueryStatus.SUCCESS, procTime); - - return apiAuthToken; - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(SecurityQuery.GET_AUTHTOKEN, - QueryStatus.FAILED, procTime); - logger.info("AUDIT: AuthToken issue FAILED " + publisherId + " from " + getRequestorsIPAddress()); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.util.Date; +import java.util.UUID; + +import javax.jws.WebService; +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.xml.ws.WebServiceContext; + +import org.uddi.api_v3.AuthToken; +import org.uddi.api_v3.DiscardAuthToken; +import org.uddi.api_v3.GetAuthToken; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.v3_service.UDDISecurityPortType; + +import org.apache.juddi.api.util.QueryStatus; +import org.apache.juddi.api.util.SecurityQuery; +import org.apache.juddi.config.PersistenceManager; +import org.apache.juddi.mapping.MappingModelToApi; +import org.apache.juddi.model.Publisher; +import org.apache.juddi.v3.auth.Authenticator; +import org.apache.juddi.v3.auth.AuthenticatorFactory; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.UnknownUserException; + +/** + * This class implements the UDDI Security Service and basically handles all authentication requests + * for jUDDI. These authentication requests are routed to the appropriately configured + * authenticator for validation, then persisted in the database until they either + * expire or are discarded. + * @author Jeff Faath (and many others) + */ +@WebService(serviceName="UDDISecurityService", + endpointInterface="org.uddi.v3_service.UDDISecurityPortType", + targetNamespace = "urn:uddi-org:api_v3_portType") +public class UDDISecurityImpl extends AuthenticatedService implements UDDISecurityPortType { + + public static final String AUTH_TOKEN_PREFIX = "authtoken:"; + private UDDIServiceCounter serviceCounter; + + public UDDISecurityImpl() { + super(); + serviceCounter = ServiceCounterLifecycleResource.getServiceCounter(UDDISecurityImpl.class); + } + + /** + * used for unit tests only + * @param ctx + */ + protected UDDISecurityImpl(WebServiceContext ctx) { + super(); + this.ctx = ctx; + serviceCounter = ServiceCounterLifecycleResource.getServiceCounter(UDDISecurityImpl.class); + } + + public void discardAuthToken(DiscardAuthToken body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + this.getEntityPublisher(em, body.getAuthInfo()); + + org.apache.juddi.model.AuthToken modelAuthToken = em.find(org.apache.juddi.model.AuthToken.class, body.getAuthInfo()); + if (modelAuthToken != null) { + modelAuthToken.setLastUsed(new Date()); + modelAuthToken.setNumberOfUses(modelAuthToken.getNumberOfUses() + 1); + modelAuthToken.setTokenState(AUTHTOKEN_RETIRED); + logger.info("AUDIT: AuthToken discarded for " + modelAuthToken.getAuthorizedName() + " from " + getRequestorsIPAddress()); + } + + tx.commit(); + + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(SecurityQuery.DISCARD_AUTHTOKEN, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + logger.info("AUDIT: AuthToken discard request aborted, issued from " + getRequestorsIPAddress()); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(SecurityQuery.DISCARD_AUTHTOKEN, + QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + + public AuthToken getAuthToken(GetAuthToken body) + throws DispositionReportFaultMessage { + + logger.info("AUDIT: AuthToken request for " + body.getUserID() + " from " + getRequestorsIPAddress()); + Authenticator authenticator = AuthenticatorFactory.getAuthenticator(); + + String publisherId = authenticator.authenticate(body.getUserID(), body.getCred()); + + return getAuthToken(publisherId); + } + + public AuthToken getAuthToken(String publisherId) throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + if (publisherId == null || publisherId.length() == 0) + throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidCredentials", publisherId)); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + //Check if this publisher exists + Publisher publisher = em.find(Publisher.class, publisherId); + if (publisher == null) + throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidCredentials", publisherId)); + + // Generate auth token and store it! + String authInfo = AUTH_TOKEN_PREFIX + UUID.randomUUID(); + org.apache.juddi.model.AuthToken modelAuthToken = new org.apache.juddi.model.AuthToken(); + modelAuthToken.setAuthToken(authInfo); + modelAuthToken.setCreated(new Date()); + modelAuthToken.setLastUsed(new Date()); + modelAuthToken.setAuthorizedName(publisherId); + modelAuthToken.setNumberOfUses(0); + modelAuthToken.setTokenState(AUTHTOKEN_ACTIVE); + modelAuthToken.setIPAddress(this.getRequestorsIPAddress()); + em.persist(modelAuthToken); + + org.uddi.api_v3.AuthToken apiAuthToken = new org.uddi.api_v3.AuthToken(); + + MappingModelToApi.mapAuthToken(modelAuthToken, apiAuthToken); + + tx.commit(); + logger.info("AUDIT: AuthToken issued for " + modelAuthToken.getAuthorizedName() + " from " + getRequestorsIPAddress()); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(SecurityQuery.GET_AUTHTOKEN, + QueryStatus.SUCCESS, procTime); + + return apiAuthToken; + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(SecurityQuery.GET_AUTHTOKEN, + QueryStatus.FAILED, procTime); + logger.info("AUDIT: AuthToken issue FAILED " + publisherId + " from " + getRequestorsIPAddress()); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIServiceCounter.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIServiceCounter.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIServiceCounter.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIServiceCounter.java diff --git a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIServiceCounterMBean.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIServiceCounterMBean.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIServiceCounterMBean.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIServiceCounterMBean.java diff --git a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDISubscriptionImpl.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDISubscriptionImpl.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/api/impl/UDDISubscriptionImpl.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDISubscriptionImpl.java index bf570f897..2f11614e5 100644 --- a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDISubscriptionImpl.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDISubscriptionImpl.java @@ -1,1046 +1,1046 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.util.ArrayList; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.UUID; - -import javax.jws.WebService; -import javax.persistence.EntityManager; -import javax.persistence.EntityTransaction; -import javax.xml.bind.JAXBException; -import javax.xml.datatype.DatatypeConfigurationException; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.ws.Holder; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.api.util.QueryStatus; -import org.apache.juddi.api.util.SubscriptionQuery; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.PersistenceManager; -import org.apache.juddi.config.Property; -import org.apache.juddi.jaxb.JAXBMarshaller; -import org.apache.juddi.mapping.MappingApiToModel; -import org.apache.juddi.mapping.MappingModelToApi; -import org.apache.juddi.model.SubscriptionChunkToken; -import org.apache.juddi.model.SubscriptionMatch; -import org.apache.juddi.model.UddiEntityPublisher; -import org.apache.juddi.query.FindBusinessByPublisherQuery; -import org.apache.juddi.query.FindSubscriptionByPublisherQuery; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.FatalErrorException; -import org.apache.juddi.v3.error.InvalidValueException; -import org.apache.juddi.validation.ValidateSubscription; -import org.uddi.api_v3.AssertionStatusReport; -import org.uddi.api_v3.BindingDetail; -import org.uddi.api_v3.BusinessDetail; -import org.uddi.api_v3.BusinessList; -import org.uddi.api_v3.FindBinding; -import org.uddi.api_v3.FindBusiness; -import org.uddi.api_v3.FindRelatedBusinesses; -import org.uddi.api_v3.FindService; -import org.uddi.api_v3.FindTModel; -import org.uddi.api_v3.GetAssertionStatusReport; -import org.uddi.api_v3.GetBindingDetail; -import org.uddi.api_v3.GetBusinessDetail; -import org.uddi.api_v3.GetServiceDetail; -import org.uddi.api_v3.GetTModelDetail; -import org.uddi.api_v3.RelatedBusinessesList; -import org.uddi.api_v3.ServiceDetail; -import org.uddi.api_v3.ServiceList; -import org.uddi.api_v3.TModelDetail; -import org.uddi.api_v3.TModelList; -import org.uddi.sub_v3.DeleteSubscription; -import org.uddi.sub_v3.GetSubscriptionResults; -import org.uddi.sub_v3.KeyBag; -import org.uddi.sub_v3.Subscription; -import org.uddi.sub_v3.SubscriptionFilter; -import org.uddi.sub_v3.SubscriptionResultsList; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.v3_service.UDDISubscriptionPortType; - -/** - * This is jUDDI's implementation of the UDDIv3 Subscription API - */ -@WebService(serviceName="UDDISubscriptionService", - endpointInterface="org.uddi.v3_service.UDDISubscriptionPortType", - targetNamespace = "urn:uddi-org:api_v3_portType") -public class UDDISubscriptionImpl extends AuthenticatedService implements UDDISubscriptionPortType { - - private static Log logger = LogFactory.getLog(UDDISubscriptionImpl.class); - - public static final int DEFAULT_SUBSCRIPTIONEXPIRATION_DAYS = 30; - public static final int DEFAULT_CHUNKEXPIRATION_MINUTES = 5; - - public static final String CHUNK_TOKEN_PREFIX = "chunktoken:"; - - private UDDIServiceCounter serviceCounter; - - public UDDISubscriptionImpl() { - super(); - serviceCounter = ServiceCounterLifecycleResource.getServiceCounter(this.getClass()); - } - - public void deleteSubscription(DeleteSubscription body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); - new ValidateSubscription(publisher).validateDeleteSubscription(em, body); - - List subscriptionKeyList = body.getSubscriptionKey(); - for (String subscriptionKey : subscriptionKeyList) { - Object obj = em.find(org.apache.juddi.model.Subscription.class, subscriptionKey); - em.remove(obj); - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(SubscriptionQuery.DELETE_SUBSCRIPTION, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(SubscriptionQuery.DELETE_SUBSCRIPTION, - QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - public SubscriptionResultsList getSubscriptionResults(GetSubscriptionResults body) throws DispositionReportFaultMessage { - return getSubscriptionResults(body, null); - } - /* (non-Javadoc) - * @see org.uddi.v3_service.UDDISubscriptionPortType#getSubscriptionResults(org.uddi.sub_v3.GetSubscriptionResults) - * - * Notes: Does it make sense to refresh the subscription matches on a call to this method? I don't think so, the user theoretically had - * a set of entities in mind when the subscription was saved and the snapshot should remain just that - a snapshot of the entities at the - * time of the subscription save. The result of this policy is that if an entity is deleted, that deleted result will appear in the keyBag - * on every call to this method. To resolve this, the user can renew the subscription at which time the "match" snapshot will be refreshed. - * - * The WS needs to be authenticated (null publisher), however the notificationSubscriber is calling this method also. The - * notificationSubscriber will pass in the publisher and this method will work in unauthenticated mode. - */ - @SuppressWarnings("unchecked") - public SubscriptionResultsList getSubscriptionResults(GetSubscriptionResults body, UddiEntityPublisher publisher) throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - if (publisher==null) { - publisher = this.getEntityPublisher(em, body.getAuthInfo()); - new ValidateSubscription(publisher).validateGetSubscriptionResults(em, body); - } - - org.apache.juddi.model.Subscription modelSubscription = em.find(org.apache.juddi.model.Subscription.class, body.getSubscriptionKey()); - SubscriptionFilter subscriptionFilter = null; - try { - subscriptionFilter = (SubscriptionFilter)JAXBMarshaller.unmarshallFromString(modelSubscription.getSubscriptionFilter(), JAXBMarshaller.PACKAGE_SUBSCRIPTION); - } - catch (JAXBException e) { - logger.error("JAXB Exception while unmarshalling subscription filter", e); - throw new FatalErrorException(new ErrorMessage("errors.Unspecified")); - } - if (logger.isDebugEnabled()) logger.debug("filter=" + modelSubscription.getSubscriptionFilter()); - - SubscriptionResultsList result = new SubscriptionResultsList(); - result.setChunkToken("0"); - //chunkToken: Optional element used to retrieve subsequent groups of data when the first invocation of this API indicates more data is available. This occurs when a chunkToken is returned whose value is not "0" in the validValuesList structure described in the next section. To retrieve the next chunk of data, the chunkToken returned should be used as an argument to the next invocation of this API. - result.setCoveragePeriod(body.getCoveragePeriod()); - - // The subscription structure is required output for the results - org.uddi.sub_v3.Subscription apiSubscription = new org.uddi.sub_v3.Subscription(); - MappingModelToApi.mapSubscription(modelSubscription, apiSubscription); - result.setSubscription(apiSubscription); - - Date startPointDate = new Date(body.getCoveragePeriod().getStartPoint().toGregorianCalendar().getTimeInMillis()); - Date endPointDate = new Date(body.getCoveragePeriod().getEndPoint().toGregorianCalendar().getTimeInMillis()); - - Integer chunkData = null; - if (body.getChunkToken() != null && body.getChunkToken().length() > 0) { - SubscriptionChunkToken chunkToken = em.find(SubscriptionChunkToken.class, body.getChunkToken()); - - if (chunkToken == null) - throw new InvalidValueException(new ErrorMessage("errors.getsubscriptionresult.InvalidChunkToken", body.getChunkToken())); - if (!chunkToken.getSubscriptionKey().equals(body.getSubscriptionKey())) - throw new InvalidValueException(new ErrorMessage("errors.getsubscriptionresult.NonMatchingChunkToken", body.getChunkToken())); - if (chunkToken.getStartPoint() != null && chunkToken.getStartPoint().getTime() != startPointDate.getTime()) - throw new InvalidValueException(new ErrorMessage("errors.getsubscriptionresult.NonMatchingChunkToken", body.getChunkToken())); - if (chunkToken.getEndPoint() != null && chunkToken.getEndPoint().getTime() != endPointDate.getTime()) - throw new InvalidValueException(new ErrorMessage("errors.getsubscriptionresult.NonMatchingChunkToken", body.getChunkToken())); - if (chunkToken.getExpiresAfter().before(new Date())) - throw new InvalidValueException(new ErrorMessage("errors.getsubscriptionresult.ExpiredChunkToken", body.getChunkToken())); - - chunkData = chunkToken.getData(); - // We've got the data from the chunk token, now it is no longer needed (once it's called, it's used up) - em.remove(chunkToken); - } - - - if (subscriptionFilter.getFindBinding() != null) { - //Get the current matching keys - List currentMatchingKeys = getSubscriptionMatches(subscriptionFilter, em); - // See if there's any missing keys by comparing against the previous matches. If so, they missing keys are added to the KeyBag and - // then added to the result - List missingKeys = getMissingKeys(currentMatchingKeys, modelSubscription.getSubscriptionMatches()); - if (missingKeys != null && missingKeys.size() > 0) { - KeyBag missingKeyBag = new KeyBag(); - missingKeyBag.setDeleted(true); - for (String key : missingKeys) - missingKeyBag.getBindingKey().add(key); - - result.getKeyBag().add(missingKeyBag); - } - - // Re-setting the subscription matches to the new matching key collection - //modelSubscription.getSubscriptionMatches().clear(); - //for (Object key : currentMatchingKeys) { - // SubscriptionMatch subMatch = new SubscriptionMatch(modelSubscription, (String)key); - // modelSubscription.getSubscriptionMatches().add(subMatch); - //} - - // Now, finding the necessary entities, within the coverage period limits - if (modelSubscription.isBrief()) { - KeyBag resultsKeyBag = new KeyBag(); - for (String key : (List)currentMatchingKeys) - resultsKeyBag.getBindingKey().add(key); - - result.getKeyBag().add(resultsKeyBag); - } - else { - FindBinding fb = subscriptionFilter.getFindBinding(); - org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); - findQualifiers.mapApiFindQualifiers(fb.getFindQualifiers()); - - // To do subscription "chunking", the listHead and maxRows are nulled which will set them to system default. User settings for - // these values don't make sense with the "chunking" feature. - fb.setListHead(null); - fb.setMaxRows(null); - // Setting the start index to the chunkData - Holder subscriptionStartIndex = new Holder(chunkData); - - BindingDetail bindingDetail = InquiryHelper.getBindingDetailFromKeys(fb, findQualifiers, em, currentMatchingKeys, - startPointDate, endPointDate, subscriptionStartIndex, modelSubscription.getMaxEntities()); - - // Upon exiting above function, if more results are to be had, the subscriptionStartIndex will contain the latest value (or null - // if no more results) - chunkData = subscriptionStartIndex.value; - - result.setBindingDetail(bindingDetail); - } - } - if (subscriptionFilter.getFindBusiness() != null) { - //Get the current matching keys - List currentMatchingKeys = getSubscriptionMatches(subscriptionFilter, em); - - List missingKeys = getMissingKeys(currentMatchingKeys, modelSubscription.getSubscriptionMatches()); - if (missingKeys != null && missingKeys.size() > 0) { - KeyBag missingKeyBag = new KeyBag(); - missingKeyBag.setDeleted(true); - for (String key : missingKeys) - missingKeyBag.getBusinessKey().add(key); - - result.getKeyBag().add(missingKeyBag); - } - - // Re-setting the subscription matches to the new matching key collection - //modelSubscription.getSubscriptionMatches().clear(); - //for (Object key : currentMatchingKeys) { - // SubscriptionMatch subMatch = new SubscriptionMatch(modelSubscription, (String)key); - // modelSubscription.getSubscriptionMatches().add(subMatch); - //} - - // Now, finding the necessary entities, within the coverage period limits - if (modelSubscription.isBrief()) { - KeyBag resultsKeyBag = new KeyBag(); - for (String key : (List)currentMatchingKeys) - resultsKeyBag.getBusinessKey().add(key); - - result.getKeyBag().add(resultsKeyBag); - } - else { - FindBusiness fb = subscriptionFilter.getFindBusiness(); - org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); - findQualifiers.mapApiFindQualifiers(fb.getFindQualifiers()); - - // To do subscription "chunking", the listHead and maxRows are nulled which will set them to system default. User settings for - // these values don't make sense with the "chunking" feature. - fb.setListHead(null); - fb.setMaxRows(null); - // Setting the start index to the chunkData - Holder subscriptionStartIndex = new Holder(chunkData); - - BusinessList businessList = InquiryHelper.getBusinessListFromKeys(fb, findQualifiers, em, currentMatchingKeys, - startPointDate, endPointDate, subscriptionStartIndex, modelSubscription.getMaxEntities()); - - // Upon exiting above function, if more results are to be had, the subscriptionStartIndex will contain the latest value (or null - // if no more results) - chunkData = subscriptionStartIndex.value; - - result.setBusinessList(businessList); - } - } - if (subscriptionFilter.getFindService() != null) { - //Get the current matching keys - List currentMatchingKeys = getSubscriptionMatches(subscriptionFilter, em); - if (logger.isDebugEnabled()) logger.debug("current matching keys=" + currentMatchingKeys); - List missingKeys = getMissingKeys(currentMatchingKeys, modelSubscription.getSubscriptionMatches()); - if (missingKeys != null && missingKeys.size() > 0) { - KeyBag missingKeyBag = new KeyBag(); - missingKeyBag.setDeleted(true); - for (String key : missingKeys) - missingKeyBag.getServiceKey().add(key); - - result.getKeyBag().add(missingKeyBag); - } - - // Re-setting the subscription matches to the new matching key collection - //modelSubscription.getSubscriptionMatches().clear(); - //for (Object key : currentMatchingKeys) { - // SubscriptionMatch subMatch = new SubscriptionMatch(modelSubscription, (String)key); - // modelSubscription.getSubscriptionMatches().add(subMatch); - //} - - // Now, finding the necessary entities, within the coverage period limits - if (modelSubscription.isBrief()) { - KeyBag resultsKeyBag = new KeyBag(); - for (String key : (List)currentMatchingKeys) - resultsKeyBag.getServiceKey().add(key); - - result.getKeyBag().add(resultsKeyBag); - } - else { - FindService fs = subscriptionFilter.getFindService(); - org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); - findQualifiers.mapApiFindQualifiers(fs.getFindQualifiers()); - - // To do subscription "chunking", the listHead and maxRows are nulled which will set them to system default. User settings for - // these values don't make sense with the "chunking" feature. - fs.setListHead(null); - fs.setMaxRows(null); - // Setting the start index to the chunkData - Holder subscriptionStartIndex = new Holder(chunkData); - - ServiceList serviceList = InquiryHelper.getServiceListFromKeys(fs, findQualifiers, em, currentMatchingKeys, - startPointDate, endPointDate, subscriptionStartIndex, modelSubscription.getMaxEntities()); - if (serviceList.getServiceInfos()==null || serviceList.getServiceInfos().getServiceInfo().size()==0) { - serviceList=null; - } - // Upon exiting above function, if more results are to be had, the subscriptionStartIndex will contain the latest value (or null - // if no more results) - chunkData = subscriptionStartIndex.value; - - result.setServiceList(serviceList); - } - } - if (subscriptionFilter.getFindTModel() != null) { - //Get the current matching keys - List currentMatchingKeys = getSubscriptionMatches(subscriptionFilter, em); - - List missingKeys = getMissingKeys(currentMatchingKeys, modelSubscription.getSubscriptionMatches()); - if (missingKeys != null && missingKeys.size() > 0) { - KeyBag missingKeyBag = new KeyBag(); - missingKeyBag.setDeleted(true); - for (String key : missingKeys) - missingKeyBag.getTModelKey().add(key); - - result.getKeyBag().add(missingKeyBag); - } - - // Re-setting the subscription matches to the new matching key collection - //modelSubscription.getSubscriptionMatches().clear(); - //for (Object key : currentMatchingKeys) { - // SubscriptionMatch subMatch = new SubscriptionMatch(modelSubscription, (String)key); - // modelSubscription.getSubscriptionMatches().add(subMatch); - //} - - // Now, finding the necessary entities, within the coverage period limits - if (modelSubscription.isBrief()) { - KeyBag resultsKeyBag = new KeyBag(); - for (String key : (List)currentMatchingKeys) - resultsKeyBag.getTModelKey().add(key); - - result.getKeyBag().add(resultsKeyBag); - } - else { - FindTModel ft = subscriptionFilter.getFindTModel(); - org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); - findQualifiers.mapApiFindQualifiers(ft.getFindQualifiers()); - - // To do subscription "chunking", the listHead and maxRows are nulled which will set them to system default. User settings for - // these values don't make sense with the "chunking" feature. - ft.setListHead(null); - ft.setMaxRows(null); - // Setting the start index to the chunkData - Holder subscriptionStartIndex = new Holder(chunkData); - - // If more results are to be had, chunkData will come out with a value and a new token will be generated below. Otherwise, it will - // be null and no token will be generated. - TModelList tmodelList = InquiryHelper.getTModelListFromKeys(ft, findQualifiers, em, currentMatchingKeys, - startPointDate, endPointDate, subscriptionStartIndex, modelSubscription.getMaxEntities()); - - // Upon exiting above function, if more results are to be had, the subscriptionStartIndex will contain the latest value (or null - // if no more results) - chunkData = subscriptionStartIndex.value; - - result.setTModelList(tmodelList); - } - - } - if (subscriptionFilter.getFindRelatedBusinesses() != null) { - FindRelatedBusinesses findRelatedBusiness = subscriptionFilter.getFindRelatedBusinesses(); - RelatedBusinessesList relatedBusinessList = InquiryHelper.getRelatedBusinessesList(findRelatedBusiness, em, startPointDate, endPointDate); - result.setRelatedBusinessesList(relatedBusinessList); - } - if (subscriptionFilter.getGetBindingDetail() != null) { - GetBindingDetail getDetail = subscriptionFilter.getGetBindingDetail(); - - // Running through the key list here to determine the deleted keys and store the existing entities. - KeyBag missingKeyBag = new KeyBag(); - missingKeyBag.setDeleted(true); - List existingList = new ArrayList(0); - for (String key : getDetail.getBindingKey()) { - org.apache.juddi.model.BindingTemplate modelBindingTemplate = em.find(org.apache.juddi.model.BindingTemplate.class, key); - if (modelBindingTemplate != null) - existingList.add(modelBindingTemplate); - else - missingKeyBag.getBindingKey().add(key); - } - // Store deleted keys in the results - if (missingKeyBag.getBindingKey() != null && missingKeyBag.getBindingKey().size() > 0) - result.getKeyBag().add(missingKeyBag); - - KeyBag resultsKeyBag = new KeyBag(); - BindingDetail bindingDetail = new BindingDetail(); - - // Set the currentIndex to 0 or the value of the chunkData - int currentIndex = 0; - if (chunkData != null) - currentIndex = chunkData; - - int returnedRowCount = 0; - while(currentIndex < existingList.size()) { - - org.apache.juddi.model.BindingTemplate modelBindingTemplate = existingList.get(currentIndex); - - if (startPointDate.after(modelBindingTemplate.getModifiedIncludingChildren())) { - currentIndex++; - continue; - } - - if (endPointDate.before(modelBindingTemplate.getModifiedIncludingChildren())) { - currentIndex++; - continue; - } - - if (modelSubscription.isBrief()) { - resultsKeyBag.getBindingKey().add(modelBindingTemplate.getEntityKey()); - } - else { - org.uddi.api_v3.BindingTemplate apiBindingTemplate = new org.uddi.api_v3.BindingTemplate(); - MappingModelToApi.mapBindingTemplate(modelBindingTemplate, apiBindingTemplate); - bindingDetail.getBindingTemplate().add(apiBindingTemplate); - - returnedRowCount++; - } - - // If the returned rows equals the max allowed, we can end the loop. - if (modelSubscription.getMaxEntities() != null) { - if (returnedRowCount == modelSubscription.getMaxEntities()) - break; - } - - currentIndex++; - } - - // If the loop was broken prematurely (max row count hit) we set the chunk data to the next index to start with. - // A non-null value of chunk data will cause a chunk token to be generated. - if (currentIndex < (existingList.size() - 1)) - chunkData = currentIndex + 1; - else - chunkData = null; - - if (modelSubscription.isBrief()) - result.getKeyBag().add(resultsKeyBag); - else - result.setBindingDetail(bindingDetail); - - - } - if (subscriptionFilter.getGetBusinessDetail() != null) { - GetBusinessDetail getDetail = subscriptionFilter.getGetBusinessDetail(); - - // Running through the key list here to determine the deleted keys and store the existing entities. - KeyBag missingKeyBag = new KeyBag(); - missingKeyBag.setDeleted(true); - List existingList = new ArrayList(0); - for (String key : getDetail.getBusinessKey()) { - org.apache.juddi.model.BusinessEntity modelBusinessEntity = em.find(org.apache.juddi.model.BusinessEntity.class, key); - if (modelBusinessEntity != null) - existingList.add(modelBusinessEntity); - else - missingKeyBag.getBusinessKey().add(key); - } - // Store deleted keys in the results - if (missingKeyBag.getBusinessKey() != null && missingKeyBag.getBusinessKey().size() > 0) - result.getKeyBag().add(missingKeyBag); - - KeyBag resultsKeyBag = new KeyBag(); - BusinessDetail businessDetail = new BusinessDetail(); - - // Set the currentIndex to 0 or the value of the chunkData - int currentIndex = 0; - if (chunkData != null) - currentIndex = chunkData; - - int returnedRowCount = 0; - while(currentIndex < existingList.size()) { - - org.apache.juddi.model.BusinessEntity modelBusinessEntity = existingList.get(currentIndex); - - if (startPointDate.after(modelBusinessEntity.getModifiedIncludingChildren())) { - currentIndex++; - continue; - } - - if (endPointDate.before(modelBusinessEntity.getModifiedIncludingChildren())) { - currentIndex++; - continue; - } - - if (modelSubscription.isBrief()) { - resultsKeyBag.getBusinessKey().add(modelBusinessEntity.getEntityKey()); - } - else { - org.uddi.api_v3.BusinessEntity apiBusinessEntity = new org.uddi.api_v3.BusinessEntity(); - MappingModelToApi.mapBusinessEntity(modelBusinessEntity, apiBusinessEntity); - businessDetail.getBusinessEntity().add(apiBusinessEntity); - - returnedRowCount++; - } - - // If the returned rows equals the max allowed, we can end the loop. - if (modelSubscription.getMaxEntities() != null) { - if (returnedRowCount == modelSubscription.getMaxEntities()) - break; - } - - currentIndex++; - } - - // If the loop was broken prematurely (max row count hit) we set the chunk data to the next index to start with. - // A non-null value of chunk data will cause a chunk token to be generated. - if (currentIndex < (existingList.size() - 1)) - chunkData = currentIndex + 1; - else - chunkData = null; - - if (modelSubscription.isBrief()) - result.getKeyBag().add(resultsKeyBag); - else - result.setBusinessDetail(businessDetail); - - } - if (subscriptionFilter.getGetServiceDetail() != null) { - GetServiceDetail getDetail = subscriptionFilter.getGetServiceDetail(); - - // Running through the key list here to determine the deleted keys and store the existing entities. - KeyBag missingKeyBag = new KeyBag(); - missingKeyBag.setDeleted(true); - List existingList = new ArrayList(0); - for (String key : getDetail.getServiceKey()) { - org.apache.juddi.model.BusinessService modelBusinessService = em.find(org.apache.juddi.model.BusinessService.class, key); - if (modelBusinessService != null) - existingList.add(modelBusinessService); - else - missingKeyBag.getBusinessKey().add(key); - } - // Store deleted keys in the results - if (missingKeyBag.getServiceKey() != null && missingKeyBag.getServiceKey().size() > 0) - result.getKeyBag().add(missingKeyBag); - - KeyBag resultsKeyBag = new KeyBag(); - ServiceDetail serviceDetail = new ServiceDetail(); - - // Set the currentIndex to 0 or the value of the chunkData - int currentIndex = 0; - if (chunkData != null) - currentIndex = chunkData; - - int returnedRowCount = 0; - while(currentIndex < existingList.size()) { - - org.apache.juddi.model.BusinessService modelBusinessService = existingList.get(currentIndex); - - if (startPointDate.after(modelBusinessService.getModifiedIncludingChildren())) { - currentIndex++; - continue; - } - - if (endPointDate.before(modelBusinessService.getModifiedIncludingChildren())) { - currentIndex++; - continue; - } - - if (modelSubscription.isBrief()) { - resultsKeyBag.getServiceKey().add(modelBusinessService.getEntityKey()); - } - else { - org.uddi.api_v3.BusinessService apiBusinessService = new org.uddi.api_v3.BusinessService(); - MappingModelToApi.mapBusinessService(modelBusinessService, apiBusinessService); - serviceDetail.getBusinessService().add(apiBusinessService); - - returnedRowCount++; - } - - // If the returned rows equals the max allowed, we can end the loop. - if (modelSubscription.getMaxEntities() != null) { - if (returnedRowCount == modelSubscription.getMaxEntities()) - break; - } - - currentIndex++; - } - - // If the loop was broken prematurely (max row count hit) we set the chunk data to the next index to start with. - // A non-null value of chunk data will cause a chunk token to be generated. - if (currentIndex < (existingList.size() - 1)) - chunkData = currentIndex + 1; - else - chunkData = null; - - if (modelSubscription.isBrief()) - result.getKeyBag().add(resultsKeyBag); - else - result.setServiceDetail(serviceDetail); - - } - if (subscriptionFilter.getGetTModelDetail() != null) { - GetTModelDetail getDetail = subscriptionFilter.getGetTModelDetail(); - - // Running through the key list here to determine the deleted keys and store the existing entities. - KeyBag missingKeyBag = new KeyBag(); - missingKeyBag.setDeleted(true); - List existingList = new ArrayList(0); - for (String key : getDetail.getTModelKey()) { - org.apache.juddi.model.Tmodel modelTModel = em.find(org.apache.juddi.model.Tmodel.class, key); - if (modelTModel != null) - existingList.add(modelTModel); - else - missingKeyBag.getTModelKey().add(key); - } - // Store deleted keys in the results - if (missingKeyBag.getTModelKey() != null && missingKeyBag.getTModelKey().size() > 0) - result.getKeyBag().add(missingKeyBag); - - KeyBag resultsKeyBag = new KeyBag(); - TModelDetail tmodelDetail = new TModelDetail(); - - // Set the currentIndex to 0 or the value of the chunkData - int currentIndex = 0; - if (chunkData != null) - currentIndex = chunkData; - - int returnedRowCount = 0; - while(currentIndex < existingList.size()) { - - org.apache.juddi.model.Tmodel modelTModel = existingList.get(currentIndex); - - if (startPointDate.after(modelTModel.getModifiedIncludingChildren())) { - currentIndex++; - continue; - } - - if (endPointDate.before(modelTModel.getModifiedIncludingChildren())) { - currentIndex++; - continue; - } - - if (modelSubscription.isBrief()) { - resultsKeyBag.getTModelKey().add(modelTModel.getEntityKey()); - } - else { - org.uddi.api_v3.TModel apiTModel = new org.uddi.api_v3.TModel(); - MappingModelToApi.mapTModel(modelTModel, apiTModel); - tmodelDetail.getTModel().add(apiTModel); - - returnedRowCount++; - } - - // If the returned rows equals the max allowed, we can end the loop. - if (modelSubscription.getMaxEntities() != null) { - if (returnedRowCount == modelSubscription.getMaxEntities()) - break; - } - - currentIndex++; - } - - // If the loop was broken prematurely (max row count hit) we set the chunk data to the next index to start with. - // A non-null value of chunk data will cause a chunk token to be generated. - if (currentIndex < (existingList.size() - 1)) - chunkData = currentIndex + 1; - else - chunkData = null; - - if (modelSubscription.isBrief()) - result.getKeyBag().add(resultsKeyBag); - else - result.setTModelDetail(tmodelDetail); - - } - if (subscriptionFilter.getGetAssertionStatusReport() != null) { - // The coverage period doesn't apply here (basically because publisher assertions don't keep operational info). - // TODO, JUDDI-873 edit they do now, rewrite this query - GetAssertionStatusReport getAssertionStatusReport = subscriptionFilter.getGetAssertionStatusReport(); - List businessKeysFound = null; - businessKeysFound = FindBusinessByPublisherQuery.select(em, null, publisher, businessKeysFound); - - AssertionStatusReport assertionStatusReport = new AssertionStatusReport(); - - List pubAssertionList = org.apache.juddi.query.FindPublisherAssertionByBusinessQuery.select(em, businessKeysFound, getAssertionStatusReport.getCompletionStatus()); - //if (pubAssertionList==null) - // return result; - for (org.apache.juddi.model.PublisherAssertion modelPubAssertion : pubAssertionList) { - - if (startPointDate.after(modelPubAssertion.getModified())) { - continue; - } - - if (endPointDate.before(modelPubAssertion.getModified())) { - continue; - } - org.uddi.api_v3.AssertionStatusItem apiAssertionStatusItem = new org.uddi.api_v3.AssertionStatusItem(); - - MappingModelToApi.mapAssertionStatusItem(modelPubAssertion, apiAssertionStatusItem, businessKeysFound); - - assertionStatusReport.getAssertionStatusItem().add(apiAssertionStatusItem); - } - - - result.setAssertionStatusReport(assertionStatusReport); - } - - // If chunkData contains non-null data, a new token must be created and the token returned in the results - if (chunkData != null) { - String chunkToken = CHUNK_TOKEN_PREFIX + UUID.randomUUID(); - SubscriptionChunkToken newChunkToken = new SubscriptionChunkToken(chunkToken); - newChunkToken.setSubscriptionKey(body.getSubscriptionKey()); - newChunkToken.setStartPoint(startPointDate); - newChunkToken.setEndPoint(endPointDate); - newChunkToken.setData(chunkData); - - int chunkExpirationMinutes = DEFAULT_CHUNKEXPIRATION_MINUTES; - try { - chunkExpirationMinutes = AppConfig.getConfiguration().getInt(Property.JUDDI_SUBSCRIPTION_CHUNKEXPIRATION_MINUTES); - } - catch(ConfigurationException ce) { - throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval")); - } - newChunkToken.setExpiresAfter(new Date(System.currentTimeMillis() + ((long)chunkExpirationMinutes * 60L * 1000L))); - - em.persist(newChunkToken); - - result.setChunkToken(chunkToken); - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(SubscriptionQuery.GET_SUBSCRIPTIONRESULTS, - QueryStatus.SUCCESS, procTime); - - return result; - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(SubscriptionQuery.GET_SUBSCRIPTIONRESULTS, - QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - @SuppressWarnings("unchecked") - public List getSubscriptions(String authInfo) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); - - List result = new ArrayList(0); - - List modelSubscriptionList = (List)FindSubscriptionByPublisherQuery.select(em, publisher.getAuthorizedName()); - if (modelSubscriptionList != null && modelSubscriptionList.size() > 0) { - for (org.apache.juddi.model.Subscription modelSubscription : modelSubscriptionList) { - - Subscription apiSubscription = new Subscription(); - - MappingModelToApi.mapSubscription(modelSubscription, apiSubscription); - - result.add(apiSubscription); - } - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(SubscriptionQuery.GET_SUBSCRIPTIONS, - QueryStatus.SUCCESS, procTime); - - return result; - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(SubscriptionQuery.GET_SUBSCRIPTIONS, - QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - - /* - * @see org.uddi.v3_service.UDDISubscriptionPortType#saveSubscription(java.lang.String, javax.xml.ws.Holder) - * - * Notes: The matching keys are saved on a new subscription (or renewed subscription) for the find_* filters only. With the other filter - * types, taking a snapshot of the matches doesn't make sense. - * - */ - public void saveSubscription(String authInfo, - Holder> subscription) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); - publisher.populateKeyGeneratorKeys(em); - new ValidateSubscription(publisher).validateSubscriptions(em, subscription.value, publisher); - - List apiSubscriptionList = subscription.value; - for (org.uddi.sub_v3.Subscription apiSubscription : apiSubscriptionList) { - - org.apache.juddi.model.Subscription modelSubscription = new org.apache.juddi.model.Subscription(); - - Object existing = em.find(org.apache.juddi.model.Subscription.class, apiSubscription.getSubscriptionKey()); - if (existing != null) { - org.apache.juddi.model.Subscription existingEntity = (org.apache.juddi.model.Subscription) existing; - doRenewal(existingEntity, apiSubscription); - //carrying over the created and last notified dates if this is a renewal. - modelSubscription.setCreateDate(existingEntity.getCreateDate()); - modelSubscription.setLastNotified(existingEntity.getLastNotified()); - em.remove(existing); - } else { - modelSubscription.setCreateDate(new Date()); - } - - doSubscriptionExpirationDate(apiSubscription); - - MappingApiToModel.mapSubscription(apiSubscription, modelSubscription); - - modelSubscription.setAuthorizedName(publisher.getAuthorizedName()); - - // Add the matching keys to the match collection - List keys = getSubscriptionMatches(apiSubscription.getSubscriptionFilter(), em); - if (keys != null && keys.size() > 0) { - for (Object key : keys) { - SubscriptionMatch subMatch = new SubscriptionMatch(modelSubscription, (String)key); - modelSubscription.getSubscriptionMatches().add(subMatch); - } - } - - em.persist(modelSubscription); - } - - tx.commit(); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(SubscriptionQuery.SAVE_SUBSCRIPTION, - QueryStatus.SUCCESS, procTime); - } catch (DispositionReportFaultMessage drfm) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(SubscriptionQuery.SAVE_SUBSCRIPTION, - QueryStatus.FAILED, procTime); - throw drfm; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - /** - * Will perform the necessary logic for when a subscription is renewed (evidenced by a subscription with the same key in existence). - * In general, the appropriate data is copied from the stored subscription to the renewal subscription request. - * - * @param existingSubscription - existing stored subscription - * @param apiSubscription - renewal subscription request - * @throws DispositionReportFaultMessage - */ - protected void doRenewal(org.apache.juddi.model.Subscription existingSubscription, org.uddi.sub_v3.Subscription apiSubscription) throws DispositionReportFaultMessage { - if (apiSubscription.getSubscriptionFilter() == null) { - String rawFilter = existingSubscription.getSubscriptionFilter(); - try { - SubscriptionFilter existingFilter = (SubscriptionFilter)JAXBMarshaller.unmarshallFromString(rawFilter, "org.uddi.sub_v3"); - apiSubscription.setSubscriptionFilter(existingFilter); - } - catch (JAXBException e) { - logger.error("JAXB Exception while marshalling subscription filter", e); - throw new FatalErrorException(new ErrorMessage("errors.Unspecified")); - } - } - - } - - /** - * Will add the expiration date to the provided subscription request. Date is earlier of user provided date and the system default - * - * @param apiSubscription - * @throws DispositionReportFaultMessage - */ - protected void doSubscriptionExpirationDate(org.uddi.sub_v3.Subscription apiSubscription) throws DispositionReportFaultMessage { - - int subscriptionExpirationDays = DEFAULT_SUBSCRIPTIONEXPIRATION_DAYS; - try { - subscriptionExpirationDays = AppConfig.getConfiguration().getInt(Property.JUDDI_SUBSCRIPTION_EXPIRATION_DAYS); - } - catch(ConfigurationException ce) { - throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval")); - } - - GregorianCalendar expirationDate = new GregorianCalendar(); - expirationDate.add(GregorianCalendar.DAY_OF_MONTH, subscriptionExpirationDays); - - // The expiration date is the earlier of the provided date and that specified by the parameter. - if (apiSubscription.getExpiresAfter() != null) { - GregorianCalendar userExpiration = apiSubscription.getExpiresAfter().toGregorianCalendar(); - if (userExpiration.getTimeInMillis() < expirationDate.getTimeInMillis()) - expirationDate.setTimeInMillis(userExpiration.getTimeInMillis()); - } - - try { - DatatypeFactory df = DatatypeFactory.newInstance(); - apiSubscription.setExpiresAfter(df.newXMLGregorianCalendar(expirationDate)); - } - catch(DatatypeConfigurationException ce) { - throw new FatalErrorException(new ErrorMessage("errors.Unspecified")); - } - - } - - /** - * Will take a snapshot of the keys that match the subscription filter return them. Currently, keys are only returned for the find_* - * filters. It seems redundant to return the keys in the get_*Detail filters. - * - * @param subscriptionFilter - * @param em - * @return a list of subscription matches - * @throws DispositionReportFaultMessage - */ - protected List getSubscriptionMatches(SubscriptionFilter subscriptionFilter, EntityManager em) - throws DispositionReportFaultMessage { - - - List keys = null; - if (subscriptionFilter.getFindBinding() != null) { - org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); - findQualifiers.mapApiFindQualifiers(subscriptionFilter.getFindBinding().getFindQualifiers()); - keys = InquiryHelper.findBinding(subscriptionFilter.getFindBinding(), findQualifiers, em); - } - if (subscriptionFilter.getFindBusiness() != null) { - org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); - findQualifiers.mapApiFindQualifiers(subscriptionFilter.getFindBusiness().getFindQualifiers()); - keys = InquiryHelper.findBusiness(subscriptionFilter.getFindBusiness(), findQualifiers, em); - } - if (subscriptionFilter.getFindService() != null) { - org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); - findQualifiers.mapApiFindQualifiers(subscriptionFilter.getFindService().getFindQualifiers()); - keys = InquiryHelper.findService(subscriptionFilter.getFindService(), findQualifiers, em); - } - if (subscriptionFilter.getFindTModel() != null) { - org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); - findQualifiers.mapApiFindQualifiers(subscriptionFilter.getFindTModel().getFindQualifiers()); - keys = InquiryHelper.findTModel(subscriptionFilter.getFindTModel(), findQualifiers, em); - } - if (subscriptionFilter.getFindRelatedBusinesses() != null) { - // TODO: should we bother taking a snapshot of these? - } - if (subscriptionFilter.getGetBindingDetail() != null) { - //keys = subscriptionFilter.getGetBindingDetail().getBindingKey(); - // Nothing needs to be done - } - if (subscriptionFilter.getGetBusinessDetail() != null) { - //keys = subscriptionFilter.getGetBusinessDetail().getBusinessKey(); - // Nothing needs to be done - } - if (subscriptionFilter.getGetServiceDetail() != null) { - //keys = subscriptionFilter.getGetServiceDetail().getServiceKey(); - // Nothing needs to be done - } - if (subscriptionFilter.getGetTModelDetail() != null) { - //keys = subscriptionFilter.getGetTModelDetail().getTModelKey(); - // Nothing needs to be done - } - if (subscriptionFilter.getGetAssertionStatusReport() != null) { - // Nothing needs to be done - } - return keys; - - } - - private List getMissingKeys(List currentMatchingKeys, List subscriptionMatches) { - - List result = new ArrayList(subscriptionMatches.size()); - for (SubscriptionMatch subMatch : subscriptionMatches) - result.add(subMatch.getEntityKey()); - - result.removeAll(currentMatchingKeys); - - return result; - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.util.ArrayList; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.UUID; + +import javax.jws.WebService; +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.xml.bind.JAXBException; +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.ws.Holder; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.api.util.QueryStatus; +import org.apache.juddi.api.util.SubscriptionQuery; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.PersistenceManager; +import org.apache.juddi.config.Property; +import org.apache.juddi.jaxb.JAXBMarshaller; +import org.apache.juddi.mapping.MappingApiToModel; +import org.apache.juddi.mapping.MappingModelToApi; +import org.apache.juddi.model.SubscriptionChunkToken; +import org.apache.juddi.model.SubscriptionMatch; +import org.apache.juddi.model.UddiEntityPublisher; +import org.apache.juddi.query.FindBusinessByPublisherQuery; +import org.apache.juddi.query.FindSubscriptionByPublisherQuery; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.FatalErrorException; +import org.apache.juddi.v3.error.InvalidValueException; +import org.apache.juddi.validation.ValidateSubscription; +import org.uddi.api_v3.AssertionStatusReport; +import org.uddi.api_v3.BindingDetail; +import org.uddi.api_v3.BusinessDetail; +import org.uddi.api_v3.BusinessList; +import org.uddi.api_v3.FindBinding; +import org.uddi.api_v3.FindBusiness; +import org.uddi.api_v3.FindRelatedBusinesses; +import org.uddi.api_v3.FindService; +import org.uddi.api_v3.FindTModel; +import org.uddi.api_v3.GetAssertionStatusReport; +import org.uddi.api_v3.GetBindingDetail; +import org.uddi.api_v3.GetBusinessDetail; +import org.uddi.api_v3.GetServiceDetail; +import org.uddi.api_v3.GetTModelDetail; +import org.uddi.api_v3.RelatedBusinessesList; +import org.uddi.api_v3.ServiceDetail; +import org.uddi.api_v3.ServiceList; +import org.uddi.api_v3.TModelDetail; +import org.uddi.api_v3.TModelList; +import org.uddi.sub_v3.DeleteSubscription; +import org.uddi.sub_v3.GetSubscriptionResults; +import org.uddi.sub_v3.KeyBag; +import org.uddi.sub_v3.Subscription; +import org.uddi.sub_v3.SubscriptionFilter; +import org.uddi.sub_v3.SubscriptionResultsList; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.v3_service.UDDISubscriptionPortType; + +/** + * This is jUDDI's implementation of the UDDIv3 Subscription API + */ +@WebService(serviceName="UDDISubscriptionService", + endpointInterface="org.uddi.v3_service.UDDISubscriptionPortType", + targetNamespace = "urn:uddi-org:api_v3_portType") +public class UDDISubscriptionImpl extends AuthenticatedService implements UDDISubscriptionPortType { + + private static Log logger = LogFactory.getLog(UDDISubscriptionImpl.class); + + public static final int DEFAULT_SUBSCRIPTIONEXPIRATION_DAYS = 30; + public static final int DEFAULT_CHUNKEXPIRATION_MINUTES = 5; + + public static final String CHUNK_TOKEN_PREFIX = "chunktoken:"; + + private UDDIServiceCounter serviceCounter; + + public UDDISubscriptionImpl() { + super(); + serviceCounter = ServiceCounterLifecycleResource.getServiceCounter(this.getClass()); + } + + public void deleteSubscription(DeleteSubscription body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); + new ValidateSubscription(publisher).validateDeleteSubscription(em, body); + + List subscriptionKeyList = body.getSubscriptionKey(); + for (String subscriptionKey : subscriptionKeyList) { + Object obj = em.find(org.apache.juddi.model.Subscription.class, subscriptionKey); + em.remove(obj); + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(SubscriptionQuery.DELETE_SUBSCRIPTION, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(SubscriptionQuery.DELETE_SUBSCRIPTION, + QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + public SubscriptionResultsList getSubscriptionResults(GetSubscriptionResults body) throws DispositionReportFaultMessage { + return getSubscriptionResults(body, null); + } + /* (non-Javadoc) + * @see org.uddi.v3_service.UDDISubscriptionPortType#getSubscriptionResults(org.uddi.sub_v3.GetSubscriptionResults) + * + * Notes: Does it make sense to refresh the subscription matches on a call to this method? I don't think so, the user theoretically had + * a set of entities in mind when the subscription was saved and the snapshot should remain just that - a snapshot of the entities at the + * time of the subscription save. The result of this policy is that if an entity is deleted, that deleted result will appear in the keyBag + * on every call to this method. To resolve this, the user can renew the subscription at which time the "match" snapshot will be refreshed. + * + * The WS needs to be authenticated (null publisher), however the notificationSubscriber is calling this method also. The + * notificationSubscriber will pass in the publisher and this method will work in unauthenticated mode. + */ + @SuppressWarnings("unchecked") + public SubscriptionResultsList getSubscriptionResults(GetSubscriptionResults body, UddiEntityPublisher publisher) throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + if (publisher==null) { + publisher = this.getEntityPublisher(em, body.getAuthInfo()); + new ValidateSubscription(publisher).validateGetSubscriptionResults(em, body); + } + + org.apache.juddi.model.Subscription modelSubscription = em.find(org.apache.juddi.model.Subscription.class, body.getSubscriptionKey()); + SubscriptionFilter subscriptionFilter = null; + try { + subscriptionFilter = (SubscriptionFilter)JAXBMarshaller.unmarshallFromString(modelSubscription.getSubscriptionFilter(), JAXBMarshaller.PACKAGE_SUBSCRIPTION); + } + catch (JAXBException e) { + logger.error("JAXB Exception while unmarshalling subscription filter", e); + throw new FatalErrorException(new ErrorMessage("errors.Unspecified")); + } + if (logger.isDebugEnabled()) logger.debug("filter=" + modelSubscription.getSubscriptionFilter()); + + SubscriptionResultsList result = new SubscriptionResultsList(); + result.setChunkToken("0"); + //chunkToken: Optional element used to retrieve subsequent groups of data when the first invocation of this API indicates more data is available. This occurs when a chunkToken is returned whose value is not "0" in the validValuesList structure described in the next section. To retrieve the next chunk of data, the chunkToken returned should be used as an argument to the next invocation of this API. + result.setCoveragePeriod(body.getCoveragePeriod()); + + // The subscription structure is required output for the results + org.uddi.sub_v3.Subscription apiSubscription = new org.uddi.sub_v3.Subscription(); + MappingModelToApi.mapSubscription(modelSubscription, apiSubscription); + result.setSubscription(apiSubscription); + + Date startPointDate = new Date(body.getCoveragePeriod().getStartPoint().toGregorianCalendar().getTimeInMillis()); + Date endPointDate = new Date(body.getCoveragePeriod().getEndPoint().toGregorianCalendar().getTimeInMillis()); + + Integer chunkData = null; + if (body.getChunkToken() != null && body.getChunkToken().length() > 0) { + SubscriptionChunkToken chunkToken = em.find(SubscriptionChunkToken.class, body.getChunkToken()); + + if (chunkToken == null) + throw new InvalidValueException(new ErrorMessage("errors.getsubscriptionresult.InvalidChunkToken", body.getChunkToken())); + if (!chunkToken.getSubscriptionKey().equals(body.getSubscriptionKey())) + throw new InvalidValueException(new ErrorMessage("errors.getsubscriptionresult.NonMatchingChunkToken", body.getChunkToken())); + if (chunkToken.getStartPoint() != null && chunkToken.getStartPoint().getTime() != startPointDate.getTime()) + throw new InvalidValueException(new ErrorMessage("errors.getsubscriptionresult.NonMatchingChunkToken", body.getChunkToken())); + if (chunkToken.getEndPoint() != null && chunkToken.getEndPoint().getTime() != endPointDate.getTime()) + throw new InvalidValueException(new ErrorMessage("errors.getsubscriptionresult.NonMatchingChunkToken", body.getChunkToken())); + if (chunkToken.getExpiresAfter().before(new Date())) + throw new InvalidValueException(new ErrorMessage("errors.getsubscriptionresult.ExpiredChunkToken", body.getChunkToken())); + + chunkData = chunkToken.getData(); + // We've got the data from the chunk token, now it is no longer needed (once it's called, it's used up) + em.remove(chunkToken); + } + + + if (subscriptionFilter.getFindBinding() != null) { + //Get the current matching keys + List currentMatchingKeys = getSubscriptionMatches(subscriptionFilter, em); + // See if there's any missing keys by comparing against the previous matches. If so, they missing keys are added to the KeyBag and + // then added to the result + List missingKeys = getMissingKeys(currentMatchingKeys, modelSubscription.getSubscriptionMatches()); + if (missingKeys != null && missingKeys.size() > 0) { + KeyBag missingKeyBag = new KeyBag(); + missingKeyBag.setDeleted(true); + for (String key : missingKeys) + missingKeyBag.getBindingKey().add(key); + + result.getKeyBag().add(missingKeyBag); + } + + // Re-setting the subscription matches to the new matching key collection + //modelSubscription.getSubscriptionMatches().clear(); + //for (Object key : currentMatchingKeys) { + // SubscriptionMatch subMatch = new SubscriptionMatch(modelSubscription, (String)key); + // modelSubscription.getSubscriptionMatches().add(subMatch); + //} + + // Now, finding the necessary entities, within the coverage period limits + if (modelSubscription.isBrief()) { + KeyBag resultsKeyBag = new KeyBag(); + for (String key : (List)currentMatchingKeys) + resultsKeyBag.getBindingKey().add(key); + + result.getKeyBag().add(resultsKeyBag); + } + else { + FindBinding fb = subscriptionFilter.getFindBinding(); + org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); + findQualifiers.mapApiFindQualifiers(fb.getFindQualifiers()); + + // To do subscription "chunking", the listHead and maxRows are nulled which will set them to system default. User settings for + // these values don't make sense with the "chunking" feature. + fb.setListHead(null); + fb.setMaxRows(null); + // Setting the start index to the chunkData + Holder subscriptionStartIndex = new Holder(chunkData); + + BindingDetail bindingDetail = InquiryHelper.getBindingDetailFromKeys(fb, findQualifiers, em, currentMatchingKeys, + startPointDate, endPointDate, subscriptionStartIndex, modelSubscription.getMaxEntities()); + + // Upon exiting above function, if more results are to be had, the subscriptionStartIndex will contain the latest value (or null + // if no more results) + chunkData = subscriptionStartIndex.value; + + result.setBindingDetail(bindingDetail); + } + } + if (subscriptionFilter.getFindBusiness() != null) { + //Get the current matching keys + List currentMatchingKeys = getSubscriptionMatches(subscriptionFilter, em); + + List missingKeys = getMissingKeys(currentMatchingKeys, modelSubscription.getSubscriptionMatches()); + if (missingKeys != null && missingKeys.size() > 0) { + KeyBag missingKeyBag = new KeyBag(); + missingKeyBag.setDeleted(true); + for (String key : missingKeys) + missingKeyBag.getBusinessKey().add(key); + + result.getKeyBag().add(missingKeyBag); + } + + // Re-setting the subscription matches to the new matching key collection + //modelSubscription.getSubscriptionMatches().clear(); + //for (Object key : currentMatchingKeys) { + // SubscriptionMatch subMatch = new SubscriptionMatch(modelSubscription, (String)key); + // modelSubscription.getSubscriptionMatches().add(subMatch); + //} + + // Now, finding the necessary entities, within the coverage period limits + if (modelSubscription.isBrief()) { + KeyBag resultsKeyBag = new KeyBag(); + for (String key : (List)currentMatchingKeys) + resultsKeyBag.getBusinessKey().add(key); + + result.getKeyBag().add(resultsKeyBag); + } + else { + FindBusiness fb = subscriptionFilter.getFindBusiness(); + org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); + findQualifiers.mapApiFindQualifiers(fb.getFindQualifiers()); + + // To do subscription "chunking", the listHead and maxRows are nulled which will set them to system default. User settings for + // these values don't make sense with the "chunking" feature. + fb.setListHead(null); + fb.setMaxRows(null); + // Setting the start index to the chunkData + Holder subscriptionStartIndex = new Holder(chunkData); + + BusinessList businessList = InquiryHelper.getBusinessListFromKeys(fb, findQualifiers, em, currentMatchingKeys, + startPointDate, endPointDate, subscriptionStartIndex, modelSubscription.getMaxEntities()); + + // Upon exiting above function, if more results are to be had, the subscriptionStartIndex will contain the latest value (or null + // if no more results) + chunkData = subscriptionStartIndex.value; + + result.setBusinessList(businessList); + } + } + if (subscriptionFilter.getFindService() != null) { + //Get the current matching keys + List currentMatchingKeys = getSubscriptionMatches(subscriptionFilter, em); + if (logger.isDebugEnabled()) logger.debug("current matching keys=" + currentMatchingKeys); + List missingKeys = getMissingKeys(currentMatchingKeys, modelSubscription.getSubscriptionMatches()); + if (missingKeys != null && missingKeys.size() > 0) { + KeyBag missingKeyBag = new KeyBag(); + missingKeyBag.setDeleted(true); + for (String key : missingKeys) + missingKeyBag.getServiceKey().add(key); + + result.getKeyBag().add(missingKeyBag); + } + + // Re-setting the subscription matches to the new matching key collection + //modelSubscription.getSubscriptionMatches().clear(); + //for (Object key : currentMatchingKeys) { + // SubscriptionMatch subMatch = new SubscriptionMatch(modelSubscription, (String)key); + // modelSubscription.getSubscriptionMatches().add(subMatch); + //} + + // Now, finding the necessary entities, within the coverage period limits + if (modelSubscription.isBrief()) { + KeyBag resultsKeyBag = new KeyBag(); + for (String key : (List)currentMatchingKeys) + resultsKeyBag.getServiceKey().add(key); + + result.getKeyBag().add(resultsKeyBag); + } + else { + FindService fs = subscriptionFilter.getFindService(); + org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); + findQualifiers.mapApiFindQualifiers(fs.getFindQualifiers()); + + // To do subscription "chunking", the listHead and maxRows are nulled which will set them to system default. User settings for + // these values don't make sense with the "chunking" feature. + fs.setListHead(null); + fs.setMaxRows(null); + // Setting the start index to the chunkData + Holder subscriptionStartIndex = new Holder(chunkData); + + ServiceList serviceList = InquiryHelper.getServiceListFromKeys(fs, findQualifiers, em, currentMatchingKeys, + startPointDate, endPointDate, subscriptionStartIndex, modelSubscription.getMaxEntities()); + if (serviceList.getServiceInfos()==null || serviceList.getServiceInfos().getServiceInfo().size()==0) { + serviceList=null; + } + // Upon exiting above function, if more results are to be had, the subscriptionStartIndex will contain the latest value (or null + // if no more results) + chunkData = subscriptionStartIndex.value; + + result.setServiceList(serviceList); + } + } + if (subscriptionFilter.getFindTModel() != null) { + //Get the current matching keys + List currentMatchingKeys = getSubscriptionMatches(subscriptionFilter, em); + + List missingKeys = getMissingKeys(currentMatchingKeys, modelSubscription.getSubscriptionMatches()); + if (missingKeys != null && missingKeys.size() > 0) { + KeyBag missingKeyBag = new KeyBag(); + missingKeyBag.setDeleted(true); + for (String key : missingKeys) + missingKeyBag.getTModelKey().add(key); + + result.getKeyBag().add(missingKeyBag); + } + + // Re-setting the subscription matches to the new matching key collection + //modelSubscription.getSubscriptionMatches().clear(); + //for (Object key : currentMatchingKeys) { + // SubscriptionMatch subMatch = new SubscriptionMatch(modelSubscription, (String)key); + // modelSubscription.getSubscriptionMatches().add(subMatch); + //} + + // Now, finding the necessary entities, within the coverage period limits + if (modelSubscription.isBrief()) { + KeyBag resultsKeyBag = new KeyBag(); + for (String key : (List)currentMatchingKeys) + resultsKeyBag.getTModelKey().add(key); + + result.getKeyBag().add(resultsKeyBag); + } + else { + FindTModel ft = subscriptionFilter.getFindTModel(); + org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); + findQualifiers.mapApiFindQualifiers(ft.getFindQualifiers()); + + // To do subscription "chunking", the listHead and maxRows are nulled which will set them to system default. User settings for + // these values don't make sense with the "chunking" feature. + ft.setListHead(null); + ft.setMaxRows(null); + // Setting the start index to the chunkData + Holder subscriptionStartIndex = new Holder(chunkData); + + // If more results are to be had, chunkData will come out with a value and a new token will be generated below. Otherwise, it will + // be null and no token will be generated. + TModelList tmodelList = InquiryHelper.getTModelListFromKeys(ft, findQualifiers, em, currentMatchingKeys, + startPointDate, endPointDate, subscriptionStartIndex, modelSubscription.getMaxEntities()); + + // Upon exiting above function, if more results are to be had, the subscriptionStartIndex will contain the latest value (or null + // if no more results) + chunkData = subscriptionStartIndex.value; + + result.setTModelList(tmodelList); + } + + } + if (subscriptionFilter.getFindRelatedBusinesses() != null) { + FindRelatedBusinesses findRelatedBusiness = subscriptionFilter.getFindRelatedBusinesses(); + RelatedBusinessesList relatedBusinessList = InquiryHelper.getRelatedBusinessesList(findRelatedBusiness, em, startPointDate, endPointDate); + result.setRelatedBusinessesList(relatedBusinessList); + } + if (subscriptionFilter.getGetBindingDetail() != null) { + GetBindingDetail getDetail = subscriptionFilter.getGetBindingDetail(); + + // Running through the key list here to determine the deleted keys and store the existing entities. + KeyBag missingKeyBag = new KeyBag(); + missingKeyBag.setDeleted(true); + List existingList = new ArrayList(0); + for (String key : getDetail.getBindingKey()) { + org.apache.juddi.model.BindingTemplate modelBindingTemplate = em.find(org.apache.juddi.model.BindingTemplate.class, key); + if (modelBindingTemplate != null) + existingList.add(modelBindingTemplate); + else + missingKeyBag.getBindingKey().add(key); + } + // Store deleted keys in the results + if (missingKeyBag.getBindingKey() != null && missingKeyBag.getBindingKey().size() > 0) + result.getKeyBag().add(missingKeyBag); + + KeyBag resultsKeyBag = new KeyBag(); + BindingDetail bindingDetail = new BindingDetail(); + + // Set the currentIndex to 0 or the value of the chunkData + int currentIndex = 0; + if (chunkData != null) + currentIndex = chunkData; + + int returnedRowCount = 0; + while(currentIndex < existingList.size()) { + + org.apache.juddi.model.BindingTemplate modelBindingTemplate = existingList.get(currentIndex); + + if (startPointDate.after(modelBindingTemplate.getModifiedIncludingChildren())) { + currentIndex++; + continue; + } + + if (endPointDate.before(modelBindingTemplate.getModifiedIncludingChildren())) { + currentIndex++; + continue; + } + + if (modelSubscription.isBrief()) { + resultsKeyBag.getBindingKey().add(modelBindingTemplate.getEntityKey()); + } + else { + org.uddi.api_v3.BindingTemplate apiBindingTemplate = new org.uddi.api_v3.BindingTemplate(); + MappingModelToApi.mapBindingTemplate(modelBindingTemplate, apiBindingTemplate); + bindingDetail.getBindingTemplate().add(apiBindingTemplate); + + returnedRowCount++; + } + + // If the returned rows equals the max allowed, we can end the loop. + if (modelSubscription.getMaxEntities() != null) { + if (returnedRowCount == modelSubscription.getMaxEntities()) + break; + } + + currentIndex++; + } + + // If the loop was broken prematurely (max row count hit) we set the chunk data to the next index to start with. + // A non-null value of chunk data will cause a chunk token to be generated. + if (currentIndex < (existingList.size() - 1)) + chunkData = currentIndex + 1; + else + chunkData = null; + + if (modelSubscription.isBrief()) + result.getKeyBag().add(resultsKeyBag); + else + result.setBindingDetail(bindingDetail); + + + } + if (subscriptionFilter.getGetBusinessDetail() != null) { + GetBusinessDetail getDetail = subscriptionFilter.getGetBusinessDetail(); + + // Running through the key list here to determine the deleted keys and store the existing entities. + KeyBag missingKeyBag = new KeyBag(); + missingKeyBag.setDeleted(true); + List existingList = new ArrayList(0); + for (String key : getDetail.getBusinessKey()) { + org.apache.juddi.model.BusinessEntity modelBusinessEntity = em.find(org.apache.juddi.model.BusinessEntity.class, key); + if (modelBusinessEntity != null) + existingList.add(modelBusinessEntity); + else + missingKeyBag.getBusinessKey().add(key); + } + // Store deleted keys in the results + if (missingKeyBag.getBusinessKey() != null && missingKeyBag.getBusinessKey().size() > 0) + result.getKeyBag().add(missingKeyBag); + + KeyBag resultsKeyBag = new KeyBag(); + BusinessDetail businessDetail = new BusinessDetail(); + + // Set the currentIndex to 0 or the value of the chunkData + int currentIndex = 0; + if (chunkData != null) + currentIndex = chunkData; + + int returnedRowCount = 0; + while(currentIndex < existingList.size()) { + + org.apache.juddi.model.BusinessEntity modelBusinessEntity = existingList.get(currentIndex); + + if (startPointDate.after(modelBusinessEntity.getModifiedIncludingChildren())) { + currentIndex++; + continue; + } + + if (endPointDate.before(modelBusinessEntity.getModifiedIncludingChildren())) { + currentIndex++; + continue; + } + + if (modelSubscription.isBrief()) { + resultsKeyBag.getBusinessKey().add(modelBusinessEntity.getEntityKey()); + } + else { + org.uddi.api_v3.BusinessEntity apiBusinessEntity = new org.uddi.api_v3.BusinessEntity(); + MappingModelToApi.mapBusinessEntity(modelBusinessEntity, apiBusinessEntity); + businessDetail.getBusinessEntity().add(apiBusinessEntity); + + returnedRowCount++; + } + + // If the returned rows equals the max allowed, we can end the loop. + if (modelSubscription.getMaxEntities() != null) { + if (returnedRowCount == modelSubscription.getMaxEntities()) + break; + } + + currentIndex++; + } + + // If the loop was broken prematurely (max row count hit) we set the chunk data to the next index to start with. + // A non-null value of chunk data will cause a chunk token to be generated. + if (currentIndex < (existingList.size() - 1)) + chunkData = currentIndex + 1; + else + chunkData = null; + + if (modelSubscription.isBrief()) + result.getKeyBag().add(resultsKeyBag); + else + result.setBusinessDetail(businessDetail); + + } + if (subscriptionFilter.getGetServiceDetail() != null) { + GetServiceDetail getDetail = subscriptionFilter.getGetServiceDetail(); + + // Running through the key list here to determine the deleted keys and store the existing entities. + KeyBag missingKeyBag = new KeyBag(); + missingKeyBag.setDeleted(true); + List existingList = new ArrayList(0); + for (String key : getDetail.getServiceKey()) { + org.apache.juddi.model.BusinessService modelBusinessService = em.find(org.apache.juddi.model.BusinessService.class, key); + if (modelBusinessService != null) + existingList.add(modelBusinessService); + else + missingKeyBag.getBusinessKey().add(key); + } + // Store deleted keys in the results + if (missingKeyBag.getServiceKey() != null && missingKeyBag.getServiceKey().size() > 0) + result.getKeyBag().add(missingKeyBag); + + KeyBag resultsKeyBag = new KeyBag(); + ServiceDetail serviceDetail = new ServiceDetail(); + + // Set the currentIndex to 0 or the value of the chunkData + int currentIndex = 0; + if (chunkData != null) + currentIndex = chunkData; + + int returnedRowCount = 0; + while(currentIndex < existingList.size()) { + + org.apache.juddi.model.BusinessService modelBusinessService = existingList.get(currentIndex); + + if (startPointDate.after(modelBusinessService.getModifiedIncludingChildren())) { + currentIndex++; + continue; + } + + if (endPointDate.before(modelBusinessService.getModifiedIncludingChildren())) { + currentIndex++; + continue; + } + + if (modelSubscription.isBrief()) { + resultsKeyBag.getServiceKey().add(modelBusinessService.getEntityKey()); + } + else { + org.uddi.api_v3.BusinessService apiBusinessService = new org.uddi.api_v3.BusinessService(); + MappingModelToApi.mapBusinessService(modelBusinessService, apiBusinessService); + serviceDetail.getBusinessService().add(apiBusinessService); + + returnedRowCount++; + } + + // If the returned rows equals the max allowed, we can end the loop. + if (modelSubscription.getMaxEntities() != null) { + if (returnedRowCount == modelSubscription.getMaxEntities()) + break; + } + + currentIndex++; + } + + // If the loop was broken prematurely (max row count hit) we set the chunk data to the next index to start with. + // A non-null value of chunk data will cause a chunk token to be generated. + if (currentIndex < (existingList.size() - 1)) + chunkData = currentIndex + 1; + else + chunkData = null; + + if (modelSubscription.isBrief()) + result.getKeyBag().add(resultsKeyBag); + else + result.setServiceDetail(serviceDetail); + + } + if (subscriptionFilter.getGetTModelDetail() != null) { + GetTModelDetail getDetail = subscriptionFilter.getGetTModelDetail(); + + // Running through the key list here to determine the deleted keys and store the existing entities. + KeyBag missingKeyBag = new KeyBag(); + missingKeyBag.setDeleted(true); + List existingList = new ArrayList(0); + for (String key : getDetail.getTModelKey()) { + org.apache.juddi.model.Tmodel modelTModel = em.find(org.apache.juddi.model.Tmodel.class, key); + if (modelTModel != null) + existingList.add(modelTModel); + else + missingKeyBag.getTModelKey().add(key); + } + // Store deleted keys in the results + if (missingKeyBag.getTModelKey() != null && missingKeyBag.getTModelKey().size() > 0) + result.getKeyBag().add(missingKeyBag); + + KeyBag resultsKeyBag = new KeyBag(); + TModelDetail tmodelDetail = new TModelDetail(); + + // Set the currentIndex to 0 or the value of the chunkData + int currentIndex = 0; + if (chunkData != null) + currentIndex = chunkData; + + int returnedRowCount = 0; + while(currentIndex < existingList.size()) { + + org.apache.juddi.model.Tmodel modelTModel = existingList.get(currentIndex); + + if (startPointDate.after(modelTModel.getModifiedIncludingChildren())) { + currentIndex++; + continue; + } + + if (endPointDate.before(modelTModel.getModifiedIncludingChildren())) { + currentIndex++; + continue; + } + + if (modelSubscription.isBrief()) { + resultsKeyBag.getTModelKey().add(modelTModel.getEntityKey()); + } + else { + org.uddi.api_v3.TModel apiTModel = new org.uddi.api_v3.TModel(); + MappingModelToApi.mapTModel(modelTModel, apiTModel); + tmodelDetail.getTModel().add(apiTModel); + + returnedRowCount++; + } + + // If the returned rows equals the max allowed, we can end the loop. + if (modelSubscription.getMaxEntities() != null) { + if (returnedRowCount == modelSubscription.getMaxEntities()) + break; + } + + currentIndex++; + } + + // If the loop was broken prematurely (max row count hit) we set the chunk data to the next index to start with. + // A non-null value of chunk data will cause a chunk token to be generated. + if (currentIndex < (existingList.size() - 1)) + chunkData = currentIndex + 1; + else + chunkData = null; + + if (modelSubscription.isBrief()) + result.getKeyBag().add(resultsKeyBag); + else + result.setTModelDetail(tmodelDetail); + + } + if (subscriptionFilter.getGetAssertionStatusReport() != null) { + // The coverage period doesn't apply here (basically because publisher assertions don't keep operational info). + // TODO, JUDDI-873 edit they do now, rewrite this query + GetAssertionStatusReport getAssertionStatusReport = subscriptionFilter.getGetAssertionStatusReport(); + List businessKeysFound = null; + businessKeysFound = FindBusinessByPublisherQuery.select(em, null, publisher, businessKeysFound); + + AssertionStatusReport assertionStatusReport = new AssertionStatusReport(); + + List pubAssertionList = org.apache.juddi.query.FindPublisherAssertionByBusinessQuery.select(em, businessKeysFound, getAssertionStatusReport.getCompletionStatus()); + //if (pubAssertionList==null) + // return result; + for (org.apache.juddi.model.PublisherAssertion modelPubAssertion : pubAssertionList) { + + if (startPointDate.after(modelPubAssertion.getModified())) { + continue; + } + + if (endPointDate.before(modelPubAssertion.getModified())) { + continue; + } + org.uddi.api_v3.AssertionStatusItem apiAssertionStatusItem = new org.uddi.api_v3.AssertionStatusItem(); + + MappingModelToApi.mapAssertionStatusItem(modelPubAssertion, apiAssertionStatusItem, businessKeysFound); + + assertionStatusReport.getAssertionStatusItem().add(apiAssertionStatusItem); + } + + + result.setAssertionStatusReport(assertionStatusReport); + } + + // If chunkData contains non-null data, a new token must be created and the token returned in the results + if (chunkData != null) { + String chunkToken = CHUNK_TOKEN_PREFIX + UUID.randomUUID(); + SubscriptionChunkToken newChunkToken = new SubscriptionChunkToken(chunkToken); + newChunkToken.setSubscriptionKey(body.getSubscriptionKey()); + newChunkToken.setStartPoint(startPointDate); + newChunkToken.setEndPoint(endPointDate); + newChunkToken.setData(chunkData); + + int chunkExpirationMinutes = DEFAULT_CHUNKEXPIRATION_MINUTES; + try { + chunkExpirationMinutes = AppConfig.getConfiguration().getInt(Property.JUDDI_SUBSCRIPTION_CHUNKEXPIRATION_MINUTES); + } + catch(ConfigurationException ce) { + throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval")); + } + newChunkToken.setExpiresAfter(new Date(System.currentTimeMillis() + ((long)chunkExpirationMinutes * 60L * 1000L))); + + em.persist(newChunkToken); + + result.setChunkToken(chunkToken); + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(SubscriptionQuery.GET_SUBSCRIPTIONRESULTS, + QueryStatus.SUCCESS, procTime); + + return result; + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(SubscriptionQuery.GET_SUBSCRIPTIONRESULTS, + QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + @SuppressWarnings("unchecked") + public List getSubscriptions(String authInfo) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); + + List result = new ArrayList(0); + + List modelSubscriptionList = (List)FindSubscriptionByPublisherQuery.select(em, publisher.getAuthorizedName()); + if (modelSubscriptionList != null && modelSubscriptionList.size() > 0) { + for (org.apache.juddi.model.Subscription modelSubscription : modelSubscriptionList) { + + Subscription apiSubscription = new Subscription(); + + MappingModelToApi.mapSubscription(modelSubscription, apiSubscription); + + result.add(apiSubscription); + } + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(SubscriptionQuery.GET_SUBSCRIPTIONS, + QueryStatus.SUCCESS, procTime); + + return result; + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(SubscriptionQuery.GET_SUBSCRIPTIONS, + QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + + /* + * @see org.uddi.v3_service.UDDISubscriptionPortType#saveSubscription(java.lang.String, javax.xml.ws.Holder) + * + * Notes: The matching keys are saved on a new subscription (or renewed subscription) for the find_* filters only. With the other filter + * types, taking a snapshot of the matches doesn't make sense. + * + */ + public void saveSubscription(String authInfo, + Holder> subscription) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); + publisher.populateKeyGeneratorKeys(em); + new ValidateSubscription(publisher).validateSubscriptions(em, subscription.value, publisher); + + List apiSubscriptionList = subscription.value; + for (org.uddi.sub_v3.Subscription apiSubscription : apiSubscriptionList) { + + org.apache.juddi.model.Subscription modelSubscription = new org.apache.juddi.model.Subscription(); + + Object existing = em.find(org.apache.juddi.model.Subscription.class, apiSubscription.getSubscriptionKey()); + if (existing != null) { + org.apache.juddi.model.Subscription existingEntity = (org.apache.juddi.model.Subscription) existing; + doRenewal(existingEntity, apiSubscription); + //carrying over the created and last notified dates if this is a renewal. + modelSubscription.setCreateDate(existingEntity.getCreateDate()); + modelSubscription.setLastNotified(existingEntity.getLastNotified()); + em.remove(existing); + } else { + modelSubscription.setCreateDate(new Date()); + } + + doSubscriptionExpirationDate(apiSubscription); + + MappingApiToModel.mapSubscription(apiSubscription, modelSubscription); + + modelSubscription.setAuthorizedName(publisher.getAuthorizedName()); + + // Add the matching keys to the match collection + List keys = getSubscriptionMatches(apiSubscription.getSubscriptionFilter(), em); + if (keys != null && keys.size() > 0) { + for (Object key : keys) { + SubscriptionMatch subMatch = new SubscriptionMatch(modelSubscription, (String)key); + modelSubscription.getSubscriptionMatches().add(subMatch); + } + } + + em.persist(modelSubscription); + } + + tx.commit(); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(SubscriptionQuery.SAVE_SUBSCRIPTION, + QueryStatus.SUCCESS, procTime); + } catch (DispositionReportFaultMessage drfm) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(SubscriptionQuery.SAVE_SUBSCRIPTION, + QueryStatus.FAILED, procTime); + throw drfm; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + /** + * Will perform the necessary logic for when a subscription is renewed (evidenced by a subscription with the same key in existence). + * In general, the appropriate data is copied from the stored subscription to the renewal subscription request. + * + * @param existingSubscription - existing stored subscription + * @param apiSubscription - renewal subscription request + * @throws DispositionReportFaultMessage + */ + protected void doRenewal(org.apache.juddi.model.Subscription existingSubscription, org.uddi.sub_v3.Subscription apiSubscription) throws DispositionReportFaultMessage { + if (apiSubscription.getSubscriptionFilter() == null) { + String rawFilter = existingSubscription.getSubscriptionFilter(); + try { + SubscriptionFilter existingFilter = (SubscriptionFilter)JAXBMarshaller.unmarshallFromString(rawFilter, "org.uddi.sub_v3"); + apiSubscription.setSubscriptionFilter(existingFilter); + } + catch (JAXBException e) { + logger.error("JAXB Exception while marshalling subscription filter", e); + throw new FatalErrorException(new ErrorMessage("errors.Unspecified")); + } + } + + } + + /** + * Will add the expiration date to the provided subscription request. Date is earlier of user provided date and the system default + * + * @param apiSubscription + * @throws DispositionReportFaultMessage + */ + protected void doSubscriptionExpirationDate(org.uddi.sub_v3.Subscription apiSubscription) throws DispositionReportFaultMessage { + + int subscriptionExpirationDays = DEFAULT_SUBSCRIPTIONEXPIRATION_DAYS; + try { + subscriptionExpirationDays = AppConfig.getConfiguration().getInt(Property.JUDDI_SUBSCRIPTION_EXPIRATION_DAYS); + } + catch(ConfigurationException ce) { + throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval")); + } + + GregorianCalendar expirationDate = new GregorianCalendar(); + expirationDate.add(GregorianCalendar.DAY_OF_MONTH, subscriptionExpirationDays); + + // The expiration date is the earlier of the provided date and that specified by the parameter. + if (apiSubscription.getExpiresAfter() != null) { + GregorianCalendar userExpiration = apiSubscription.getExpiresAfter().toGregorianCalendar(); + if (userExpiration.getTimeInMillis() < expirationDate.getTimeInMillis()) + expirationDate.setTimeInMillis(userExpiration.getTimeInMillis()); + } + + try { + DatatypeFactory df = DatatypeFactory.newInstance(); + apiSubscription.setExpiresAfter(df.newXMLGregorianCalendar(expirationDate)); + } + catch(DatatypeConfigurationException ce) { + throw new FatalErrorException(new ErrorMessage("errors.Unspecified")); + } + + } + + /** + * Will take a snapshot of the keys that match the subscription filter return them. Currently, keys are only returned for the find_* + * filters. It seems redundant to return the keys in the get_*Detail filters. + * + * @param subscriptionFilter + * @param em + * @return a list of subscription matches + * @throws DispositionReportFaultMessage + */ + protected List getSubscriptionMatches(SubscriptionFilter subscriptionFilter, EntityManager em) + throws DispositionReportFaultMessage { + + + List keys = null; + if (subscriptionFilter.getFindBinding() != null) { + org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); + findQualifiers.mapApiFindQualifiers(subscriptionFilter.getFindBinding().getFindQualifiers()); + keys = InquiryHelper.findBinding(subscriptionFilter.getFindBinding(), findQualifiers, em); + } + if (subscriptionFilter.getFindBusiness() != null) { + org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); + findQualifiers.mapApiFindQualifiers(subscriptionFilter.getFindBusiness().getFindQualifiers()); + keys = InquiryHelper.findBusiness(subscriptionFilter.getFindBusiness(), findQualifiers, em); + } + if (subscriptionFilter.getFindService() != null) { + org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); + findQualifiers.mapApiFindQualifiers(subscriptionFilter.getFindService().getFindQualifiers()); + keys = InquiryHelper.findService(subscriptionFilter.getFindService(), findQualifiers, em); + } + if (subscriptionFilter.getFindTModel() != null) { + org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers(); + findQualifiers.mapApiFindQualifiers(subscriptionFilter.getFindTModel().getFindQualifiers()); + keys = InquiryHelper.findTModel(subscriptionFilter.getFindTModel(), findQualifiers, em); + } + if (subscriptionFilter.getFindRelatedBusinesses() != null) { + // TODO: should we bother taking a snapshot of these? + } + if (subscriptionFilter.getGetBindingDetail() != null) { + //keys = subscriptionFilter.getGetBindingDetail().getBindingKey(); + // Nothing needs to be done + } + if (subscriptionFilter.getGetBusinessDetail() != null) { + //keys = subscriptionFilter.getGetBusinessDetail().getBusinessKey(); + // Nothing needs to be done + } + if (subscriptionFilter.getGetServiceDetail() != null) { + //keys = subscriptionFilter.getGetServiceDetail().getServiceKey(); + // Nothing needs to be done + } + if (subscriptionFilter.getGetTModelDetail() != null) { + //keys = subscriptionFilter.getGetTModelDetail().getTModelKey(); + // Nothing needs to be done + } + if (subscriptionFilter.getGetAssertionStatusReport() != null) { + // Nothing needs to be done + } + return keys; + + } + + private List getMissingKeys(List currentMatchingKeys, List subscriptionMatches) { + + List result = new ArrayList(subscriptionMatches.size()); + for (SubscriptionMatch subMatch : subscriptionMatches) + result.add(subMatch.getEntityKey()); + + result.removeAll(currentMatchingKeys); + + return result; + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDISubscriptionListenerImpl.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDISubscriptionListenerImpl.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/api/impl/UDDISubscriptionListenerImpl.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDISubscriptionListenerImpl.java index dbe328e97..8c12241ba 100644 --- a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDISubscriptionListenerImpl.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDISubscriptionListenerImpl.java @@ -1,115 +1,115 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.io.StringWriter; - -import javax.jws.WebService; -import javax.persistence.EntityManager; -import javax.persistence.EntityTransaction; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.config.PersistenceManager; -import org.apache.juddi.mapping.MappingModelToApi; -import org.apache.juddi.subscription.NotificationList; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.FatalErrorException; -import org.apache.juddi.v3.error.InvalidKeyPassedException; -import org.apache.juddi.validation.ValidateSubscriptionListener; -import org.uddi.api_v3.DispositionReport; -import org.uddi.api_v3.Result; -import org.uddi.subr_v3.NotifySubscriptionListener; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.v3_service.UDDISubscriptionListenerPortType; - -/** - * This class implements the UDDI v3 Subscription Listener API (server side) - * for jUDDI. It is primarily used for server to server subscriptions. - * - */ -@WebService(serviceName="UDDISubscriptionListenerService", - endpointInterface="org.uddi.v3_service.UDDISubscriptionListenerPortType", - targetNamespace = "urn:uddi-org:api_v3_portType") -public class UDDISubscriptionListenerImpl extends AuthenticatedService implements - UDDISubscriptionListenerPortType { - - private static Log logger = LogFactory.getLog(UDDISubscriptionListenerImpl.class); - - @SuppressWarnings("unchecked") - public DispositionReport notifySubscriptionListener( - NotifySubscriptionListener body) - throws DispositionReportFaultMessage { - try { - JAXBContext context = JAXBContext.newInstance(body.getClass()); - Marshaller marshaller = context.createMarshaller(); - StringWriter sw = new StringWriter(); - marshaller.marshal(body, sw); - - logger.info("Notification received by UDDISubscriptionListenerService : " + sw.toString()); - - @SuppressWarnings("rawtypes") - NotificationList nl = NotificationList.getInstance(); - nl.getNotifications().add(sw.toString()); - - org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo = null; - - //find the clerks to go with this subscription - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - this.getEntityPublisher(em, body.getAuthInfo()); - String subscriptionKey = body.getSubscriptionResultsList().getSubscription().getSubscriptionKey(); - org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo = null; - try { - modelClientSubscriptionInfo = em.find(org.apache.juddi.model.ClientSubscriptionInfo.class, subscriptionKey); - } catch (ClassCastException e) {} - if (modelClientSubscriptionInfo == null) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.SubscripKeyNotFound", subscriptionKey)); - } - apiClientSubscriptionInfo = new org.apache.juddi.api_v3.ClientSubscriptionInfo(); - MappingModelToApi.mapClientSubscriptionInfo(modelClientSubscriptionInfo, apiClientSubscriptionInfo,em); - - tx.commit(); - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - XRegisterHelper.handle(apiClientSubscriptionInfo.getFromClerk(),apiClientSubscriptionInfo.getToClerk(), body.getSubscriptionResultsList()); - - } catch (JAXBException jaxbe) { - logger.error("", jaxbe); - throw new FatalErrorException(new ErrorMessage("errors.subscriptionnotifier.client")); - } - - new ValidateSubscriptionListener().validateNotification(body); - - DispositionReport dr = new DispositionReport(); - Result res = new Result(); - dr.getResult().add(res); - return dr; - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.io.StringWriter; + +import javax.jws.WebService; +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.config.PersistenceManager; +import org.apache.juddi.mapping.MappingModelToApi; +import org.apache.juddi.subscription.NotificationList; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.FatalErrorException; +import org.apache.juddi.v3.error.InvalidKeyPassedException; +import org.apache.juddi.validation.ValidateSubscriptionListener; +import org.uddi.api_v3.DispositionReport; +import org.uddi.api_v3.Result; +import org.uddi.subr_v3.NotifySubscriptionListener; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.v3_service.UDDISubscriptionListenerPortType; + +/** + * This class implements the UDDI v3 Subscription Listener API (server side) + * for jUDDI. It is primarily used for server to server subscriptions. + * + */ +@WebService(serviceName="UDDISubscriptionListenerService", + endpointInterface="org.uddi.v3_service.UDDISubscriptionListenerPortType", + targetNamespace = "urn:uddi-org:api_v3_portType") +public class UDDISubscriptionListenerImpl extends AuthenticatedService implements + UDDISubscriptionListenerPortType { + + private static Log logger = LogFactory.getLog(UDDISubscriptionListenerImpl.class); + + @SuppressWarnings("unchecked") + public DispositionReport notifySubscriptionListener( + NotifySubscriptionListener body) + throws DispositionReportFaultMessage { + try { + JAXBContext context = JAXBContext.newInstance(body.getClass()); + Marshaller marshaller = context.createMarshaller(); + StringWriter sw = new StringWriter(); + marshaller.marshal(body, sw); + + logger.info("Notification received by UDDISubscriptionListenerService : " + sw.toString()); + + @SuppressWarnings("rawtypes") + NotificationList nl = NotificationList.getInstance(); + nl.getNotifications().add(sw.toString()); + + org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo = null; + + //find the clerks to go with this subscription + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + this.getEntityPublisher(em, body.getAuthInfo()); + String subscriptionKey = body.getSubscriptionResultsList().getSubscription().getSubscriptionKey(); + org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo = null; + try { + modelClientSubscriptionInfo = em.find(org.apache.juddi.model.ClientSubscriptionInfo.class, subscriptionKey); + } catch (ClassCastException e) {} + if (modelClientSubscriptionInfo == null) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.SubscripKeyNotFound", subscriptionKey)); + } + apiClientSubscriptionInfo = new org.apache.juddi.api_v3.ClientSubscriptionInfo(); + MappingModelToApi.mapClientSubscriptionInfo(modelClientSubscriptionInfo, apiClientSubscriptionInfo,em); + + tx.commit(); + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + XRegisterHelper.handle(apiClientSubscriptionInfo.getFromClerk(),apiClientSubscriptionInfo.getToClerk(), body.getSubscriptionResultsList()); + + } catch (JAXBException jaxbe) { + logger.error("", jaxbe); + throw new FatalErrorException(new ErrorMessage("errors.subscriptionnotifier.client")); + } + + new ValidateSubscriptionListener().validateNotification(body); + + DispositionReport dr = new DispositionReport(); + Result res = new Result(); + dr.getResult().add(res); + return dr; + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIValueSetCachingImpl.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIValueSetCachingImpl.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIValueSetCachingImpl.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIValueSetCachingImpl.java index 4e6cc21e3..fb2a96ae8 100644 --- a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIValueSetCachingImpl.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIValueSetCachingImpl.java @@ -1,97 +1,97 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.util.ArrayList; -import java.util.List; -import javax.jws.WebService; - -import javax.xml.ws.Holder; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.api.util.QueryStatus; -import org.apache.juddi.api.util.ValueSetCachingQuery; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.v3_service.UDDIValueSetCachingPortType; -import org.uddi.vscache_v3.ValidValue; - -@WebService(serviceName="UDDIValueSetCachingService", - endpointInterface="org.uddi.v3_service.UDDIValueSetCachingPortType", - targetNamespace = "urn:uddi-org:v3_service") -public class UDDIValueSetCachingImpl extends AuthenticatedService implements UDDIValueSetCachingPortType { - - private static Log logger = LogFactory.getLog(UDDIValueSetCachingImpl.class); - private UDDIServiceCounter serviceCounter; - - public UDDIValueSetCachingImpl() { - super(); - serviceCounter = ServiceCounterLifecycleResource.getServiceCounter(this.getClass()); - } - - /** - * - * @param authInfo An optional element that contains an authentication - * token. Authentication tokens are obtained using the get_authToken API - * call or through some other means external to this specification. - * Providers of get_allValidValues Web services that serve multiple - * registries and providers that restrict who can use their service may - * require authInfo for this API. - * @param modelKey A required uddiKey value that identifies the specific - * instance of the tModel which describes the value set or category - * group system for which a Web service to get all valid values has been - * provided. It uniquely identifies the category, identifier, or - * category group system for which valid values are being requested. - * @param chunkToken Optional element used to retrieve subsequent groups - * of data when the first invocation of this API indicates more data is - * available. This occurs when a chunkToken is returned whose value is - * not "0" in the validValuesList structure described in the next - * section. To retrieve the next chunk of data, the chunkToken returned - * should be used as an argument to the next invocation of this API. - * @param validValue A validValuesList structure is returned containing - * the set of valid values for the external category or identifier - * system. The list MUST contain a chunkToken if the Web service - * provider wishes to provide the data in packets. - * @throws DispositionReportFaultMessage - */ - @Override - public void getAllValidValues(String authInfo, String modelKey, - Holder chunkToken, Holder> validValue) - throws DispositionReportFaultMessage { - - long startTime = System.currentTimeMillis(); - List validValues = UDDIValueSetValidationImpl.getValidValues(modelKey); - - Holder> ret = new Holder>(new ArrayList()); - if (validValues != null) { - for (int i = 0; i < validValues.size(); i++) { - ValidValue x = new ValidValue(validValues.get(i)); - ret.value.add(x); - } - } - //findbugs will flag the following as "UC_USELESS_OBJECT" when in fact - //it is returned as part of the service call - chunkToken = new Holder(); - chunkToken.value ="0"; - - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(ValueSetCachingQuery.GET_ALLVALIDVALUES, - QueryStatus.SUCCESS, procTime); - - - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.util.ArrayList; +import java.util.List; +import javax.jws.WebService; + +import javax.xml.ws.Holder; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.api.util.QueryStatus; +import org.apache.juddi.api.util.ValueSetCachingQuery; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.v3_service.UDDIValueSetCachingPortType; +import org.uddi.vscache_v3.ValidValue; + +@WebService(serviceName="UDDIValueSetCachingService", + endpointInterface="org.uddi.v3_service.UDDIValueSetCachingPortType", + targetNamespace = "urn:uddi-org:v3_service") +public class UDDIValueSetCachingImpl extends AuthenticatedService implements UDDIValueSetCachingPortType { + + private static Log logger = LogFactory.getLog(UDDIValueSetCachingImpl.class); + private UDDIServiceCounter serviceCounter; + + public UDDIValueSetCachingImpl() { + super(); + serviceCounter = ServiceCounterLifecycleResource.getServiceCounter(this.getClass()); + } + + /** + * + * @param authInfo An optional element that contains an authentication + * token. Authentication tokens are obtained using the get_authToken API + * call or through some other means external to this specification. + * Providers of get_allValidValues Web services that serve multiple + * registries and providers that restrict who can use their service may + * require authInfo for this API. + * @param modelKey A required uddiKey value that identifies the specific + * instance of the tModel which describes the value set or category + * group system for which a Web service to get all valid values has been + * provided. It uniquely identifies the category, identifier, or + * category group system for which valid values are being requested. + * @param chunkToken Optional element used to retrieve subsequent groups + * of data when the first invocation of this API indicates more data is + * available. This occurs when a chunkToken is returned whose value is + * not "0" in the validValuesList structure described in the next + * section. To retrieve the next chunk of data, the chunkToken returned + * should be used as an argument to the next invocation of this API. + * @param validValue A validValuesList structure is returned containing + * the set of valid values for the external category or identifier + * system. The list MUST contain a chunkToken if the Web service + * provider wishes to provide the data in packets. + * @throws DispositionReportFaultMessage + */ + @Override + public void getAllValidValues(String authInfo, String modelKey, + Holder chunkToken, Holder> validValue) + throws DispositionReportFaultMessage { + + long startTime = System.currentTimeMillis(); + List validValues = UDDIValueSetValidationImpl.getValidValues(modelKey); + + Holder> ret = new Holder>(new ArrayList()); + if (validValues != null) { + for (int i = 0; i < validValues.size(); i++) { + ValidValue x = new ValidValue(validValues.get(i)); + ret.value.add(x); + } + } + //findbugs will flag the following as "UC_USELESS_OBJECT" when in fact + //it is returned as part of the service call + chunkToken = new Holder(); + chunkToken.value ="0"; + + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(ValueSetCachingQuery.GET_ALLVALIDVALUES, + QueryStatus.SUCCESS, procTime); + + + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIValueSetValidationImpl.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIValueSetValidationImpl.java similarity index 98% rename from juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIValueSetValidationImpl.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIValueSetValidationImpl.java index 59f2ebe28..430b86937 100644 --- a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIValueSetValidationImpl.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIValueSetValidationImpl.java @@ -1,368 +1,368 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import javax.jws.WebService; -import javax.persistence.EntityManager; -import javax.persistence.EntityTransaction; -import static org.apache.juddi.api.impl.AuthenticatedService.logger; -import org.apache.juddi.api.util.QueryStatus; -import org.apache.juddi.api.util.ValueSetValidationQuery; -import org.apache.juddi.config.PersistenceManager; -import org.apache.juddi.model.Tmodel; -import org.apache.juddi.v3.client.UDDIConstants; -import org.apache.juddi.v3.client.UDDIConstantsV2; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.FatalErrorException; -import org.apache.juddi.v3.error.ValueNotAllowedException; -import org.apache.juddi.validation.vsv.AbstractSimpleValidator; -import org.apache.juddi.validation.vsv.ValueSetValidator; -import org.uddi.api_v3.BindingTemplate; -import org.uddi.api_v3.BusinessEntity; -import org.uddi.api_v3.BusinessService; -import org.uddi.api_v3.DispositionReport; -import org.uddi.api_v3.KeyedReference; -import org.uddi.api_v3.KeyedReferenceGroup; -import org.uddi.api_v3.PublisherAssertion; -import org.uddi.api_v3.Result; -import org.uddi.api_v3.TModel; -import org.uddi.api_v3.TModelInstanceInfo; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.v3_service.UDDIValueSetValidationPortType; -import org.uddi.vs_v3.ValidateValues; - -/** - * Implementation the UDDI v3 spec for Value Set Validation This is basically - * used to validate Keyed Reference value sets and offers validation via jUDDI's - * VSV extensibility framework.

- * To use this, define a tModel containing the following - *
<categoryBag>
- * <keyedReference keyName=""
- * keyValue="uddi:juddi.apache.org:servicebindings-valueset-cp"
- * tModelKey="uddi:uddi.org:identifier:validatedby"/>
- * </categoryBag>
- * 
Where uddi:juddi.apache.org:servicebindings-valueset-cp is the binding - * key of the service implementing the VSV API (this service). - *

- * From there, you need to create a class that either implements - * {@link ValueSetValidator} or extends {@link AbstractSimpleValidator}. It must - * be in the package named org.apache.juddi.validation.vsv and must by named - * following the convention outlined in {@link #convertKeyToClass(java.lang.String) - * } - * - * @see ValueSetValidator - * @see AbstractSimpleValidator - * @author Alex O'Ree - */ -@WebService(serviceName="UDDIValueSetCachingService", endpointInterface = "org.uddi.v3_service.UDDIValueSetValidationPortType" - , targetNamespace = "urn:uddi-org:api_v3_portType") -public class UDDIValueSetValidationImpl extends AuthenticatedService implements - UDDIValueSetValidationPortType { - - private UDDIServiceCounter serviceCounter; - - public UDDIValueSetValidationImpl() { - super(); - serviceCounter = ServiceCounterLifecycleResource.getServiceCounter(this.getClass()); - } - - @Override - public DispositionReport validateValues(ValidateValues body) - throws DispositionReportFaultMessage { - long startTime = System.currentTimeMillis(); - - if (body == null) { - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(ValueSetValidationQuery.VALIDATE_VALUES, - QueryStatus.FAILED, procTime); - - throw new ValueNotAllowedException(new ErrorMessage("errors.valuesetvalidation.noinput")); - } - /* - * The UDDI node that is calling validate_values MUST pass one - * or more businessEntity elements, one or more businessService - * elements, one or more bindingTemplate elements, one or more - * tModel elements, or one or more publisherAssertion elements - * as the sole argument to this Web service. - * */ - - - /* performs validation on all of the keyedReferences or keyedReferenceGroups */ - - /*when the entity being saved is a businessEntity, contained - * businessService and bindingTemplate entities may themselves - * reference values from the authorized value sets as well. */ - //go through all published items - //pull out all keys - //look up keys in database for a validation class - //dedup results - //run validation classes - List classNames = new ArrayList(); - classNames.addAll(validateValuesBindingTemplate(body.getBindingTemplate())); - classNames.addAll(validateValuesBusinessEntity(body.getBusinessEntity())); - classNames.addAll(validateValuesBusinessService(body.getBusinessService())); - classNames.addAll(validateValuesPublisherAssertion(body.getPublisherAssertion())); - classNames.addAll(validateValuesTModel(body.getTModel())); - Set set = new HashSet(classNames); - Iterator iterator = set.iterator(); - Set validators = new HashSet(); - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - //for each key to process - try { - while (iterator.hasNext()) { - - String key = iterator.next(); - //find out if it needs to be validated - Tmodel find = em.find(org.apache.juddi.model.Tmodel.class, key); - if (find != null) { - //if it is, added it to the list - if (containsValidatedKey(find, UDDIConstants.IS_VALIDATED_BY)) { - validators.add(key); - } - if (containsValidatedKey(find, UDDIConstantsV2.IS_VALIDATED_BY)) { - validators.add(key); - } - } - } - - } catch (Exception drfm) { - logger.warn("Unable to process vsv validation", drfm); - throw new FatalErrorException(new ErrorMessage("errors.valuesetvalidation.fatal", drfm.getMessage())); - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - Iterator iterator1 = validators.iterator(); - while (iterator1.hasNext()) { - String tmodelkey = iterator1.next(); - String clazz = convertKeyToClass(tmodelkey); - ValueSetValidator vsv; - if (clazz == null) { - logger.info("No validator found for " + tmodelkey); - } else { - try { - vsv = (ValueSetValidator) Class.forName(clazz).newInstance(); - logger.info("translated " + tmodelkey + " to class " + clazz); - vsv.validateValuesBindingTemplate(body.getBindingTemplate(), ""); - vsv.validateValuesBusinessEntity(body.getBusinessEntity()); - vsv.validateValuesBusinessService(body.getBusinessService(), ""); - vsv.validateValuesPublisherAssertion(body.getPublisherAssertion()); - vsv.validateValuesTModel(body.getTModel()); - } catch (ClassNotFoundException ex) { - logger.warn("Unable to process vsv validation for " + tmodelkey, ex); - throw new FatalErrorException(new ErrorMessage("errors.valuesetvalidation.fatal", "key=" + tmodelkey + " class=" + clazz + " " + ex.getMessage())); - } catch (InstantiationException ex) { - logger.warn("Unable to process vsv validation for " + tmodelkey, ex); - throw new FatalErrorException(new ErrorMessage("errors.valuesetvalidation.fatal", "key=" + tmodelkey + " class=" + clazz + " " + ex.getMessage())); - } catch (IllegalAccessException ex) { - logger.warn("Unable to process vsv validation for " + tmodelkey, ex); - throw new FatalErrorException(new ErrorMessage("errors.valuesetvalidation.fatal", "key=" + tmodelkey + " class=" + clazz + " " + ex.getMessage())); - } - } - } - - DispositionReport r = new DispositionReport(); - r.getResult().add(new Result()); - long procTime = System.currentTimeMillis() - startTime; - serviceCounter.update(ValueSetValidationQuery.VALIDATE_VALUES, - QueryStatus.SUCCESS, procTime); - - return r; - } - - private List validateValuesBindingTemplate(List items) { - List ret = new ArrayList(); - if (items == null) { - return ret; - } - for (int i = 0; i < items.size(); i++) { - if (items.get(i).getCategoryBag() != null) { - ret.addAll(validateValuesKeyRef(items.get(i).getCategoryBag().getKeyedReference())); - ret.addAll(validateValuesKeyRefGrp(items.get(i).getCategoryBag().getKeyedReferenceGroup())); - } - if (items.get(i).getTModelInstanceDetails() != null) { - - //validateTmodelInstanceDetails(items.get(i).getTModelInstanceDetails().getTModelInstanceInfo(), xpath + "bindingTemplate(" + i + ").tModelInstanceDetails."); - } - } - return ret; - } - - private List validateValuesBusinessEntity(List items) { - List ret = new ArrayList(); - if (items == null) { - return ret; - } - for (int i = 0; i < items.size(); i++) { - if (items.get(i).getCategoryBag() != null) { - ret.addAll(validateValuesKeyRef(items.get(i).getCategoryBag().getKeyedReference())); - ret.addAll(validateValuesKeyRefGrp(items.get(i).getCategoryBag().getKeyedReferenceGroup())); - } - if (items.get(i).getIdentifierBag() != null) { - ret.addAll(validateValuesKeyRef(items.get(i).getIdentifierBag().getKeyedReference())); - } - if (items.get(i).getBusinessServices() != null) { - ret.addAll(validateValuesBusinessService(items.get(i).getBusinessServices().getBusinessService())); - } - } - return ret; - } - - private List validateValuesBusinessService(List items) { - List ret = new ArrayList(); - if (items == null) { - return ret; - } - for (int i = 0; i < items.size(); i++) { - if (items.get(i).getCategoryBag() != null) { - ret.addAll(validateValuesKeyRef(items.get(i).getCategoryBag().getKeyedReference())); - ret.addAll(validateValuesKeyRefGrp(items.get(i).getCategoryBag().getKeyedReferenceGroup())); - } - if (items.get(i).getBindingTemplates() != null) { - ret.addAll(validateValuesBindingTemplate(items.get(i).getBindingTemplates().getBindingTemplate())); - } - } - return ret; - } - - private List validateValuesPublisherAssertion(List items) { - - List ret = new ArrayList(); - if (items == null) { - return ret; - } - for (int i = 0; i < items.size(); i++) { - if (items.get(i).getKeyedReference() != null) { - List temp = new ArrayList(); - temp.add(items.get(i).getKeyedReference()); - ret.addAll(validateValuesKeyRef(temp)); - } - } - return ret; - } - - private List validateValuesTModel(List items) { - List ret = new ArrayList(); - if (items == null) { - return ret; - } - for (int i = 0; i < items.size(); i++) { - if (items.get(i).getCategoryBag() != null) { - ret.addAll(validateValuesKeyRef(items.get(i).getCategoryBag().getKeyedReference())); - ret.addAll(validateValuesKeyRefGrp(items.get(i).getCategoryBag().getKeyedReferenceGroup())); - } - if (items.get(i).getIdentifierBag() != null) { - ret.addAll(validateValuesKeyRef(items.get(i).getIdentifierBag().getKeyedReference())); - } - } - return ret; - } - - private List validateValuesKeyRef(List items) { - List ret = new ArrayList(); - if (items == null) { - return ret; - } - - for (int i = 0; i < items.size(); i++) { - ret.add(items.get(i).getTModelKey()); - } - - return ret; - } - - private List validateValuesKeyRefGrp(List items) { - List ret = new ArrayList(); - if (items == null) { - return ret; - } - for (int i = 0; i < items.size(); i++) { - ret.addAll(validateValuesKeyRef(items.get(i).getKeyedReference())); - } - return ret; - } - - - - public static String convertKeyToClass(String tmodelkey) { - - if (tmodelkey == null) { - return null; - } - if (tmodelkey.length() < 2) { - return null; - } - - String key = new String(new char[]{tmodelkey.charAt(0)}).toUpperCase() + tmodelkey.substring(1).toLowerCase(); - key = key.replaceAll("[^a-zA-Z0-9]", ""); - - String clazz = "org.apache.juddi.validation.vsv." + key; - - return clazz; - - } - - public static List getValidValues(String modelKey) { - try { - ValueSetValidator vsv = (ValueSetValidator) Class.forName(convertKeyToClass(modelKey)).newInstance(); - return vsv.getValidValues(); - } catch (ClassNotFoundException ex) { - } catch (InstantiationException ex) { - } catch (IllegalAccessException ex) { - } - return null; - } - - private boolean containsValidatedKey(Tmodel find, String key) { - if (find.getCategoryBag() != null) { - if (find.getCategoryBag().getKeyedReferences() != null) { - for (int i = 0; i < find.getCategoryBag().getKeyedReferences().size(); i++) { - if (key.equalsIgnoreCase(find.getCategoryBag().getKeyedReferences().get(i).getTmodelKeyRef())) { - return true; - } - } - } - if (find.getCategoryBag().getKeyedReferenceGroups() != null) { - for (int i = 0; i < find.getCategoryBag().getKeyedReferenceGroups().size(); i++) { - for (int k = 0; k < find.getCategoryBag().getKeyedReferenceGroups().get(i).getKeyedReferences().size(); k++) { - if (key.equalsIgnoreCase(find.getCategoryBag().getKeyedReferenceGroups().get(i).getKeyedReferences().get(k).getTmodelKeyRef())) { - return true; - } - } - } - } - } - if (find.getTmodelIdentifiers() != null) { - - for (int i = 0; i < find.getTmodelIdentifiers().size(); i++) { - if (key.equalsIgnoreCase(find.getTmodelIdentifiers().get(i).getTmodelKeyRef())) { - return true; - } - } - } - - return false; - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import javax.jws.WebService; +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import static org.apache.juddi.api.impl.AuthenticatedService.logger; +import org.apache.juddi.api.util.QueryStatus; +import org.apache.juddi.api.util.ValueSetValidationQuery; +import org.apache.juddi.config.PersistenceManager; +import org.apache.juddi.model.Tmodel; +import org.apache.juddi.v3.client.UDDIConstants; +import org.apache.juddi.v3.client.UDDIConstantsV2; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.FatalErrorException; +import org.apache.juddi.v3.error.ValueNotAllowedException; +import org.apache.juddi.validation.vsv.AbstractSimpleValidator; +import org.apache.juddi.validation.vsv.ValueSetValidator; +import org.uddi.api_v3.BindingTemplate; +import org.uddi.api_v3.BusinessEntity; +import org.uddi.api_v3.BusinessService; +import org.uddi.api_v3.DispositionReport; +import org.uddi.api_v3.KeyedReference; +import org.uddi.api_v3.KeyedReferenceGroup; +import org.uddi.api_v3.PublisherAssertion; +import org.uddi.api_v3.Result; +import org.uddi.api_v3.TModel; +import org.uddi.api_v3.TModelInstanceInfo; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.v3_service.UDDIValueSetValidationPortType; +import org.uddi.vs_v3.ValidateValues; + +/** + * Implementation the UDDI v3 spec for Value Set Validation This is basically + * used to validate Keyed Reference value sets and offers validation via jUDDI's + * VSV extensibility framework.

+ * To use this, define a tModel containing the following + *
<categoryBag>
+ * <keyedReference keyName=""
+ * keyValue="uddi:juddi.apache.org:servicebindings-valueset-cp"
+ * tModelKey="uddi:uddi.org:identifier:validatedby"/>
+ * </categoryBag>
+ * 
Where uddi:juddi.apache.org:servicebindings-valueset-cp is the binding + * key of the service implementing the VSV API (this service). + *

+ * From there, you need to create a class that either implements + * {@link ValueSetValidator} or extends {@link AbstractSimpleValidator}. It must + * be in the package named org.apache.juddi.validation.vsv and must by named + * following the convention outlined in {@link #convertKeyToClass(java.lang.String) + * } + * + * @see ValueSetValidator + * @see AbstractSimpleValidator + * @author Alex O'Ree + */ +@WebService(serviceName="UDDIValueSetCachingService", endpointInterface = "org.uddi.v3_service.UDDIValueSetValidationPortType" + , targetNamespace = "urn:uddi-org:api_v3_portType") +public class UDDIValueSetValidationImpl extends AuthenticatedService implements + UDDIValueSetValidationPortType { + + private UDDIServiceCounter serviceCounter; + + public UDDIValueSetValidationImpl() { + super(); + serviceCounter = ServiceCounterLifecycleResource.getServiceCounter(this.getClass()); + } + + @Override + public DispositionReport validateValues(ValidateValues body) + throws DispositionReportFaultMessage { + long startTime = System.currentTimeMillis(); + + if (body == null) { + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(ValueSetValidationQuery.VALIDATE_VALUES, + QueryStatus.FAILED, procTime); + + throw new ValueNotAllowedException(new ErrorMessage("errors.valuesetvalidation.noinput")); + } + /* + * The UDDI node that is calling validate_values MUST pass one + * or more businessEntity elements, one or more businessService + * elements, one or more bindingTemplate elements, one or more + * tModel elements, or one or more publisherAssertion elements + * as the sole argument to this Web service. + * */ + + + /* performs validation on all of the keyedReferences or keyedReferenceGroups */ + + /*when the entity being saved is a businessEntity, contained + * businessService and bindingTemplate entities may themselves + * reference values from the authorized value sets as well. */ + //go through all published items + //pull out all keys + //look up keys in database for a validation class + //dedup results + //run validation classes + List classNames = new ArrayList(); + classNames.addAll(validateValuesBindingTemplate(body.getBindingTemplate())); + classNames.addAll(validateValuesBusinessEntity(body.getBusinessEntity())); + classNames.addAll(validateValuesBusinessService(body.getBusinessService())); + classNames.addAll(validateValuesPublisherAssertion(body.getPublisherAssertion())); + classNames.addAll(validateValuesTModel(body.getTModel())); + Set set = new HashSet(classNames); + Iterator iterator = set.iterator(); + Set validators = new HashSet(); + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + //for each key to process + try { + while (iterator.hasNext()) { + + String key = iterator.next(); + //find out if it needs to be validated + Tmodel find = em.find(org.apache.juddi.model.Tmodel.class, key); + if (find != null) { + //if it is, added it to the list + if (containsValidatedKey(find, UDDIConstants.IS_VALIDATED_BY)) { + validators.add(key); + } + if (containsValidatedKey(find, UDDIConstantsV2.IS_VALIDATED_BY)) { + validators.add(key); + } + } + } + + } catch (Exception drfm) { + logger.warn("Unable to process vsv validation", drfm); + throw new FatalErrorException(new ErrorMessage("errors.valuesetvalidation.fatal", drfm.getMessage())); + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + Iterator iterator1 = validators.iterator(); + while (iterator1.hasNext()) { + String tmodelkey = iterator1.next(); + String clazz = convertKeyToClass(tmodelkey); + ValueSetValidator vsv; + if (clazz == null) { + logger.info("No validator found for " + tmodelkey); + } else { + try { + vsv = (ValueSetValidator) Class.forName(clazz).newInstance(); + logger.info("translated " + tmodelkey + " to class " + clazz); + vsv.validateValuesBindingTemplate(body.getBindingTemplate(), ""); + vsv.validateValuesBusinessEntity(body.getBusinessEntity()); + vsv.validateValuesBusinessService(body.getBusinessService(), ""); + vsv.validateValuesPublisherAssertion(body.getPublisherAssertion()); + vsv.validateValuesTModel(body.getTModel()); + } catch (ClassNotFoundException ex) { + logger.warn("Unable to process vsv validation for " + tmodelkey, ex); + throw new FatalErrorException(new ErrorMessage("errors.valuesetvalidation.fatal", "key=" + tmodelkey + " class=" + clazz + " " + ex.getMessage())); + } catch (InstantiationException ex) { + logger.warn("Unable to process vsv validation for " + tmodelkey, ex); + throw new FatalErrorException(new ErrorMessage("errors.valuesetvalidation.fatal", "key=" + tmodelkey + " class=" + clazz + " " + ex.getMessage())); + } catch (IllegalAccessException ex) { + logger.warn("Unable to process vsv validation for " + tmodelkey, ex); + throw new FatalErrorException(new ErrorMessage("errors.valuesetvalidation.fatal", "key=" + tmodelkey + " class=" + clazz + " " + ex.getMessage())); + } + } + } + + DispositionReport r = new DispositionReport(); + r.getResult().add(new Result()); + long procTime = System.currentTimeMillis() - startTime; + serviceCounter.update(ValueSetValidationQuery.VALIDATE_VALUES, + QueryStatus.SUCCESS, procTime); + + return r; + } + + private List validateValuesBindingTemplate(List items) { + List ret = new ArrayList(); + if (items == null) { + return ret; + } + for (int i = 0; i < items.size(); i++) { + if (items.get(i).getCategoryBag() != null) { + ret.addAll(validateValuesKeyRef(items.get(i).getCategoryBag().getKeyedReference())); + ret.addAll(validateValuesKeyRefGrp(items.get(i).getCategoryBag().getKeyedReferenceGroup())); + } + if (items.get(i).getTModelInstanceDetails() != null) { + + //validateTmodelInstanceDetails(items.get(i).getTModelInstanceDetails().getTModelInstanceInfo(), xpath + "bindingTemplate(" + i + ").tModelInstanceDetails."); + } + } + return ret; + } + + private List validateValuesBusinessEntity(List items) { + List ret = new ArrayList(); + if (items == null) { + return ret; + } + for (int i = 0; i < items.size(); i++) { + if (items.get(i).getCategoryBag() != null) { + ret.addAll(validateValuesKeyRef(items.get(i).getCategoryBag().getKeyedReference())); + ret.addAll(validateValuesKeyRefGrp(items.get(i).getCategoryBag().getKeyedReferenceGroup())); + } + if (items.get(i).getIdentifierBag() != null) { + ret.addAll(validateValuesKeyRef(items.get(i).getIdentifierBag().getKeyedReference())); + } + if (items.get(i).getBusinessServices() != null) { + ret.addAll(validateValuesBusinessService(items.get(i).getBusinessServices().getBusinessService())); + } + } + return ret; + } + + private List validateValuesBusinessService(List items) { + List ret = new ArrayList(); + if (items == null) { + return ret; + } + for (int i = 0; i < items.size(); i++) { + if (items.get(i).getCategoryBag() != null) { + ret.addAll(validateValuesKeyRef(items.get(i).getCategoryBag().getKeyedReference())); + ret.addAll(validateValuesKeyRefGrp(items.get(i).getCategoryBag().getKeyedReferenceGroup())); + } + if (items.get(i).getBindingTemplates() != null) { + ret.addAll(validateValuesBindingTemplate(items.get(i).getBindingTemplates().getBindingTemplate())); + } + } + return ret; + } + + private List validateValuesPublisherAssertion(List items) { + + List ret = new ArrayList(); + if (items == null) { + return ret; + } + for (int i = 0; i < items.size(); i++) { + if (items.get(i).getKeyedReference() != null) { + List temp = new ArrayList(); + temp.add(items.get(i).getKeyedReference()); + ret.addAll(validateValuesKeyRef(temp)); + } + } + return ret; + } + + private List validateValuesTModel(List items) { + List ret = new ArrayList(); + if (items == null) { + return ret; + } + for (int i = 0; i < items.size(); i++) { + if (items.get(i).getCategoryBag() != null) { + ret.addAll(validateValuesKeyRef(items.get(i).getCategoryBag().getKeyedReference())); + ret.addAll(validateValuesKeyRefGrp(items.get(i).getCategoryBag().getKeyedReferenceGroup())); + } + if (items.get(i).getIdentifierBag() != null) { + ret.addAll(validateValuesKeyRef(items.get(i).getIdentifierBag().getKeyedReference())); + } + } + return ret; + } + + private List validateValuesKeyRef(List items) { + List ret = new ArrayList(); + if (items == null) { + return ret; + } + + for (int i = 0; i < items.size(); i++) { + ret.add(items.get(i).getTModelKey()); + } + + return ret; + } + + private List validateValuesKeyRefGrp(List items) { + List ret = new ArrayList(); + if (items == null) { + return ret; + } + for (int i = 0; i < items.size(); i++) { + ret.addAll(validateValuesKeyRef(items.get(i).getKeyedReference())); + } + return ret; + } + + + + public static String convertKeyToClass(String tmodelkey) { + + if (tmodelkey == null) { + return null; + } + if (tmodelkey.length() < 2) { + return null; + } + + String key = new String(new char[]{tmodelkey.charAt(0)}).toUpperCase() + tmodelkey.substring(1).toLowerCase(); + key = key.replaceAll("[^a-zA-Z0-9]", ""); + + String clazz = "org.apache.juddi.validation.vsv." + key; + + return clazz; + + } + + public static List getValidValues(String modelKey) { + try { + ValueSetValidator vsv = (ValueSetValidator) Class.forName(convertKeyToClass(modelKey)).newInstance(); + return vsv.getValidValues(); + } catch (ClassNotFoundException ex) { + } catch (InstantiationException ex) { + } catch (IllegalAccessException ex) { + } + return null; + } + + private boolean containsValidatedKey(Tmodel find, String key) { + if (find.getCategoryBag() != null) { + if (find.getCategoryBag().getKeyedReferences() != null) { + for (int i = 0; i < find.getCategoryBag().getKeyedReferences().size(); i++) { + if (key.equalsIgnoreCase(find.getCategoryBag().getKeyedReferences().get(i).getTmodelKeyRef())) { + return true; + } + } + } + if (find.getCategoryBag().getKeyedReferenceGroups() != null) { + for (int i = 0; i < find.getCategoryBag().getKeyedReferenceGroups().size(); i++) { + for (int k = 0; k < find.getCategoryBag().getKeyedReferenceGroups().get(i).getKeyedReferences().size(); k++) { + if (key.equalsIgnoreCase(find.getCategoryBag().getKeyedReferenceGroups().get(i).getKeyedReferences().get(k).getTmodelKeyRef())) { + return true; + } + } + } + } + } + if (find.getTmodelIdentifiers() != null) { + + for (int i = 0; i < find.getTmodelIdentifiers().size(); i++) { + if (key.equalsIgnoreCase(find.getTmodelIdentifiers().get(i).getTmodelKeyRef())) { + return true; + } + } + } + + return false; + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIv2InquiryImpl.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIv2InquiryImpl.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIv2InquiryImpl.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIv2InquiryImpl.java diff --git a/juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIv2PublishImpl.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIv2PublishImpl.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/api/impl/UDDIv2PublishImpl.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/UDDIv2PublishImpl.java diff --git a/juddi-core/src/main/java/org/apache/juddi/api/impl/XRegisterHelper.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/XRegisterHelper.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/api/impl/XRegisterHelper.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/XRegisterHelper.java index 126c54db5..96d3e362e 100644 --- a/juddi-core/src/main/java/org/apache/juddi/api/impl/XRegisterHelper.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/XRegisterHelper.java @@ -1,177 +1,177 @@ -/* - * Copyright 2001-2009 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.api_v3.Clerk; -import org.apache.juddi.v3.client.config.UDDIClerk; -import org.apache.juddi.v3.client.config.XRegistration; -import org.uddi.api_v3.BindingDetail; -import org.uddi.api_v3.BindingTemplate; -import org.uddi.api_v3.BusinessDetail; -import org.uddi.api_v3.BusinessEntity; -import org.uddi.api_v3.BusinessInfo; -import org.uddi.api_v3.BusinessService; -import org.uddi.api_v3.ServiceDetail; -import org.uddi.api_v3.ServiceInfo; -import org.uddi.sub_v3.SubscriptionResultsList; - -/** - * Used to factor out inquiry functionality as it is used in more than one spot. - * - * @author Kurt T Stam - */ -public class XRegisterHelper { - - private static Log log = LogFactory.getLog(XRegisterHelper.class); - - public static void handle(Clerk fromClerk, Clerk toClerk, SubscriptionResultsList list) { - - UDDIClerk uddiToClerk = new UDDIClerk(toClerk); - UDDIClerk uddiFromClerk = new UDDIClerk(fromClerk); - //SERVICE LIST - if (list.getServiceList()!=null) { - log.info("Subscription result for ServiceList with subscription key=" + list.getSubscription().getSubscriptionKey()); - for (ServiceInfo serviceInfo : list.getServiceList().getServiceInfos().getServiceInfo() ) { - - BusinessEntity existingBusinessEntity = null; - try { - if (existingBusinessEntity==null) { - existingBusinessEntity = uddiToClerk.findBusiness(serviceInfo.getBusinessKey(), toClerk.getNode()); - } - if (existingBusinessEntity!=null) { - log.debug("Found business with key " + existingBusinessEntity.getBusinessKey() + ". No need to add it again"); - } else { - log.info("Business was not found in the destination UDDI " + toClerk.getNode().getName() - + ", going to add it in."); - new XRegistration(serviceInfo.getBusinessKey(), new UDDIClerk(fromClerk), new UDDIClerk(toClerk)).xRegisterBusiness(); - } - new XRegistration(serviceInfo.getServiceKey(), new UDDIClerk(fromClerk), new UDDIClerk(toClerk)).xRegisterServiceAndBindings(); - } catch (Exception e) { - log.error(e.getMessage(),e); - } - } - } - //SERVICE DETAIL - if (list.getServiceDetail()!=null) { - log.info("Subscription result for ServiceDetail with subscription key=" + list.getSubscription().getSubscriptionKey()); - ServiceDetail serviceDetail = list.getServiceDetail(); - if (serviceDetail.isTruncated()) { - log.info("The serviceDetail is truncated, the maxEntries must have been hit. The number of services is " + serviceDetail.getBusinessService().size()); - } - for (BusinessService service : serviceDetail.getBusinessService()) { - BusinessEntity existingBusinessEntity = null; - try { - if (existingBusinessEntity==null) { - existingBusinessEntity = uddiToClerk.findBusiness(service.getBusinessKey(), toClerk.getNode()); - } - if (existingBusinessEntity!=null) { - log.debug("Found business with key " + existingBusinessEntity.getBusinessKey() + ". No need to add it again"); - } else { - log.info("Business was not found in the destination UDDI " + toClerk.getNode().getName() - + ", going to add it in."); - new XRegistration(service.getBusinessKey(), new UDDIClerk(fromClerk), new UDDIClerk(toClerk)).xRegisterBusiness(); - } - new XRegistration(service.getServiceKey(), new UDDIClerk(fromClerk), new UDDIClerk(toClerk)).xRegisterServiceAndBindings(); - } catch (Exception e) { - log.error(e.getMessage(),e); - } - } - } - - //BUSINESS LIST - if (list.getBusinessList()!=null) { - log.info("Subscription result for BusinessList with subscription key=" + list.getSubscription().getSubscriptionKey()); - for (BusinessInfo businessInfo : list.getBusinessList().getBusinessInfos().getBusinessInfo()) { - new XRegistration(businessInfo.getBusinessKey(), new UDDIClerk(fromClerk), new UDDIClerk(toClerk)).xRegisterBusinessAndServices(); - } - } - - //BUSINESS DETAIL - if (list.getBusinessDetail()!=null) { - log.info("Subscription result for BusinessDetail with subscription key=" + list.getSubscription().getSubscriptionKey()); - BusinessDetail businessDetail = list.getBusinessDetail(); - if (businessDetail.isTruncated()) { - log.info("The businessDetail is truncated, the maxEntries must have been hit. The number of businesses is " + businessDetail.getBusinessEntity().size()); - } - for (BusinessEntity businessEntity : businessDetail.getBusinessEntity()) { - new XRegistration(businessEntity.getBusinessKey(), new UDDIClerk(fromClerk), new UDDIClerk(toClerk)).xRegisterBusinessAndServices(); - } - } - - //KEY BAG, NOT IMPLEMENTED - if (list.getKeyBag()!=null) { - log.info("Returning results when a 'brief' format is selected, please do not use 'brief' results when using the XRegistration functionality"); - } - - //BINDING DETAIL - if (list.getBindingDetail()!=null) { - log.info("Subscription result for BindingDetail with subscription key=" + list.getSubscription().getSubscriptionKey()); - BindingDetail bindingDetail = list.getBindingDetail(); - if (bindingDetail.isTruncated()) { - log.info("The bindingDetail is truncated, the maxEntries must have been hit. The number of bindings is " + bindingDetail.getBindingTemplate().size()); - } - for (BindingTemplate bindingTemplate : bindingDetail.getBindingTemplate()) { - try { - //check if the service exist - BusinessService existingToService = uddiToClerk.findService(bindingTemplate.getServiceKey(), toClerk.getNode()); - if (existingToService!=null) { - log.debug("Found service with key " + existingToService.getServiceKey() + ". No need to add it again"); - } else { - BusinessService fromService = uddiFromClerk.findService(bindingTemplate.getServiceKey(), fromClerk.getNode()); - //check if the business exist - BusinessEntity existingBusinessEntity = uddiToClerk.findBusiness(fromService.getBusinessKey(), toClerk.getNode()); - if (existingBusinessEntity!=null) { - log.debug("Found business with key " + existingBusinessEntity.getBusinessKey() + ". No need to add it again"); - } else { - log.info("Business was not found in the destination UDDI " + toClerk.getNode().getName() - + ", going to add it in."); - new XRegistration(fromService.getBusinessKey(), new UDDIClerk(fromClerk), new UDDIClerk(toClerk)).xRegisterBusiness(); - } - log.info("Service was not found in the destination UDDI " + toClerk.getNode().getName() - + ", going to add it in."); - new XRegistration(fromService.getServiceKey(), new UDDIClerk(fromClerk), new UDDIClerk(toClerk)).xRegisterService(); - } - //now the service exists in the toNode and we can add this binding - new XRegistration(bindingTemplate.getBindingKey(), new UDDIClerk(fromClerk), new UDDIClerk(toClerk)).xRegisterServiceBinding(); - } catch (Exception e) { - log.error(e.getMessage(),e); - } - } - } - - //RELATED BUSINESSES - if (list.getRelatedBusinessesList()!=null) { - log.info("Subscription result for RelatedBusinesses with subscription key=" + list.getSubscription().getSubscriptionKey()); - log.info("The jUDDI Listener is not doing anything with this subscription at this moment"); - } - - //ASSERTION STATUS REPORT - if (list.getAssertionStatusReport()!=null) { - log.info("Subscription result for AssertionStatusReport with subscription key=" + list.getSubscription().getSubscriptionKey()); - log.info("The jUDDI Listener is not doing anything with this subscription at this moment"); - } - - //TMODELS - if (list.getTModelList()!=null ){ - log.info("Subscription result for tModelList with subscription key=" + list.getSubscription().getSubscriptionKey()); - log.info("The jUDDI Listener is not doing anything with this subscription at this moment"); - } - } - -} +/* + * Copyright 2001-2009 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.api_v3.Clerk; +import org.apache.juddi.v3.client.config.UDDIClerk; +import org.apache.juddi.v3.client.config.XRegistration; +import org.uddi.api_v3.BindingDetail; +import org.uddi.api_v3.BindingTemplate; +import org.uddi.api_v3.BusinessDetail; +import org.uddi.api_v3.BusinessEntity; +import org.uddi.api_v3.BusinessInfo; +import org.uddi.api_v3.BusinessService; +import org.uddi.api_v3.ServiceDetail; +import org.uddi.api_v3.ServiceInfo; +import org.uddi.sub_v3.SubscriptionResultsList; + +/** + * Used to factor out inquiry functionality as it is used in more than one spot. + * + * @author Kurt T Stam + */ +public class XRegisterHelper { + + private static Log log = LogFactory.getLog(XRegisterHelper.class); + + public static void handle(Clerk fromClerk, Clerk toClerk, SubscriptionResultsList list) { + + UDDIClerk uddiToClerk = new UDDIClerk(toClerk); + UDDIClerk uddiFromClerk = new UDDIClerk(fromClerk); + //SERVICE LIST + if (list.getServiceList()!=null) { + log.info("Subscription result for ServiceList with subscription key=" + list.getSubscription().getSubscriptionKey()); + for (ServiceInfo serviceInfo : list.getServiceList().getServiceInfos().getServiceInfo() ) { + + BusinessEntity existingBusinessEntity = null; + try { + if (existingBusinessEntity==null) { + existingBusinessEntity = uddiToClerk.findBusiness(serviceInfo.getBusinessKey(), toClerk.getNode()); + } + if (existingBusinessEntity!=null) { + log.debug("Found business with key " + existingBusinessEntity.getBusinessKey() + ". No need to add it again"); + } else { + log.info("Business was not found in the destination UDDI " + toClerk.getNode().getName() + + ", going to add it in."); + new XRegistration(serviceInfo.getBusinessKey(), new UDDIClerk(fromClerk), new UDDIClerk(toClerk)).xRegisterBusiness(); + } + new XRegistration(serviceInfo.getServiceKey(), new UDDIClerk(fromClerk), new UDDIClerk(toClerk)).xRegisterServiceAndBindings(); + } catch (Exception e) { + log.error(e.getMessage(),e); + } + } + } + //SERVICE DETAIL + if (list.getServiceDetail()!=null) { + log.info("Subscription result for ServiceDetail with subscription key=" + list.getSubscription().getSubscriptionKey()); + ServiceDetail serviceDetail = list.getServiceDetail(); + if (serviceDetail.isTruncated()) { + log.info("The serviceDetail is truncated, the maxEntries must have been hit. The number of services is " + serviceDetail.getBusinessService().size()); + } + for (BusinessService service : serviceDetail.getBusinessService()) { + BusinessEntity existingBusinessEntity = null; + try { + if (existingBusinessEntity==null) { + existingBusinessEntity = uddiToClerk.findBusiness(service.getBusinessKey(), toClerk.getNode()); + } + if (existingBusinessEntity!=null) { + log.debug("Found business with key " + existingBusinessEntity.getBusinessKey() + ". No need to add it again"); + } else { + log.info("Business was not found in the destination UDDI " + toClerk.getNode().getName() + + ", going to add it in."); + new XRegistration(service.getBusinessKey(), new UDDIClerk(fromClerk), new UDDIClerk(toClerk)).xRegisterBusiness(); + } + new XRegistration(service.getServiceKey(), new UDDIClerk(fromClerk), new UDDIClerk(toClerk)).xRegisterServiceAndBindings(); + } catch (Exception e) { + log.error(e.getMessage(),e); + } + } + } + + //BUSINESS LIST + if (list.getBusinessList()!=null) { + log.info("Subscription result for BusinessList with subscription key=" + list.getSubscription().getSubscriptionKey()); + for (BusinessInfo businessInfo : list.getBusinessList().getBusinessInfos().getBusinessInfo()) { + new XRegistration(businessInfo.getBusinessKey(), new UDDIClerk(fromClerk), new UDDIClerk(toClerk)).xRegisterBusinessAndServices(); + } + } + + //BUSINESS DETAIL + if (list.getBusinessDetail()!=null) { + log.info("Subscription result for BusinessDetail with subscription key=" + list.getSubscription().getSubscriptionKey()); + BusinessDetail businessDetail = list.getBusinessDetail(); + if (businessDetail.isTruncated()) { + log.info("The businessDetail is truncated, the maxEntries must have been hit. The number of businesses is " + businessDetail.getBusinessEntity().size()); + } + for (BusinessEntity businessEntity : businessDetail.getBusinessEntity()) { + new XRegistration(businessEntity.getBusinessKey(), new UDDIClerk(fromClerk), new UDDIClerk(toClerk)).xRegisterBusinessAndServices(); + } + } + + //KEY BAG, NOT IMPLEMENTED + if (list.getKeyBag()!=null) { + log.info("Returning results when a 'brief' format is selected, please do not use 'brief' results when using the XRegistration functionality"); + } + + //BINDING DETAIL + if (list.getBindingDetail()!=null) { + log.info("Subscription result for BindingDetail with subscription key=" + list.getSubscription().getSubscriptionKey()); + BindingDetail bindingDetail = list.getBindingDetail(); + if (bindingDetail.isTruncated()) { + log.info("The bindingDetail is truncated, the maxEntries must have been hit. The number of bindings is " + bindingDetail.getBindingTemplate().size()); + } + for (BindingTemplate bindingTemplate : bindingDetail.getBindingTemplate()) { + try { + //check if the service exist + BusinessService existingToService = uddiToClerk.findService(bindingTemplate.getServiceKey(), toClerk.getNode()); + if (existingToService!=null) { + log.debug("Found service with key " + existingToService.getServiceKey() + ". No need to add it again"); + } else { + BusinessService fromService = uddiFromClerk.findService(bindingTemplate.getServiceKey(), fromClerk.getNode()); + //check if the business exist + BusinessEntity existingBusinessEntity = uddiToClerk.findBusiness(fromService.getBusinessKey(), toClerk.getNode()); + if (existingBusinessEntity!=null) { + log.debug("Found business with key " + existingBusinessEntity.getBusinessKey() + ". No need to add it again"); + } else { + log.info("Business was not found in the destination UDDI " + toClerk.getNode().getName() + + ", going to add it in."); + new XRegistration(fromService.getBusinessKey(), new UDDIClerk(fromClerk), new UDDIClerk(toClerk)).xRegisterBusiness(); + } + log.info("Service was not found in the destination UDDI " + toClerk.getNode().getName() + + ", going to add it in."); + new XRegistration(fromService.getServiceKey(), new UDDIClerk(fromClerk), new UDDIClerk(toClerk)).xRegisterService(); + } + //now the service exists in the toNode and we can add this binding + new XRegistration(bindingTemplate.getBindingKey(), new UDDIClerk(fromClerk), new UDDIClerk(toClerk)).xRegisterServiceBinding(); + } catch (Exception e) { + log.error(e.getMessage(),e); + } + } + } + + //RELATED BUSINESSES + if (list.getRelatedBusinessesList()!=null) { + log.info("Subscription result for RelatedBusinesses with subscription key=" + list.getSubscription().getSubscriptionKey()); + log.info("The jUDDI Listener is not doing anything with this subscription at this moment"); + } + + //ASSERTION STATUS REPORT + if (list.getAssertionStatusReport()!=null) { + log.info("Subscription result for AssertionStatusReport with subscription key=" + list.getSubscription().getSubscriptionKey()); + log.info("The jUDDI Listener is not doing anything with this subscription at this moment"); + } + + //TMODELS + if (list.getTModelList()!=null ){ + log.info("Subscription result for tModelList with subscription key=" + list.getSubscription().getSubscriptionKey()); + log.info("The jUDDI Listener is not doing anything with this subscription at this moment"); + } + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/api/impl/package-info.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/package-info.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/api/impl/package-info.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/impl/package-info.java diff --git a/juddi-core/src/main/java/org/apache/juddi/api/util/CustodyTransferQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/CustodyTransferQuery.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/api/util/CustodyTransferQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/CustodyTransferQuery.java diff --git a/juddi-core/src/main/java/org/apache/juddi/api/util/InquiryQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/InquiryQuery.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/api/util/InquiryQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/InquiryQuery.java diff --git a/juddi-core/src/main/java/org/apache/juddi/api/util/JUDDIQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/JUDDIQuery.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/api/util/JUDDIQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/JUDDIQuery.java diff --git a/juddi-core/src/main/java/org/apache/juddi/api/util/PublicationQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/PublicationQuery.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/api/util/PublicationQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/PublicationQuery.java diff --git a/juddi-core/src/main/java/org/apache/juddi/api/util/QueryStatus.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/QueryStatus.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/api/util/QueryStatus.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/QueryStatus.java diff --git a/juddi-core/src/main/java/org/apache/juddi/api/util/ReplicationQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/ReplicationQuery.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/api/util/ReplicationQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/ReplicationQuery.java diff --git a/juddi-core/src/main/java/org/apache/juddi/api/util/SecurityQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/SecurityQuery.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/api/util/SecurityQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/SecurityQuery.java diff --git a/juddi-core/src/main/java/org/apache/juddi/api/util/SubscriptionListenerQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/SubscriptionListenerQuery.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/api/util/SubscriptionListenerQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/SubscriptionListenerQuery.java diff --git a/juddi-core/src/main/java/org/apache/juddi/api/util/SubscriptionQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/SubscriptionQuery.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/api/util/SubscriptionQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/SubscriptionQuery.java diff --git a/juddi-core/src/main/java/org/apache/juddi/api/util/UDDIQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/UDDIQuery.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/api/util/UDDIQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/UDDIQuery.java diff --git a/juddi-core/src/main/java/org/apache/juddi/api/util/ValueSetCachingQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/ValueSetCachingQuery.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/api/util/ValueSetCachingQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/ValueSetCachingQuery.java diff --git a/juddi-core/src/main/java/org/apache/juddi/api/util/ValueSetValidationQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/ValueSetValidationQuery.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/api/util/ValueSetValidationQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/ValueSetValidationQuery.java diff --git a/juddi-core/src/main/java/org/apache/juddi/api/util/package-info.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/package-info.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/api/util/package-info.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/api/util/package-info.java diff --git a/juddi-core/src/main/java/org/apache/juddi/config/AppConfig.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/config/AppConfig.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/config/AppConfig.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/config/AppConfig.java diff --git a/juddi-core/src/main/java/org/apache/juddi/config/Constants.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/config/Constants.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/config/Constants.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/config/Constants.java index 94cd5e48d..08c63b45e 100644 --- a/juddi-core/src/main/java/org/apache/juddi/config/Constants.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/config/Constants.java @@ -1,30 +1,30 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.config; - -/** - * Contains all the system constants - * - * @author Jeff Faath - */ -public class Constants { - - public static final String GENERAL_KEYWORD_TMODEL = "uddi:uddi.org:categorization:general_keywords"; - public static final String NODE_CATEGORY_TMODEL = "uddi:uddi.org:categorization:nodes"; - public static final String NODE_KEYVALUE = "node"; -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.config; + +/** + * Contains all the system constants + * + * @author Jeff Faath + */ +public class Constants { + + public static final String GENERAL_KEYWORD_TMODEL = "uddi:uddi.org:categorization:general_keywords"; + public static final String NODE_CATEGORY_TMODEL = "uddi:uddi.org:categorization:nodes"; + public static final String NODE_KEYVALUE = "node"; +} diff --git a/juddi-core/src/main/java/org/apache/juddi/config/Install.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/config/Install.java similarity index 98% rename from juddi-core/src/main/java/org/apache/juddi/config/Install.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/config/Install.java index 363f26b86..f0652e1c8 100644 --- a/juddi-core/src/main/java/org/apache/juddi/config/Install.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/config/Install.java @@ -1,838 +1,838 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.config; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.Enumeration; -import java.util.List; -import java.util.StringTokenizer; -import java.util.UUID; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.persistence.EntityManager; -import javax.persistence.EntityTransaction; -import javax.xml.bind.JAXB; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; -import javax.xml.transform.stream.StreamSource; - -import org.apache.commons.configuration.Configuration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.ClassUtil; -import org.apache.juddi.api.impl.AuthenticatedService; -import org.apache.juddi.api.impl.UDDIInquiryImpl; -import org.apache.juddi.api.impl.UDDIPublicationImpl; -import org.apache.juddi.keygen.KeyGenerator; -import org.apache.juddi.mapping.MappingApiToModel; -import org.apache.juddi.mapping.MappingModelToApi; -import org.apache.juddi.model.ReplicationConfiguration; -import org.apache.juddi.model.UddiEntityPublisher; -import org.apache.juddi.replication.ReplicationNotifier; -import org.apache.juddi.v3.client.cryptor.XmlUtils; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.FatalErrorException; -import org.apache.juddi.v3.error.InvalidKeyPassedException; -import org.apache.juddi.v3.error.KeyUnavailableException; -import org.apache.juddi.v3.error.ValueNotAllowedException; -import org.apache.juddi.validation.ValidatePublish; -import org.apache.juddi.validation.ValidateReplication; -import org.apache.juddi.validation.ValidateUDDIKey; -import org.uddi.api_v3.SaveBusiness; -import org.uddi.api_v3.SaveTModel; -import org.uddi.api_v3.TModel; -import org.uddi.repl_v3.Operator; -import org.uddi.v3_service.DispositionReportFaultMessage; - -/** - * This class is called when jUDDI starts up - * - * @author Jeff Faath - * @author Alex O'Ree - * @see org.apache.juddi.servlets.RegistryServlet - */ -public class Install { - - public static final String FILE_BUSINESSENTITY = "_BusinessEntity.xml"; - public static final String FILE_PUBLISHER = "_Publisher.xml"; - public static final String FILE_TMODELKEYGEN = "_tModelKeyGen.xml"; - public static final String FILE_TMODELS = "_tModels.xml"; - - public static final String FILE_PERSISTENCE = "persistence.xml"; - public static final String JUDDI_INSTALL_DATA_DIR = "juddi_install_data/"; - public static final String JUDDI_CUSTOM_INSTALL_DATA_DIR = "juddi_custom_install_data/"; - public static final String FILE_REPLICATION_CONFIG = "_replicationConfiguration.xml"; - public static final Log log = LogFactory.getLog(Install.class); - - protected static void install(Configuration config) throws JAXBException, DispositionReportFaultMessage, IOException, ConfigurationException, XMLStreamException { - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - - UddiEntityPublisher rootPublisher = null; - - try { - tx.begin(); - boolean seedAlways = config.getBoolean("juddi.seed.always", false); - boolean alreadyInstalled = alreadyInstalled(config); - if (!seedAlways && alreadyInstalled) { - throw new FatalErrorException(new ErrorMessage("errors.install.AlreadyInstalled")); - } - - String rootPublisherStr = config.getString(Property.JUDDI_ROOT_PUBLISHER); - String fileRootTModelKeygen = rootPublisherStr + FILE_TMODELKEYGEN; - TModel rootTModelKeyGen = (TModel) buildInstallEntity(fileRootTModelKeygen, "org.uddi.api_v3", config); - String fileRootBusinessEntity = rootPublisherStr + FILE_BUSINESSENTITY; - org.uddi.api_v3.BusinessEntity rootBusinessEntity = (org.uddi.api_v3.BusinessEntity) buildInstallEntity(fileRootBusinessEntity, "org.uddi.api_v3", config); - - String rootPartition = getRootPartition(rootTModelKeyGen); - //JUDDI-645 - String nodeId = config.getString(Property.JUDDI_NODE_ID, getNodeId(rootBusinessEntity.getBusinessKey(), rootPartition)); - //getNodeId(rootBusinessEntity.getBusinessKey(), rootPartition); - String rootbizkey = getNodeId(rootBusinessEntity.getBusinessKey(), rootPartition); - String fileRootPublisher = rootPublisherStr + FILE_PUBLISHER; - String fileReplicationConfig = rootPublisherStr + FILE_REPLICATION_CONFIG; - org.uddi.repl_v3.ReplicationConfiguration replicationCfg = (org.uddi.repl_v3.ReplicationConfiguration) buildInstallEntityAlt(fileReplicationConfig, org.uddi.repl_v3.ReplicationConfiguration.class, config); - if (!alreadyInstalled) { - log.info("Loading the root Publisher from file " + fileRootPublisher); - - rootPublisher = installPublisher(em, fileRootPublisher, config); - installRootPublisherKeyGen(em, rootTModelKeyGen, rootPartition, rootPublisher, nodeId); - rootBusinessEntity.setBusinessKey(rootbizkey); - installBusinessEntity(true, em, rootBusinessEntity, rootPublisher, rootPartition, config, nodeId); - installReplicationConfiguration(em, replicationCfg, config, nodeId); - } else { - log.debug("juddi.seed.always reapplies all seed files except for the root data."); - } - - List juddiPublishers = getPublishers(config); - for (String publisherStr : juddiPublishers) { - String filePublisher = publisherStr + FILE_PUBLISHER; - String fileTModelKeygen = publisherStr + FILE_TMODELKEYGEN; - TModel tModelKeyGen = (TModel) buildInstallEntity(fileTModelKeygen, "org.uddi.api_v3", config); - String fileBusinessEntity = publisherStr + FILE_BUSINESSENTITY; - org.uddi.api_v3.BusinessEntity businessEntity = (org.uddi.api_v3.BusinessEntity) buildInstallEntity(fileBusinessEntity, "org.uddi.api_v3", config); - UddiEntityPublisher publisher = installPublisher(em, filePublisher, config); - if (publisher == null) { - throw new ConfigurationException("File " + filePublisher + " not found."); - } else { - if (tModelKeyGen != null) { - installPublisherKeyGen(em, tModelKeyGen, publisher, nodeId); - } - if (businessEntity != null) { - installBusinessEntity(false, em, businessEntity, publisher, null, config, nodeId); - } - String fileTModels = publisherStr + FILE_TMODELS; - installSaveTModel(em, fileTModels, publisher, nodeId, config); - } - } - - tx.commit(); - } catch (DispositionReportFaultMessage dr) { - log.error(dr.getMessage(), dr); - tx.rollback(); - throw dr; - } catch (JAXBException je) { - log.error(je.getMessage(), je); - tx.rollback(); - throw je; - } catch (IOException ie) { - log.error(ie.getMessage(), ie); - tx.rollback(); - throw ie; - } catch (XMLStreamException ex) { - log.error(ex.getMessage(), ex); - tx.rollback(); - throw ex; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - protected static void uninstall() { - // Close the open emf, open a new one with Persistence.create...(String, Map) and overwrite the property that handles the table - // generation. The persistence.xml file will have to be read in to determine which property - // to overwrite. The property will be specific to the provider. - // Hibernate: ->use "create-drop" or just "drop"? - // OpenJPA: openjpa.jdbc.SynchronizeMappings=buildSchema(SchemaAction='add,deleteTableContents') - // etc...(find more) - // Then close this emf. Question: is the original emf reusable or will closing it cause problems? - - } - - /** - * Checks if there is a database with a root publisher. If it is not - * found an - * - * @param config - * @return true if it finds a database with the root publisher in it. - * @throws ConfigurationException - */ - protected static boolean alreadyInstalled(Configuration config) throws ConfigurationException { - - String rootPublisherStr = config.getString(Property.JUDDI_ROOT_PUBLISHER); - log.info("Checking if jUDDI is seeded by searching for root publisher " + rootPublisherStr); - org.apache.juddi.model.Publisher publisher = null; - int numberOfTries = 0; - while (numberOfTries++ < 100) { - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - publisher = em.find(org.apache.juddi.model.Publisher.class, rootPublisherStr); - tx.commit(); - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - if (publisher != null) { - return true; - } - - if (config.getBoolean(Property.JUDDI_LOAD_INSTALL_DATA, Property.DEFAULT_LOAD_INSTALL_DATA)) { - log.debug("Install data not yet installed."); - return false; - } else { - try { - log.info("Install data not yet installed."); - log.info("Going to sleep and retry..."); - Thread.sleep(1000l); - } catch (InterruptedException e) { - log.error(e.getMessage(), e); - } - } - } - throw new ConfigurationException("Could not load the Root node data. Please check for errors."); - } - - protected static String getRootPartition(TModel rootTModelKeyGen) throws JAXBException, IOException, DispositionReportFaultMessage { - String result = rootTModelKeyGen.getTModelKey().substring(0, rootTModelKeyGen.getTModelKey().lastIndexOf(KeyGenerator.PARTITION_SEPARATOR)); - - if (result == null || result.length() == 0) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.MalformedKey", result)); - } - - // Must validate the root partition. The first component should be a domain key and the any following - // tokens should be a valid KSS. - result = result.trim(); - if (result.endsWith(KeyGenerator.PARTITION_SEPARATOR) || result.startsWith(KeyGenerator.PARTITION_SEPARATOR)) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.MalformedKey", result)); - } - - StringTokenizer tokenizer = new StringTokenizer(result.toLowerCase(), KeyGenerator.PARTITION_SEPARATOR); - for (int count = 0; tokenizer.hasMoreTokens(); count++) { - String nextToken = tokenizer.nextToken(); - - if (count == 0) { - if (!ValidateUDDIKey.isValidDomainKey(nextToken)) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.MalformedKey", result)); - } - } else { - if (!ValidateUDDIKey.isValidKSS(nextToken)) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.MalformedKey", result)); - } - } - } - - return result; - } - - protected static String getNodeId(String userNodeId, String rootPartition) throws DispositionReportFaultMessage { - - String result = userNodeId; - if (result == null || result.length() == 0) { - result = rootPartition + KeyGenerator.PARTITION_SEPARATOR + UUID.randomUUID(); - } else { - ValidateUDDIKey.validateUDDIv3Key(result); - String keyPartition = result.substring(0, result.lastIndexOf(KeyGenerator.PARTITION_SEPARATOR)); - if (!rootPartition.equalsIgnoreCase(keyPartition)) { - throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", userNodeId)); - } - } - return result; - } - - private static String installBusinessEntity(boolean isRoot, EntityManager em, org.uddi.api_v3.BusinessEntity rootBusinessEntity, - UddiEntityPublisher rootPublisher, String rootPartition, Configuration config, String nodeId) - throws JAXBException, DispositionReportFaultMessage, IOException { - - if (isRoot) { - validateRootBusinessEntity(rootBusinessEntity, rootPublisher, rootPartition, config); - } - - org.apache.juddi.model.BusinessEntity modelBusinessEntity = new org.apache.juddi.model.BusinessEntity(); - MappingApiToModel.mapBusinessEntity(rootBusinessEntity, modelBusinessEntity); - - modelBusinessEntity.setAuthorizedName(rootPublisher.getAuthorizedName()); - modelBusinessEntity.setNodeId(nodeId); - Date now = new Date(); - modelBusinessEntity.setCreated(now); - modelBusinessEntity.setModified(now); - modelBusinessEntity.setModifiedIncludingChildren(now); - //JUDDI-645 - //modelBusinessEntity.setNodeId(modelBusinessEntity.getEntityKey()); - modelBusinessEntity.setNodeId(config.getString(Property.JUDDI_NODE_ID, modelBusinessEntity.getEntityKey())); - - for (org.apache.juddi.model.BusinessService service : modelBusinessEntity.getBusinessServices()) { - service.setAuthorizedName(rootPublisher.getAuthorizedName()); - service.setNodeId(modelBusinessEntity.getNodeId()); - service.setCreated(now); - service.setModified(now); - service.setModifiedIncludingChildren(now); - //JUDDI-645 - //service.setNodeId(config.getString(Property.JUDDI_NODE_ID,modelBusinessEntity.getEntityKey())); - //service.setNodeId(modelBusinessEntity.getEntityKey()); - - for (org.apache.juddi.model.BindingTemplate binding : service.getBindingTemplates()) { - binding.setAuthorizedName(rootPublisher.getAuthorizedName()); - binding.setNodeId(nodeId); - binding.setCreated(now); - binding.setModified(now); - binding.setModifiedIncludingChildren(now); - //binding.setNodeId(modelBusinessEntity.getEntityKey()); - //binding.setNodeId(config.getString(Property.JUDDI_NODE_ID,modelBusinessEntity.getEntityKey())); - //JUDDI-645 - - } - } - - em.persist(modelBusinessEntity); - SaveBusiness sb = new SaveBusiness(); - sb.getBusinessEntity().add(rootBusinessEntity); - ReplicationNotifier.enqueue(UDDIPublicationImpl.getChangeRecord(modelBusinessEntity, rootBusinessEntity, modelBusinessEntity.getNodeId())); - - return modelBusinessEntity.getEntityKey(); - - } - - // A watered down version of ValidatePublish's validateBusinessEntity, designed for the specific condition that this is run upon the initial - // jUDDI install. - private static void validateRootBusinessEntity(org.uddi.api_v3.BusinessEntity businessEntity, UddiEntityPublisher rootPublisher, - String rootPartition, Configuration config) - throws DispositionReportFaultMessage { - - // A supplied businessService can't be null - if (businessEntity == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.businessentity.NullInput")); - } - - // The business key should already be set to the previously calculated and validated nodeId. This validation is unnecessary but kept for - // symmetry with the other entity validations. - String entityKey = businessEntity.getBusinessKey(); - if (entityKey == null || entityKey.length() == 0) { - entityKey = rootPartition + KeyGenerator.PARTITION_SEPARATOR + UUID.randomUUID(); - businessEntity.setBusinessKey(entityKey); - } else { - // Per section 4.4: keys must be case-folded - entityKey = entityKey.toLowerCase(); - businessEntity.setBusinessKey(entityKey); - - ValidateUDDIKey.validateUDDIv3Key(entityKey); - String keyPartition = entityKey.substring(0, entityKey.lastIndexOf(KeyGenerator.PARTITION_SEPARATOR)); - if (!rootPartition.equalsIgnoreCase(keyPartition)) { - throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", entityKey)); - } - } - - ValidatePublish validatePublish = new ValidatePublish(rootPublisher, config.getString(Property.JUDDI_NODE_ID)); - - validatePublish.validateNames(businessEntity.getName()); - validatePublish.validateDiscoveryUrls(businessEntity.getDiscoveryURLs()); - validatePublish.validateContacts(businessEntity.getContacts(), config); - validatePublish.validateCategoryBag(businessEntity.getCategoryBag(), config, true); - validatePublish.validateIdentifierBag(businessEntity.getIdentifierBag(), config, true); - - org.uddi.api_v3.BusinessServices businessServices = businessEntity.getBusinessServices(); - if (businessServices != null) { - List businessServiceList = businessServices.getBusinessService(); - if (businessServiceList == null || businessServiceList.size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.businessservices.NoInput")); - } - - for (org.uddi.api_v3.BusinessService businessService : businessServiceList) { - validateRootBusinessService(businessService, businessEntity, rootPublisher, rootPartition, config); - } - } - - } - - // A watered down version of ValidatePublish's validateBusinessService, designed for the specific condition that this is run upon the initial - // jUDDI install. - private static void validateRootBusinessService(org.uddi.api_v3.BusinessService businessService, org.uddi.api_v3.BusinessEntity parent, - UddiEntityPublisher rootPublisher, String rootPartition, Configuration config) - throws DispositionReportFaultMessage { - - // A supplied businessService can't be null - if (businessService == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.businessservice.NullInput")); - } - - // A business key doesn't have to be provided, but if it is, it should match the parent business's key - String parentKey = businessService.getBusinessKey(); - if (parentKey != null && parentKey.length() > 0) { - if (!parentKey.equalsIgnoreCase(parent.getBusinessKey())) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ParentBusinessNotFound", parentKey + " " + businessService.getBusinessKey() + " " + businessService.getBusinessKey().length() + " " + parentKey.length())); - } - } - - // Retrieve the service's passed key - String entityKey = businessService.getServiceKey(); - if (entityKey == null || entityKey.length() == 0) { - entityKey = rootPartition + KeyGenerator.PARTITION_SEPARATOR + UUID.randomUUID(); - businessService.setServiceKey(entityKey); - } else { - // Per section 4.4: keys must be case-folded - entityKey = entityKey.toLowerCase(); - businessService.setServiceKey(entityKey); - - ValidateUDDIKey.validateUDDIv3Key(entityKey); - String keyPartition = entityKey.substring(0, entityKey.lastIndexOf(KeyGenerator.PARTITION_SEPARATOR)); - if (!rootPartition.equalsIgnoreCase(keyPartition)) { - throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", entityKey)); - } - } - - ValidatePublish validatePublish = new ValidatePublish(rootPublisher, config.getString(Property.JUDDI_NODE_ID)); - - validatePublish.validateNames(businessService.getName()); - validatePublish.validateCategoryBag(businessService.getCategoryBag(), config, true); - - org.uddi.api_v3.BindingTemplates bindingTemplates = businessService.getBindingTemplates(); - if (bindingTemplates != null) { - List bindingTemplateList = bindingTemplates.getBindingTemplate(); - if (bindingTemplateList == null || bindingTemplateList.size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.bindingtemplates.NoInput")); - } - - for (org.uddi.api_v3.BindingTemplate bindingTemplate : bindingTemplateList) { - validateRootBindingTemplate(bindingTemplate, businessService, rootPublisher, rootPartition, config); - } - } - } - - // A watered down version of ValidatePublish's validatBindingTemplate, designed for the specific condition that this is run upon the initial - // jUDDI install. - private static void validateRootBindingTemplate(org.uddi.api_v3.BindingTemplate bindingTemplate, org.uddi.api_v3.BusinessService parent, - UddiEntityPublisher rootPublisher, String rootPartition, Configuration config) - throws DispositionReportFaultMessage { - - // A supplied businessService can't be null - if (bindingTemplate == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.bindingtemplate.NullInput")); - } - - // A service key doesn't have to be provided, but if it is, it should match the parent service's key - String parentKey = bindingTemplate.getServiceKey(); - if (parentKey != null && parentKey.length() > 0) { - if (!parentKey.equalsIgnoreCase(parent.getServiceKey())) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ParentServiceNotFound", parentKey)); - } - } - - // Retrieve the service's passed key - String entityKey = bindingTemplate.getBindingKey(); - if (entityKey == null || entityKey.length() == 0) { - entityKey = rootPartition + KeyGenerator.PARTITION_SEPARATOR + UUID.randomUUID(); - bindingTemplate.setBindingKey(entityKey); - } else { - // Per section 4.4: keys must be case-folded - entityKey = entityKey.toLowerCase(); - bindingTemplate.setBindingKey(entityKey); - - ValidateUDDIKey.validateUDDIv3Key(entityKey); - String keyPartition = entityKey.substring(0, entityKey.lastIndexOf(KeyGenerator.PARTITION_SEPARATOR)); - if (!rootPartition.equalsIgnoreCase(keyPartition)) { - throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", entityKey)); - } - } - - ValidatePublish validatePublish = new ValidatePublish(rootPublisher, config.getString(Property.JUDDI_NODE_ID)); - - validatePublish.validateCategoryBag(bindingTemplate.getCategoryBag(), config, true); - validatePublish.validateTModelInstanceDetails(bindingTemplate.getTModelInstanceDetails(), config, true); - - } - - private static void installTModels(EntityManager em, List apiTModelList, UddiEntityPublisher publisher, String nodeId) throws DispositionReportFaultMessage { - if (apiTModelList != null) { - for (org.uddi.api_v3.TModel apiTModel : apiTModelList) { - String tModelKey = apiTModel.getTModelKey(); - - if (tModelKey.toUpperCase().endsWith(KeyGenerator.KEYGENERATOR_SUFFIX.toUpperCase())) { - installPublisherKeyGen(em, apiTModel, publisher, nodeId); - } else { - org.apache.juddi.model.Tmodel modelTModel = new org.apache.juddi.model.Tmodel(); - apiTModel.setTModelKey(apiTModel.getTModelKey().toLowerCase()); - - MappingApiToModel.mapTModel(apiTModel, modelTModel); - - modelTModel.setAuthorizedName(publisher.getAuthorizedName()); - - Date now = new Date(); - modelTModel.setCreated(now); - modelTModel.setModified(now); - modelTModel.setModifiedIncludingChildren(now); - modelTModel.setNodeId(nodeId); - - em.persist(modelTModel); - - SaveTModel stm = new SaveTModel(); - stm.getTModel().add(apiTModel); - ReplicationNotifier.enqueue(UDDIPublicationImpl.getChangeRecord(modelTModel, apiTModel, nodeId)); - } - - } - } - - } - - private static void installRootPublisherKeyGen(EntityManager em, TModel rootTModelKeyGen, String rootPartition, UddiEntityPublisher publisher, String nodeId) - throws DispositionReportFaultMessage { - - rootTModelKeyGen.setTModelKey(rootPartition + KeyGenerator.PARTITION_SEPARATOR + KeyGenerator.KEYGENERATOR_SUFFIX); - - installPublisherKeyGen(em, rootTModelKeyGen, publisher, nodeId); - } - - private static void installPublisherKeyGen(EntityManager em, TModel apiTModel, UddiEntityPublisher publisher, String nodeId) throws DispositionReportFaultMessage { - - org.apache.juddi.model.Tmodel modelTModel = new org.apache.juddi.model.Tmodel(); - MappingApiToModel.mapTModel(apiTModel, modelTModel); - - modelTModel.setAuthorizedName(publisher.getAuthorizedName()); - - Date now = new Date(); - modelTModel.setCreated(now); - modelTModel.setModified(now); - modelTModel.setModifiedIncludingChildren(now); - modelTModel.setNodeId(nodeId); - - em.persist(modelTModel); - - } - - private static List getPublishers(Configuration config) throws ConfigurationException { - List publishers = new ArrayList(); - String basePath = JUDDI_CUSTOM_INSTALL_DATA_DIR; - URL url = ClassUtil.getResource(JUDDI_CUSTOM_INSTALL_DATA_DIR, Install.class); - if (url == null) { - url = ClassUtil.getResource(JUDDI_INSTALL_DATA_DIR, Install.class); - basePath = JUDDI_INSTALL_DATA_DIR; - } - - String path = null; - - try { - path = url.toURI().getSchemeSpecificPart(); - } catch (URISyntaxException e) { - throw new ConfigurationException(e); - } - - File dir = new File(path); - String rootPublisherStr = config.getString(Property.JUDDI_ROOT_PUBLISHER); - if (dir.exists()) { - log.debug("Discovering the Publisher XML data files in directory: " + path); - File[] files = dir.listFiles(new PublisherFileFilter()); - if (files!=null) - for (File f : files) { - String publisher = f.getName().substring(0, f.getName().indexOf(FILE_PUBLISHER)); - if (!rootPublisherStr.equalsIgnoreCase(publisher)) { - publishers.add(publisher); - } - } - } else { - String[] paths = {}; - Enumeration en = null; - JarFile jf = null; - try { - - if (path.indexOf("!") > 0) { - paths = path.split("!"); - jf = new JarFile(new File(new URI(paths[0]))); - en = jf.entries(); - } else { - // Handle Windows / jboss-5.1.0 case - if (path.indexOf(".jar") > 0) { - paths = path.split(".jar"); - paths[0] = paths[0] + ".jar"; - File temp = new File(paths[0]); - if (temp.exists()) { - jf = new JarFile(temp); - en = jf.entries(); - } - } - } - if (paths.length > 0) { - log.debug("Discovering the Publisher XML data files in jar: " + paths[0]); - while (en != null && en.hasMoreElements()) { - String name = en.nextElement().getName(); - if (name.endsWith(FILE_PUBLISHER)) { - log.debug("Found publisher file=" + name); - String publisher = name.substring(basePath.length(), name.indexOf(FILE_PUBLISHER)); - if (!rootPublisherStr.equalsIgnoreCase(publisher)) { - publishers.add(publisher); - } - } - } - } else { - log.info("No custom configuration files where found in " + path); - } - if (jf != null) { - jf.close(); - } - - } catch (IOException e) { - throw new ConfigurationException(e); - } catch (URISyntaxException e) { - throw new ConfigurationException(e); - } - } - return publishers; - } - - private static Object buildInstallEntityAlt(final String fileName, Class outputtype, Configuration config) throws JAXBException, IOException, ConfigurationException { - InputStream resourceStream = null; - - // First try the custom install directory - URL url = ClassUtil.getResource(JUDDI_CUSTOM_INSTALL_DATA_DIR + fileName, Install.class); - if (url != null) { - resourceStream = url.openStream(); - } - - // If the custom install directory doesn't exist, then use the standard install directory where the resource is guaranteed to exist. - if (resourceStream == null) { - url = ClassUtil.getResource(JUDDI_INSTALL_DATA_DIR + fileName, Install.class); - if (url != null) { - resourceStream = url.openStream(); - } - // If file still does not exist then return null; - if (url == null || resourceStream == null) { - if (fileName.endsWith(FILE_PUBLISHER)) { - throw new ConfigurationException("Could not locate " + JUDDI_INSTALL_DATA_DIR + fileName); - } else { - log.debug("Could not locate: " + url); - } - return null; - } - } - log.info("Loading the content of file: " + url); - StringBuilder xml = new StringBuilder(); - byte[] b = new byte[4096]; - for (int n; (n = resourceStream.read(b)) != -1;) { - xml.append(new String(b, 0, n, AuthenticatedService.UTF8)); - } - log.debug("inserting: " + xml.toString()); - StringReader reader = new StringReader(xml.toString()); - - Object obj= XmlUtils.unmarshal(reader, outputtype); - reader.close(); - return obj; - } - - private static Object buildInstallEntity(final String fileName, String packageName, Configuration config) throws JAXBException, IOException, ConfigurationException, XMLStreamException { - InputStream resourceStream = null; - - // First try the custom install directory - URL url = ClassUtil.getResource(JUDDI_CUSTOM_INSTALL_DATA_DIR + fileName, Install.class); - if (url != null) { - resourceStream = url.openStream(); - } - - // If the custom install directory doesn't exist, then use the standard install directory where the resource is guaranteed to exist. - if (resourceStream == null) { - url = ClassUtil.getResource(JUDDI_INSTALL_DATA_DIR + fileName, Install.class); - if (url != null) { - resourceStream = url.openStream(); - } - // If file still does not exist then return null; - if (url == null || resourceStream == null) { - if (fileName.endsWith(FILE_PUBLISHER)) { - throw new ConfigurationException("Could not locate " + JUDDI_INSTALL_DATA_DIR + fileName); - } else { - log.debug("Could not locate: " + url); - } - return null; - } - } - log.info("Loading the content of file: " + url); - StringBuilder xml = new StringBuilder(); - byte[] b = new byte[4096]; - for (int n; (n = resourceStream.read(b)) != -1;) { - xml.append(new String(b, 0, n, AuthenticatedService.UTF8)); - } - log.debug("inserting: " + xml.toString()); - StringReader reader = new StringReader(xml.toString()); - - Object obj= XmlUtils.unmarshal(reader, packageName); - reader.close(); - return obj; - } - - /** - * Public convenience method that allows one to retrieve the node - * business entity (perhaps to display during an install process, or - * even to initiate the install process). - * - * @param businessKey - * @return BusinessEntity Object - * @throws DispositionReportFaultMessage - */ - public static org.uddi.api_v3.BusinessEntity getNodeBusinessEntity(String businessKey) throws DispositionReportFaultMessage { - UDDIInquiryImpl inquiry = new UDDIInquiryImpl(); - - org.uddi.api_v3.GetBusinessDetail gbd = new org.uddi.api_v3.GetBusinessDetail(); - gbd.getBusinessKey().add(businessKey); - - org.uddi.api_v3.BusinessDetail bd = inquiry.getBusinessDetail(gbd); - if (bd != null) { - List beList = bd.getBusinessEntity(); - if (beList != null && beList.size() > 0) { - return beList.get(0); - } - } - - return new org.uddi.api_v3.BusinessEntity(); - } - - /** - * Public convenience method that allows one to install additional - * TModels via a SaveTModel structure. - * - * @param em - the entity manager to a juddi model - * @param fileName - name of SaveTModel xml file - * @param publisher - the publisher structure that owns the tModels - * @param nodeId - the node id of the custodial node - * @throws JAXBException - * @throws DispositionReportFaultMessage - * @throws IOException - * @throws ConfigurationException - */ - public static void installSaveTModel(EntityManager em, String fileName, UddiEntityPublisher publisher, String nodeId, Configuration config) - throws JAXBException, DispositionReportFaultMessage, IOException, ConfigurationException, XMLStreamException { - - SaveTModel apiSaveTModel = (SaveTModel) buildInstallEntity(fileName, "org.uddi.api_v3", config); - if (apiSaveTModel != null) { - installTModels(em, apiSaveTModel.getTModel(), publisher, nodeId); - } - } - - /** - * Public convenience method that allows one to install additional - * Publishers via a Publisher structure. - * - * @param em - the entity manager to the juddi model - * @param fileName - name of Publisher xml file - * @return UddiEntityPublisher object, can be any UDDIEntity - * @throws JAXBException - * @throws DispositionReportFaultMessage - * @throws IOException - * @throws ConfigurationException - */ - public static UddiEntityPublisher installPublisher(EntityManager em, String fileName, Configuration config) - throws JAXBException, DispositionReportFaultMessage, IOException, ConfigurationException, XMLStreamException { - - org.apache.juddi.api_v3.Publisher apiPub = (org.apache.juddi.api_v3.Publisher) buildInstallEntity(fileName, "org.apache.juddi.api_v3", config); - if (apiPub == null) { - return null; - } - org.apache.juddi.model.Publisher modelPub = new org.apache.juddi.model.Publisher(); - MappingApiToModel.mapPublisher(apiPub, modelPub); - em.persist(modelPub); - return modelPub; - } - - public static org.uddi.repl_v3.ReplicationConfiguration applyReplicationTokenChanges(org.uddi.repl_v3.ReplicationConfiguration replicationCfg, Configuration config, String thisnode) { - log.info("replacing tokens on repl config"); - if (replicationCfg == null) { - return null; - } - //apply any token replacements - for (Operator op : replicationCfg.getOperator()) { - op.setOperatorNodeID(op.getOperatorNodeID().replace("${juddi.nodeId}", thisnode)); - op.setSoapReplicationURL(op.getSoapReplicationURL().replace("${juddi.server.baseurlsecure}", config.getString("juddi.server.baseurlsecure"))); - op.setSoapReplicationURL(op.getSoapReplicationURL().replace("${juddi.server.baseurl}", config.getString("juddi.server.baseurl"))); - } - if (replicationCfg.getCommunicationGraph() != null) { - for (int i = 0; i < replicationCfg.getCommunicationGraph().getNode().size(); i++) { - replicationCfg.getCommunicationGraph().getNode().set(i, replicationCfg.getCommunicationGraph().getNode().get(i).replace("${juddi.nodeId}", thisnode)); - - } - for (int i = 0; i < replicationCfg.getCommunicationGraph().getEdge().size(); i++) { - replicationCfg.getCommunicationGraph().getEdge().get(i).setMessageSender(replicationCfg.getCommunicationGraph().getEdge().get(i).getMessageSender().replace("${juddi.nodeId}", thisnode)); - replicationCfg.getCommunicationGraph().getEdge().get(i).setMessageReceiver(replicationCfg.getCommunicationGraph().getEdge().get(i).getMessageReceiver().replace("${juddi.nodeId}", thisnode)); - for (int k = 0; k < replicationCfg.getCommunicationGraph().getEdge().get(i).getMessageReceiverAlternate().size(); k++) { - replicationCfg.getCommunicationGraph().getEdge().get(i).getMessageReceiverAlternate().set(k, replicationCfg.getCommunicationGraph().getEdge().get(i).getMessageReceiverAlternate().get(k).replace("${juddi.nodeId}", thisnode)); - } - } - } - - for (Operator op : replicationCfg.getOperator()) { - op.setOperatorNodeID(op.getOperatorNodeID().replace("${juddi.nodeId}", thisnode)); - } - log.info("replacing tokens on repl config, done"); - return replicationCfg; - } - - private static void installReplicationConfiguration(EntityManager em, org.uddi.repl_v3.ReplicationConfiguration replicationCfg, Configuration config, String thisnode) throws DispositionReportFaultMessage, ConfigurationException { - replicationCfg = applyReplicationTokenChanges(replicationCfg, config, thisnode); - new ValidateReplication(null, thisnode).validateSetReplicationNodes(replicationCfg, em, thisnode, config); - - SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddkkmmZ"); - replicationCfg.setTimeOfConfigurationUpdate(sdf.format(new Date())); - - org.apache.juddi.model.ReplicationConfiguration model = new ReplicationConfiguration(); - - MappingApiToModel.mapReplicationConfiguration(replicationCfg, model, em); - - model.setSerialNumber(System.currentTimeMillis()); - - org.apache.juddi.model.ReplicationConfiguration oldstuff = null; - // logger.info(publisher.getAuthorizedName() + " is setting the replication config from " + getRequestorsIPAddress());// + " " + sw.toString()); - try { - oldstuff = (ReplicationConfiguration) em.createQuery("select c FROM ReplicationConfiguration c order by c.serialNumber desc").getSingleResult(); - } catch (Exception ex) { - } - if (oldstuff != null) { - em.remove(oldstuff); - } - em.persist(model); - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.config; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringReader; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.Enumeration; +import java.util.List; +import java.util.StringTokenizer; +import java.util.UUID; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.xml.bind.JAXB; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.transform.stream.StreamSource; + +import org.apache.commons.configuration.Configuration; +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.ClassUtil; +import org.apache.juddi.api.impl.AuthenticatedService; +import org.apache.juddi.api.impl.UDDIInquiryImpl; +import org.apache.juddi.api.impl.UDDIPublicationImpl; +import org.apache.juddi.keygen.KeyGenerator; +import org.apache.juddi.mapping.MappingApiToModel; +import org.apache.juddi.mapping.MappingModelToApi; +import org.apache.juddi.model.ReplicationConfiguration; +import org.apache.juddi.model.UddiEntityPublisher; +import org.apache.juddi.replication.ReplicationNotifier; +import org.apache.juddi.v3.client.cryptor.XmlUtils; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.FatalErrorException; +import org.apache.juddi.v3.error.InvalidKeyPassedException; +import org.apache.juddi.v3.error.KeyUnavailableException; +import org.apache.juddi.v3.error.ValueNotAllowedException; +import org.apache.juddi.validation.ValidatePublish; +import org.apache.juddi.validation.ValidateReplication; +import org.apache.juddi.validation.ValidateUDDIKey; +import org.uddi.api_v3.SaveBusiness; +import org.uddi.api_v3.SaveTModel; +import org.uddi.api_v3.TModel; +import org.uddi.repl_v3.Operator; +import org.uddi.v3_service.DispositionReportFaultMessage; + +/** + * This class is called when jUDDI starts up + * + * @author Jeff Faath + * @author Alex O'Ree + * @see org.apache.juddi.servlets.RegistryServlet + */ +public class Install { + + public static final String FILE_BUSINESSENTITY = "_BusinessEntity.xml"; + public static final String FILE_PUBLISHER = "_Publisher.xml"; + public static final String FILE_TMODELKEYGEN = "_tModelKeyGen.xml"; + public static final String FILE_TMODELS = "_tModels.xml"; + + public static final String FILE_PERSISTENCE = "persistence.xml"; + public static final String JUDDI_INSTALL_DATA_DIR = "juddi_install_data/"; + public static final String JUDDI_CUSTOM_INSTALL_DATA_DIR = "juddi_custom_install_data/"; + public static final String FILE_REPLICATION_CONFIG = "_replicationConfiguration.xml"; + public static final Log log = LogFactory.getLog(Install.class); + + protected static void install(Configuration config) throws JAXBException, DispositionReportFaultMessage, IOException, ConfigurationException, XMLStreamException { + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + + UddiEntityPublisher rootPublisher = null; + + try { + tx.begin(); + boolean seedAlways = config.getBoolean("juddi.seed.always", false); + boolean alreadyInstalled = alreadyInstalled(config); + if (!seedAlways && alreadyInstalled) { + throw new FatalErrorException(new ErrorMessage("errors.install.AlreadyInstalled")); + } + + String rootPublisherStr = config.getString(Property.JUDDI_ROOT_PUBLISHER); + String fileRootTModelKeygen = rootPublisherStr + FILE_TMODELKEYGEN; + TModel rootTModelKeyGen = (TModel) buildInstallEntity(fileRootTModelKeygen, "org.uddi.api_v3", config); + String fileRootBusinessEntity = rootPublisherStr + FILE_BUSINESSENTITY; + org.uddi.api_v3.BusinessEntity rootBusinessEntity = (org.uddi.api_v3.BusinessEntity) buildInstallEntity(fileRootBusinessEntity, "org.uddi.api_v3", config); + + String rootPartition = getRootPartition(rootTModelKeyGen); + //JUDDI-645 + String nodeId = config.getString(Property.JUDDI_NODE_ID, getNodeId(rootBusinessEntity.getBusinessKey(), rootPartition)); + //getNodeId(rootBusinessEntity.getBusinessKey(), rootPartition); + String rootbizkey = getNodeId(rootBusinessEntity.getBusinessKey(), rootPartition); + String fileRootPublisher = rootPublisherStr + FILE_PUBLISHER; + String fileReplicationConfig = rootPublisherStr + FILE_REPLICATION_CONFIG; + org.uddi.repl_v3.ReplicationConfiguration replicationCfg = (org.uddi.repl_v3.ReplicationConfiguration) buildInstallEntityAlt(fileReplicationConfig, org.uddi.repl_v3.ReplicationConfiguration.class, config); + if (!alreadyInstalled) { + log.info("Loading the root Publisher from file " + fileRootPublisher); + + rootPublisher = installPublisher(em, fileRootPublisher, config); + installRootPublisherKeyGen(em, rootTModelKeyGen, rootPartition, rootPublisher, nodeId); + rootBusinessEntity.setBusinessKey(rootbizkey); + installBusinessEntity(true, em, rootBusinessEntity, rootPublisher, rootPartition, config, nodeId); + installReplicationConfiguration(em, replicationCfg, config, nodeId); + } else { + log.debug("juddi.seed.always reapplies all seed files except for the root data."); + } + + List juddiPublishers = getPublishers(config); + for (String publisherStr : juddiPublishers) { + String filePublisher = publisherStr + FILE_PUBLISHER; + String fileTModelKeygen = publisherStr + FILE_TMODELKEYGEN; + TModel tModelKeyGen = (TModel) buildInstallEntity(fileTModelKeygen, "org.uddi.api_v3", config); + String fileBusinessEntity = publisherStr + FILE_BUSINESSENTITY; + org.uddi.api_v3.BusinessEntity businessEntity = (org.uddi.api_v3.BusinessEntity) buildInstallEntity(fileBusinessEntity, "org.uddi.api_v3", config); + UddiEntityPublisher publisher = installPublisher(em, filePublisher, config); + if (publisher == null) { + throw new ConfigurationException("File " + filePublisher + " not found."); + } else { + if (tModelKeyGen != null) { + installPublisherKeyGen(em, tModelKeyGen, publisher, nodeId); + } + if (businessEntity != null) { + installBusinessEntity(false, em, businessEntity, publisher, null, config, nodeId); + } + String fileTModels = publisherStr + FILE_TMODELS; + installSaveTModel(em, fileTModels, publisher, nodeId, config); + } + } + + tx.commit(); + } catch (DispositionReportFaultMessage dr) { + log.error(dr.getMessage(), dr); + tx.rollback(); + throw dr; + } catch (JAXBException je) { + log.error(je.getMessage(), je); + tx.rollback(); + throw je; + } catch (IOException ie) { + log.error(ie.getMessage(), ie); + tx.rollback(); + throw ie; + } catch (XMLStreamException ex) { + log.error(ex.getMessage(), ex); + tx.rollback(); + throw ex; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + protected static void uninstall() { + // Close the open emf, open a new one with Persistence.create...(String, Map) and overwrite the property that handles the table + // generation. The persistence.xml file will have to be read in to determine which property + // to overwrite. The property will be specific to the provider. + // Hibernate: ->use "create-drop" or just "drop"? + // OpenJPA: openjpa.jdbc.SynchronizeMappings=buildSchema(SchemaAction='add,deleteTableContents') + // etc...(find more) + // Then close this emf. Question: is the original emf reusable or will closing it cause problems? + + } + + /** + * Checks if there is a database with a root publisher. If it is not + * found an + * + * @param config + * @return true if it finds a database with the root publisher in it. + * @throws ConfigurationException + */ + protected static boolean alreadyInstalled(Configuration config) throws ConfigurationException { + + String rootPublisherStr = config.getString(Property.JUDDI_ROOT_PUBLISHER); + log.info("Checking if jUDDI is seeded by searching for root publisher " + rootPublisherStr); + org.apache.juddi.model.Publisher publisher = null; + int numberOfTries = 0; + while (numberOfTries++ < 100) { + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + publisher = em.find(org.apache.juddi.model.Publisher.class, rootPublisherStr); + tx.commit(); + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + if (publisher != null) { + return true; + } + + if (config.getBoolean(Property.JUDDI_LOAD_INSTALL_DATA, Property.DEFAULT_LOAD_INSTALL_DATA)) { + log.debug("Install data not yet installed."); + return false; + } else { + try { + log.info("Install data not yet installed."); + log.info("Going to sleep and retry..."); + Thread.sleep(1000l); + } catch (InterruptedException e) { + log.error(e.getMessage(), e); + } + } + } + throw new ConfigurationException("Could not load the Root node data. Please check for errors."); + } + + protected static String getRootPartition(TModel rootTModelKeyGen) throws JAXBException, IOException, DispositionReportFaultMessage { + String result = rootTModelKeyGen.getTModelKey().substring(0, rootTModelKeyGen.getTModelKey().lastIndexOf(KeyGenerator.PARTITION_SEPARATOR)); + + if (result == null || result.length() == 0) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.MalformedKey", result)); + } + + // Must validate the root partition. The first component should be a domain key and the any following + // tokens should be a valid KSS. + result = result.trim(); + if (result.endsWith(KeyGenerator.PARTITION_SEPARATOR) || result.startsWith(KeyGenerator.PARTITION_SEPARATOR)) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.MalformedKey", result)); + } + + StringTokenizer tokenizer = new StringTokenizer(result.toLowerCase(), KeyGenerator.PARTITION_SEPARATOR); + for (int count = 0; tokenizer.hasMoreTokens(); count++) { + String nextToken = tokenizer.nextToken(); + + if (count == 0) { + if (!ValidateUDDIKey.isValidDomainKey(nextToken)) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.MalformedKey", result)); + } + } else { + if (!ValidateUDDIKey.isValidKSS(nextToken)) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.MalformedKey", result)); + } + } + } + + return result; + } + + protected static String getNodeId(String userNodeId, String rootPartition) throws DispositionReportFaultMessage { + + String result = userNodeId; + if (result == null || result.length() == 0) { + result = rootPartition + KeyGenerator.PARTITION_SEPARATOR + UUID.randomUUID(); + } else { + ValidateUDDIKey.validateUDDIv3Key(result); + String keyPartition = result.substring(0, result.lastIndexOf(KeyGenerator.PARTITION_SEPARATOR)); + if (!rootPartition.equalsIgnoreCase(keyPartition)) { + throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", userNodeId)); + } + } + return result; + } + + private static String installBusinessEntity(boolean isRoot, EntityManager em, org.uddi.api_v3.BusinessEntity rootBusinessEntity, + UddiEntityPublisher rootPublisher, String rootPartition, Configuration config, String nodeId) + throws JAXBException, DispositionReportFaultMessage, IOException { + + if (isRoot) { + validateRootBusinessEntity(rootBusinessEntity, rootPublisher, rootPartition, config); + } + + org.apache.juddi.model.BusinessEntity modelBusinessEntity = new org.apache.juddi.model.BusinessEntity(); + MappingApiToModel.mapBusinessEntity(rootBusinessEntity, modelBusinessEntity); + + modelBusinessEntity.setAuthorizedName(rootPublisher.getAuthorizedName()); + modelBusinessEntity.setNodeId(nodeId); + Date now = new Date(); + modelBusinessEntity.setCreated(now); + modelBusinessEntity.setModified(now); + modelBusinessEntity.setModifiedIncludingChildren(now); + //JUDDI-645 + //modelBusinessEntity.setNodeId(modelBusinessEntity.getEntityKey()); + modelBusinessEntity.setNodeId(config.getString(Property.JUDDI_NODE_ID, modelBusinessEntity.getEntityKey())); + + for (org.apache.juddi.model.BusinessService service : modelBusinessEntity.getBusinessServices()) { + service.setAuthorizedName(rootPublisher.getAuthorizedName()); + service.setNodeId(modelBusinessEntity.getNodeId()); + service.setCreated(now); + service.setModified(now); + service.setModifiedIncludingChildren(now); + //JUDDI-645 + //service.setNodeId(config.getString(Property.JUDDI_NODE_ID,modelBusinessEntity.getEntityKey())); + //service.setNodeId(modelBusinessEntity.getEntityKey()); + + for (org.apache.juddi.model.BindingTemplate binding : service.getBindingTemplates()) { + binding.setAuthorizedName(rootPublisher.getAuthorizedName()); + binding.setNodeId(nodeId); + binding.setCreated(now); + binding.setModified(now); + binding.setModifiedIncludingChildren(now); + //binding.setNodeId(modelBusinessEntity.getEntityKey()); + //binding.setNodeId(config.getString(Property.JUDDI_NODE_ID,modelBusinessEntity.getEntityKey())); + //JUDDI-645 + + } + } + + em.persist(modelBusinessEntity); + SaveBusiness sb = new SaveBusiness(); + sb.getBusinessEntity().add(rootBusinessEntity); + ReplicationNotifier.enqueue(UDDIPublicationImpl.getChangeRecord(modelBusinessEntity, rootBusinessEntity, modelBusinessEntity.getNodeId())); + + return modelBusinessEntity.getEntityKey(); + + } + + // A watered down version of ValidatePublish's validateBusinessEntity, designed for the specific condition that this is run upon the initial + // jUDDI install. + private static void validateRootBusinessEntity(org.uddi.api_v3.BusinessEntity businessEntity, UddiEntityPublisher rootPublisher, + String rootPartition, Configuration config) + throws DispositionReportFaultMessage { + + // A supplied businessService can't be null + if (businessEntity == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.businessentity.NullInput")); + } + + // The business key should already be set to the previously calculated and validated nodeId. This validation is unnecessary but kept for + // symmetry with the other entity validations. + String entityKey = businessEntity.getBusinessKey(); + if (entityKey == null || entityKey.length() == 0) { + entityKey = rootPartition + KeyGenerator.PARTITION_SEPARATOR + UUID.randomUUID(); + businessEntity.setBusinessKey(entityKey); + } else { + // Per section 4.4: keys must be case-folded + entityKey = entityKey.toLowerCase(); + businessEntity.setBusinessKey(entityKey); + + ValidateUDDIKey.validateUDDIv3Key(entityKey); + String keyPartition = entityKey.substring(0, entityKey.lastIndexOf(KeyGenerator.PARTITION_SEPARATOR)); + if (!rootPartition.equalsIgnoreCase(keyPartition)) { + throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", entityKey)); + } + } + + ValidatePublish validatePublish = new ValidatePublish(rootPublisher, config.getString(Property.JUDDI_NODE_ID)); + + validatePublish.validateNames(businessEntity.getName()); + validatePublish.validateDiscoveryUrls(businessEntity.getDiscoveryURLs()); + validatePublish.validateContacts(businessEntity.getContacts(), config); + validatePublish.validateCategoryBag(businessEntity.getCategoryBag(), config, true); + validatePublish.validateIdentifierBag(businessEntity.getIdentifierBag(), config, true); + + org.uddi.api_v3.BusinessServices businessServices = businessEntity.getBusinessServices(); + if (businessServices != null) { + List businessServiceList = businessServices.getBusinessService(); + if (businessServiceList == null || businessServiceList.size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.businessservices.NoInput")); + } + + for (org.uddi.api_v3.BusinessService businessService : businessServiceList) { + validateRootBusinessService(businessService, businessEntity, rootPublisher, rootPartition, config); + } + } + + } + + // A watered down version of ValidatePublish's validateBusinessService, designed for the specific condition that this is run upon the initial + // jUDDI install. + private static void validateRootBusinessService(org.uddi.api_v3.BusinessService businessService, org.uddi.api_v3.BusinessEntity parent, + UddiEntityPublisher rootPublisher, String rootPartition, Configuration config) + throws DispositionReportFaultMessage { + + // A supplied businessService can't be null + if (businessService == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.businessservice.NullInput")); + } + + // A business key doesn't have to be provided, but if it is, it should match the parent business's key + String parentKey = businessService.getBusinessKey(); + if (parentKey != null && parentKey.length() > 0) { + if (!parentKey.equalsIgnoreCase(parent.getBusinessKey())) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ParentBusinessNotFound", parentKey + " " + businessService.getBusinessKey() + " " + businessService.getBusinessKey().length() + " " + parentKey.length())); + } + } + + // Retrieve the service's passed key + String entityKey = businessService.getServiceKey(); + if (entityKey == null || entityKey.length() == 0) { + entityKey = rootPartition + KeyGenerator.PARTITION_SEPARATOR + UUID.randomUUID(); + businessService.setServiceKey(entityKey); + } else { + // Per section 4.4: keys must be case-folded + entityKey = entityKey.toLowerCase(); + businessService.setServiceKey(entityKey); + + ValidateUDDIKey.validateUDDIv3Key(entityKey); + String keyPartition = entityKey.substring(0, entityKey.lastIndexOf(KeyGenerator.PARTITION_SEPARATOR)); + if (!rootPartition.equalsIgnoreCase(keyPartition)) { + throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", entityKey)); + } + } + + ValidatePublish validatePublish = new ValidatePublish(rootPublisher, config.getString(Property.JUDDI_NODE_ID)); + + validatePublish.validateNames(businessService.getName()); + validatePublish.validateCategoryBag(businessService.getCategoryBag(), config, true); + + org.uddi.api_v3.BindingTemplates bindingTemplates = businessService.getBindingTemplates(); + if (bindingTemplates != null) { + List bindingTemplateList = bindingTemplates.getBindingTemplate(); + if (bindingTemplateList == null || bindingTemplateList.size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.bindingtemplates.NoInput")); + } + + for (org.uddi.api_v3.BindingTemplate bindingTemplate : bindingTemplateList) { + validateRootBindingTemplate(bindingTemplate, businessService, rootPublisher, rootPartition, config); + } + } + } + + // A watered down version of ValidatePublish's validatBindingTemplate, designed for the specific condition that this is run upon the initial + // jUDDI install. + private static void validateRootBindingTemplate(org.uddi.api_v3.BindingTemplate bindingTemplate, org.uddi.api_v3.BusinessService parent, + UddiEntityPublisher rootPublisher, String rootPartition, Configuration config) + throws DispositionReportFaultMessage { + + // A supplied businessService can't be null + if (bindingTemplate == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.bindingtemplate.NullInput")); + } + + // A service key doesn't have to be provided, but if it is, it should match the parent service's key + String parentKey = bindingTemplate.getServiceKey(); + if (parentKey != null && parentKey.length() > 0) { + if (!parentKey.equalsIgnoreCase(parent.getServiceKey())) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ParentServiceNotFound", parentKey)); + } + } + + // Retrieve the service's passed key + String entityKey = bindingTemplate.getBindingKey(); + if (entityKey == null || entityKey.length() == 0) { + entityKey = rootPartition + KeyGenerator.PARTITION_SEPARATOR + UUID.randomUUID(); + bindingTemplate.setBindingKey(entityKey); + } else { + // Per section 4.4: keys must be case-folded + entityKey = entityKey.toLowerCase(); + bindingTemplate.setBindingKey(entityKey); + + ValidateUDDIKey.validateUDDIv3Key(entityKey); + String keyPartition = entityKey.substring(0, entityKey.lastIndexOf(KeyGenerator.PARTITION_SEPARATOR)); + if (!rootPartition.equalsIgnoreCase(keyPartition)) { + throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", entityKey)); + } + } + + ValidatePublish validatePublish = new ValidatePublish(rootPublisher, config.getString(Property.JUDDI_NODE_ID)); + + validatePublish.validateCategoryBag(bindingTemplate.getCategoryBag(), config, true); + validatePublish.validateTModelInstanceDetails(bindingTemplate.getTModelInstanceDetails(), config, true); + + } + + private static void installTModels(EntityManager em, List apiTModelList, UddiEntityPublisher publisher, String nodeId) throws DispositionReportFaultMessage { + if (apiTModelList != null) { + for (org.uddi.api_v3.TModel apiTModel : apiTModelList) { + String tModelKey = apiTModel.getTModelKey(); + + if (tModelKey.toUpperCase().endsWith(KeyGenerator.KEYGENERATOR_SUFFIX.toUpperCase())) { + installPublisherKeyGen(em, apiTModel, publisher, nodeId); + } else { + org.apache.juddi.model.Tmodel modelTModel = new org.apache.juddi.model.Tmodel(); + apiTModel.setTModelKey(apiTModel.getTModelKey().toLowerCase()); + + MappingApiToModel.mapTModel(apiTModel, modelTModel); + + modelTModel.setAuthorizedName(publisher.getAuthorizedName()); + + Date now = new Date(); + modelTModel.setCreated(now); + modelTModel.setModified(now); + modelTModel.setModifiedIncludingChildren(now); + modelTModel.setNodeId(nodeId); + + em.persist(modelTModel); + + SaveTModel stm = new SaveTModel(); + stm.getTModel().add(apiTModel); + ReplicationNotifier.enqueue(UDDIPublicationImpl.getChangeRecord(modelTModel, apiTModel, nodeId)); + } + + } + } + + } + + private static void installRootPublisherKeyGen(EntityManager em, TModel rootTModelKeyGen, String rootPartition, UddiEntityPublisher publisher, String nodeId) + throws DispositionReportFaultMessage { + + rootTModelKeyGen.setTModelKey(rootPartition + KeyGenerator.PARTITION_SEPARATOR + KeyGenerator.KEYGENERATOR_SUFFIX); + + installPublisherKeyGen(em, rootTModelKeyGen, publisher, nodeId); + } + + private static void installPublisherKeyGen(EntityManager em, TModel apiTModel, UddiEntityPublisher publisher, String nodeId) throws DispositionReportFaultMessage { + + org.apache.juddi.model.Tmodel modelTModel = new org.apache.juddi.model.Tmodel(); + MappingApiToModel.mapTModel(apiTModel, modelTModel); + + modelTModel.setAuthorizedName(publisher.getAuthorizedName()); + + Date now = new Date(); + modelTModel.setCreated(now); + modelTModel.setModified(now); + modelTModel.setModifiedIncludingChildren(now); + modelTModel.setNodeId(nodeId); + + em.persist(modelTModel); + + } + + private static List getPublishers(Configuration config) throws ConfigurationException { + List publishers = new ArrayList(); + String basePath = JUDDI_CUSTOM_INSTALL_DATA_DIR; + URL url = ClassUtil.getResource(JUDDI_CUSTOM_INSTALL_DATA_DIR, Install.class); + if (url == null) { + url = ClassUtil.getResource(JUDDI_INSTALL_DATA_DIR, Install.class); + basePath = JUDDI_INSTALL_DATA_DIR; + } + + String path = null; + + try { + path = url.toURI().getSchemeSpecificPart(); + } catch (URISyntaxException e) { + throw new ConfigurationException(e); + } + + File dir = new File(path); + String rootPublisherStr = config.getString(Property.JUDDI_ROOT_PUBLISHER); + if (dir.exists()) { + log.debug("Discovering the Publisher XML data files in directory: " + path); + File[] files = dir.listFiles(new PublisherFileFilter()); + if (files!=null) + for (File f : files) { + String publisher = f.getName().substring(0, f.getName().indexOf(FILE_PUBLISHER)); + if (!rootPublisherStr.equalsIgnoreCase(publisher)) { + publishers.add(publisher); + } + } + } else { + String[] paths = {}; + Enumeration en = null; + JarFile jf = null; + try { + + if (path.indexOf("!") > 0) { + paths = path.split("!"); + jf = new JarFile(new File(new URI(paths[0]))); + en = jf.entries(); + } else { + // Handle Windows / jboss-5.1.0 case + if (path.indexOf(".jar") > 0) { + paths = path.split(".jar"); + paths[0] = paths[0] + ".jar"; + File temp = new File(paths[0]); + if (temp.exists()) { + jf = new JarFile(temp); + en = jf.entries(); + } + } + } + if (paths.length > 0) { + log.debug("Discovering the Publisher XML data files in jar: " + paths[0]); + while (en != null && en.hasMoreElements()) { + String name = en.nextElement().getName(); + if (name.endsWith(FILE_PUBLISHER)) { + log.debug("Found publisher file=" + name); + String publisher = name.substring(basePath.length(), name.indexOf(FILE_PUBLISHER)); + if (!rootPublisherStr.equalsIgnoreCase(publisher)) { + publishers.add(publisher); + } + } + } + } else { + log.info("No custom configuration files where found in " + path); + } + if (jf != null) { + jf.close(); + } + + } catch (IOException e) { + throw new ConfigurationException(e); + } catch (URISyntaxException e) { + throw new ConfigurationException(e); + } + } + return publishers; + } + + private static Object buildInstallEntityAlt(final String fileName, Class outputtype, Configuration config) throws JAXBException, IOException, ConfigurationException { + InputStream resourceStream = null; + + // First try the custom install directory + URL url = ClassUtil.getResource(JUDDI_CUSTOM_INSTALL_DATA_DIR + fileName, Install.class); + if (url != null) { + resourceStream = url.openStream(); + } + + // If the custom install directory doesn't exist, then use the standard install directory where the resource is guaranteed to exist. + if (resourceStream == null) { + url = ClassUtil.getResource(JUDDI_INSTALL_DATA_DIR + fileName, Install.class); + if (url != null) { + resourceStream = url.openStream(); + } + // If file still does not exist then return null; + if (url == null || resourceStream == null) { + if (fileName.endsWith(FILE_PUBLISHER)) { + throw new ConfigurationException("Could not locate " + JUDDI_INSTALL_DATA_DIR + fileName); + } else { + log.debug("Could not locate: " + url); + } + return null; + } + } + log.info("Loading the content of file: " + url); + StringBuilder xml = new StringBuilder(); + byte[] b = new byte[4096]; + for (int n; (n = resourceStream.read(b)) != -1;) { + xml.append(new String(b, 0, n, AuthenticatedService.UTF8)); + } + log.debug("inserting: " + xml.toString()); + StringReader reader = new StringReader(xml.toString()); + + Object obj= XmlUtils.unmarshal(reader, outputtype); + reader.close(); + return obj; + } + + private static Object buildInstallEntity(final String fileName, String packageName, Configuration config) throws JAXBException, IOException, ConfigurationException, XMLStreamException { + InputStream resourceStream = null; + + // First try the custom install directory + URL url = ClassUtil.getResource(JUDDI_CUSTOM_INSTALL_DATA_DIR + fileName, Install.class); + if (url != null) { + resourceStream = url.openStream(); + } + + // If the custom install directory doesn't exist, then use the standard install directory where the resource is guaranteed to exist. + if (resourceStream == null) { + url = ClassUtil.getResource(JUDDI_INSTALL_DATA_DIR + fileName, Install.class); + if (url != null) { + resourceStream = url.openStream(); + } + // If file still does not exist then return null; + if (url == null || resourceStream == null) { + if (fileName.endsWith(FILE_PUBLISHER)) { + throw new ConfigurationException("Could not locate " + JUDDI_INSTALL_DATA_DIR + fileName); + } else { + log.debug("Could not locate: " + url); + } + return null; + } + } + log.info("Loading the content of file: " + url); + StringBuilder xml = new StringBuilder(); + byte[] b = new byte[4096]; + for (int n; (n = resourceStream.read(b)) != -1;) { + xml.append(new String(b, 0, n, AuthenticatedService.UTF8)); + } + log.debug("inserting: " + xml.toString()); + StringReader reader = new StringReader(xml.toString()); + + Object obj= XmlUtils.unmarshal(reader, packageName); + reader.close(); + return obj; + } + + /** + * Public convenience method that allows one to retrieve the node + * business entity (perhaps to display during an install process, or + * even to initiate the install process). + * + * @param businessKey + * @return BusinessEntity Object + * @throws DispositionReportFaultMessage + */ + public static org.uddi.api_v3.BusinessEntity getNodeBusinessEntity(String businessKey) throws DispositionReportFaultMessage { + UDDIInquiryImpl inquiry = new UDDIInquiryImpl(); + + org.uddi.api_v3.GetBusinessDetail gbd = new org.uddi.api_v3.GetBusinessDetail(); + gbd.getBusinessKey().add(businessKey); + + org.uddi.api_v3.BusinessDetail bd = inquiry.getBusinessDetail(gbd); + if (bd != null) { + List beList = bd.getBusinessEntity(); + if (beList != null && beList.size() > 0) { + return beList.get(0); + } + } + + return new org.uddi.api_v3.BusinessEntity(); + } + + /** + * Public convenience method that allows one to install additional + * TModels via a SaveTModel structure. + * + * @param em - the entity manager to a juddi model + * @param fileName - name of SaveTModel xml file + * @param publisher - the publisher structure that owns the tModels + * @param nodeId - the node id of the custodial node + * @throws JAXBException + * @throws DispositionReportFaultMessage + * @throws IOException + * @throws ConfigurationException + */ + public static void installSaveTModel(EntityManager em, String fileName, UddiEntityPublisher publisher, String nodeId, Configuration config) + throws JAXBException, DispositionReportFaultMessage, IOException, ConfigurationException, XMLStreamException { + + SaveTModel apiSaveTModel = (SaveTModel) buildInstallEntity(fileName, "org.uddi.api_v3", config); + if (apiSaveTModel != null) { + installTModels(em, apiSaveTModel.getTModel(), publisher, nodeId); + } + } + + /** + * Public convenience method that allows one to install additional + * Publishers via a Publisher structure. + * + * @param em - the entity manager to the juddi model + * @param fileName - name of Publisher xml file + * @return UddiEntityPublisher object, can be any UDDIEntity + * @throws JAXBException + * @throws DispositionReportFaultMessage + * @throws IOException + * @throws ConfigurationException + */ + public static UddiEntityPublisher installPublisher(EntityManager em, String fileName, Configuration config) + throws JAXBException, DispositionReportFaultMessage, IOException, ConfigurationException, XMLStreamException { + + org.apache.juddi.api_v3.Publisher apiPub = (org.apache.juddi.api_v3.Publisher) buildInstallEntity(fileName, "org.apache.juddi.api_v3", config); + if (apiPub == null) { + return null; + } + org.apache.juddi.model.Publisher modelPub = new org.apache.juddi.model.Publisher(); + MappingApiToModel.mapPublisher(apiPub, modelPub); + em.persist(modelPub); + return modelPub; + } + + public static org.uddi.repl_v3.ReplicationConfiguration applyReplicationTokenChanges(org.uddi.repl_v3.ReplicationConfiguration replicationCfg, Configuration config, String thisnode) { + log.info("replacing tokens on repl config"); + if (replicationCfg == null) { + return null; + } + //apply any token replacements + for (Operator op : replicationCfg.getOperator()) { + op.setOperatorNodeID(op.getOperatorNodeID().replace("${juddi.nodeId}", thisnode)); + op.setSoapReplicationURL(op.getSoapReplicationURL().replace("${juddi.server.baseurlsecure}", config.getString("juddi.server.baseurlsecure"))); + op.setSoapReplicationURL(op.getSoapReplicationURL().replace("${juddi.server.baseurl}", config.getString("juddi.server.baseurl"))); + } + if (replicationCfg.getCommunicationGraph() != null) { + for (int i = 0; i < replicationCfg.getCommunicationGraph().getNode().size(); i++) { + replicationCfg.getCommunicationGraph().getNode().set(i, replicationCfg.getCommunicationGraph().getNode().get(i).replace("${juddi.nodeId}", thisnode)); + + } + for (int i = 0; i < replicationCfg.getCommunicationGraph().getEdge().size(); i++) { + replicationCfg.getCommunicationGraph().getEdge().get(i).setMessageSender(replicationCfg.getCommunicationGraph().getEdge().get(i).getMessageSender().replace("${juddi.nodeId}", thisnode)); + replicationCfg.getCommunicationGraph().getEdge().get(i).setMessageReceiver(replicationCfg.getCommunicationGraph().getEdge().get(i).getMessageReceiver().replace("${juddi.nodeId}", thisnode)); + for (int k = 0; k < replicationCfg.getCommunicationGraph().getEdge().get(i).getMessageReceiverAlternate().size(); k++) { + replicationCfg.getCommunicationGraph().getEdge().get(i).getMessageReceiverAlternate().set(k, replicationCfg.getCommunicationGraph().getEdge().get(i).getMessageReceiverAlternate().get(k).replace("${juddi.nodeId}", thisnode)); + } + } + } + + for (Operator op : replicationCfg.getOperator()) { + op.setOperatorNodeID(op.getOperatorNodeID().replace("${juddi.nodeId}", thisnode)); + } + log.info("replacing tokens on repl config, done"); + return replicationCfg; + } + + private static void installReplicationConfiguration(EntityManager em, org.uddi.repl_v3.ReplicationConfiguration replicationCfg, Configuration config, String thisnode) throws DispositionReportFaultMessage, ConfigurationException { + replicationCfg = applyReplicationTokenChanges(replicationCfg, config, thisnode); + new ValidateReplication(null, thisnode).validateSetReplicationNodes(replicationCfg, em, thisnode, config); + + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddkkmmZ"); + replicationCfg.setTimeOfConfigurationUpdate(sdf.format(new Date())); + + org.apache.juddi.model.ReplicationConfiguration model = new ReplicationConfiguration(); + + MappingApiToModel.mapReplicationConfiguration(replicationCfg, model, em); + + model.setSerialNumber(System.currentTimeMillis()); + + org.apache.juddi.model.ReplicationConfiguration oldstuff = null; + // logger.info(publisher.getAuthorizedName() + " is setting the replication config from " + getRequestorsIPAddress());// + " " + sw.toString()); + try { + oldstuff = (ReplicationConfiguration) em.createQuery("select c FROM ReplicationConfiguration c order by c.serialNumber desc").getSingleResult(); + } catch (Exception ex) { + } + if (oldstuff != null) { + em.remove(oldstuff); + } + em.persist(model); + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/config/PersistenceManager.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/config/PersistenceManager.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/config/PersistenceManager.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/config/PersistenceManager.java diff --git a/juddi-core/src/main/java/org/apache/juddi/config/Property.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/config/Property.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/config/Property.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/config/Property.java diff --git a/juddi-core/src/main/java/org/apache/juddi/config/PublisherFileFilter.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/config/PublisherFileFilter.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/config/PublisherFileFilter.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/config/PublisherFileFilter.java diff --git a/juddi-core/src/main/java/org/apache/juddi/config/Release.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/config/Release.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/config/Release.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/config/Release.java diff --git a/juddi-core/src/main/java/org/apache/juddi/config/ResourceConfig.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/config/ResourceConfig.java similarity index 96% rename from juddi-core/src/main/java/org/apache/juddi/config/ResourceConfig.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/config/ResourceConfig.java index 8be9b02ff..8b8f0fa9d 100644 --- a/juddi-core/src/main/java/org/apache/juddi/config/ResourceConfig.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/config/ResourceConfig.java @@ -1,52 +1,52 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.config; - -import java.util.ResourceBundle; -import java.util.Locale; - -/** - * @author Jeff Faath - */ -public class ResourceConfig { - public static final String GLOBAL_MESSAGES_FILE = "messages"; - - private static final ResourceBundle globalMessages; - - static { - try { - globalMessages = ResourceBundle.getBundle(GLOBAL_MESSAGES_FILE, Locale.getDefault()); - } - catch (Throwable t) { - System.err.println("Initial configuration failed:" + t); - throw new ExceptionInInitializerError(t); - } - } - - public static String getGlobalMessage(String key) { - String msg = null; - if (globalMessages != null) { - if (key != null && key.length() > 0) - msg = globalMessages.getString(key); - } - if (msg != null && msg.length() > 0) - return msg; - - return key; - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.config; + +import java.util.ResourceBundle; +import java.util.Locale; + +/** + * @author Jeff Faath + */ +public class ResourceConfig { + public static final String GLOBAL_MESSAGES_FILE = "messages"; + + private static final ResourceBundle globalMessages; + + static { + try { + globalMessages = ResourceBundle.getBundle(GLOBAL_MESSAGES_FILE, Locale.getDefault()); + } + catch (Throwable t) { + System.err.println("Initial configuration failed:" + t); + throw new ExceptionInInitializerError(t); + } + } + + public static String getGlobalMessage(String key) { + String msg = null; + if (globalMessages != null) { + if (key != null && key.length() > 0) + msg = globalMessages.getString(key); + } + if (msg != null && msg.length() > 0) + return msg; + + return key; + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/config/package-info.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/config/package-info.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/config/package-info.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/config/package-info.java diff --git a/juddi-core/src/main/java/org/apache/juddi/cryptor/CryptorFactory.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/cryptor/CryptorFactory.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/cryptor/CryptorFactory.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/cryptor/CryptorFactory.java index 0b8236eb0..38ea978c5 100644 --- a/juddi-core/src/main/java/org/apache/juddi/cryptor/CryptorFactory.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/cryptor/CryptorFactory.java @@ -1,107 +1,107 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.cryptor; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.ClassUtil; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.Property; -import org.apache.juddi.v3.client.cryptor.Cryptor; - -/** - * Used to create the org.apache.juddi.cryptor.Cryptor implementation as - * specified by the 'juddi.cryptor' property. Defaults to - * org.apache.juddi.cryptor.DefaultCryptor if an implementation is not - * specified.
- *
- * This class is a special instance that loads from the juddi server side config file.
- * - * Use org.apache.juddi.v3.client.cryptor.CryptorFactor for all client side actions - * @see org.apache.juddi.v3.client.cryptor.CryptorFactory - * @author Steve Viens (sviens@apache.org) - * @author Jeff Faath - */ - -public abstract class CryptorFactory { - - private static final Log log = LogFactory.getLog(CryptorFactory.class); - // the shared Cryptor instance - private static Cryptor cryptor = null; - - /* - * Returns a new instance of a CryptorFactory. - * - * @return Cryptor - */ - public static synchronized Cryptor getCryptor() { - if (cryptor == null) { - cryptor = createCryptor(); - } - return cryptor; - } - - public static synchronized Cryptor getCryptor(String className) throws Exception { - return org.apache.juddi.v3.client.cryptor.CryptorFactory.getCryptor(className); - - } - - /* - * Returns a new instance of a Cryptor. - * - * @return Cryptor - */ - private static synchronized Cryptor createCryptor() { - if (cryptor != null) { - return cryptor; - } - - // grab class name of the Cryptor implementation to create - String className = Property.DEFAULT_CRYPTOR; - try { - // grab class name of the Authenticator implementation to create - className = AppConfig.getConfiguration().getString(Property.JUDDI_CRYPTOR, Property.DEFAULT_CRYPTOR); - } catch (ConfigurationException ce) { - log.error("Configuration exception occurred retrieving: " + Property.JUDDI_CRYPTOR, ce); - } - - // write the Cryptor implementation name to the log - log.debug("Cryptor Implementation = " + className); - - Class cryptorClass = null; - try { - // Use Loader to locate & load the Cryptor implementation - cryptorClass = ClassUtil.forName(className, CryptorFactory.class); - } catch (ClassNotFoundException e) { - log.error("The specified Cryptor class '" + className + "' was not found in classpath."); - log.error(e); - } - - if (cryptorClass != null) { - try { - // try to instantiate the Cryptor implementation - cryptor = (Cryptor) cryptorClass.newInstance(); - } catch (Exception e) { - log.error("Exception while attempting to instantiate the implementation of Cryptor: " + cryptorClass.getName() + "\n" + e.getMessage()); - log.error(e); - } - } - - return cryptor; - } +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.cryptor; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.ClassUtil; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.Property; +import org.apache.juddi.v3.client.cryptor.Cryptor; + +/** + * Used to create the org.apache.juddi.cryptor.Cryptor implementation as + * specified by the 'juddi.cryptor' property. Defaults to + * org.apache.juddi.cryptor.DefaultCryptor if an implementation is not + * specified.
+ *
+ * This class is a special instance that loads from the juddi server side config file.
+ * + * Use org.apache.juddi.v3.client.cryptor.CryptorFactor for all client side actions + * @see org.apache.juddi.v3.client.cryptor.CryptorFactory + * @author Steve Viens (sviens@apache.org) + * @author Jeff Faath + */ + +public abstract class CryptorFactory { + + private static final Log log = LogFactory.getLog(CryptorFactory.class); + // the shared Cryptor instance + private static Cryptor cryptor = null; + + /* + * Returns a new instance of a CryptorFactory. + * + * @return Cryptor + */ + public static synchronized Cryptor getCryptor() { + if (cryptor == null) { + cryptor = createCryptor(); + } + return cryptor; + } + + public static synchronized Cryptor getCryptor(String className) throws Exception { + return org.apache.juddi.v3.client.cryptor.CryptorFactory.getCryptor(className); + + } + + /* + * Returns a new instance of a Cryptor. + * + * @return Cryptor + */ + private static synchronized Cryptor createCryptor() { + if (cryptor != null) { + return cryptor; + } + + // grab class name of the Cryptor implementation to create + String className = Property.DEFAULT_CRYPTOR; + try { + // grab class name of the Authenticator implementation to create + className = AppConfig.getConfiguration().getString(Property.JUDDI_CRYPTOR, Property.DEFAULT_CRYPTOR); + } catch (ConfigurationException ce) { + log.error("Configuration exception occurred retrieving: " + Property.JUDDI_CRYPTOR, ce); + } + + // write the Cryptor implementation name to the log + log.debug("Cryptor Implementation = " + className); + + Class cryptorClass = null; + try { + // Use Loader to locate & load the Cryptor implementation + cryptorClass = ClassUtil.forName(className, CryptorFactory.class); + } catch (ClassNotFoundException e) { + log.error("The specified Cryptor class '" + className + "' was not found in classpath."); + log.error(e); + } + + if (cryptorClass != null) { + try { + // try to instantiate the Cryptor implementation + cryptor = (Cryptor) cryptorClass.newInstance(); + } catch (Exception e) { + log.error("Exception while attempting to instantiate the implementation of Cryptor: " + cryptorClass.getName() + "\n" + e.getMessage()); + log.error(e); + } + } + + return cryptor; + } } \ No newline at end of file diff --git a/juddi-core/src/main/java/org/apache/juddi/cryptor/package-info.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/cryptor/package-info.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/cryptor/package-info.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/cryptor/package-info.java diff --git a/juddi-core/src/main/java/org/apache/juddi/keygen/DefaultKeyGenerator.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/keygen/DefaultKeyGenerator.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/keygen/DefaultKeyGenerator.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/keygen/DefaultKeyGenerator.java index f6b59cadf..6fbf377b9 100644 --- a/juddi-core/src/main/java/org/apache/juddi/keygen/DefaultKeyGenerator.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/keygen/DefaultKeyGenerator.java @@ -1,83 +1,83 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.keygen; - -import java.util.Iterator; -import java.util.List; -import java.util.UUID; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.Property; -import org.apache.juddi.model.UddiEntityPublisher; -import org.apache.juddi.v3.client.UDDIConstants; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.FatalErrorException; -import org.uddi.v3_service.DispositionReportFaultMessage; - -/** - * The default jUDDI key generator. Generates a key like this: - * - * uddiScheme : domain : UUID - * - * where domain is the shortest keyGenerator domain. - * - * If no domain is set for this publihser, or the publisher is 'uddi' then - * it defaults to the RootDomain: - * - * uddiScheme : RootDomain : UUID - * - * @author Jeff Faath - */ -public class DefaultKeyGenerator implements KeyGenerator { - - public String generate(UddiEntityPublisher publisher) throws DispositionReportFaultMessage { - String domain = getDomain(publisher); - if (domain==null) { - String rootPartition = ""; - try - { rootPartition = AppConfig.getConfiguration().getString(Property.JUDDI_ROOT_PARTITION); } - catch(ConfigurationException ce) - { throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval", Property.JUDDI_ROOT_PARTITION));} - domain = rootPartition; - } - return domain + PARTITION_SEPARATOR + UUID.randomUUID(); - } - - public static String getDomain(UddiEntityPublisher publisher) { - String domain = null; - if (publisher==null || "uddi".equalsIgnoreCase(publisher.getAuthorizedName())) return domain; //default to the rootPartition - List domains = publisher.getKeyGeneratorKeys(); - if (domains!=null && !domains.isEmpty()) { - Iterator iter = domains.iterator(); - int partsMax = 1000; - //pick the KeyGenerator with the fewest amount of parts, ignoring the subdomain keys. - while (iter.hasNext()) { - String thisDomain = iter.next(); - String[] parts = thisDomain.split(":"); - if ((domain == null || (2 <= parts.length && parts.length < partsMax)) && thisDomain.length() + 37 < 255) { - partsMax = parts.length; - domain = thisDomain; - } - } - domain = domain.substring(0, domain.lastIndexOf(":")); - } - return domain; - } - +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.keygen; + +import java.util.Iterator; +import java.util.List; +import java.util.UUID; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.Property; +import org.apache.juddi.model.UddiEntityPublisher; +import org.apache.juddi.v3.client.UDDIConstants; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.FatalErrorException; +import org.uddi.v3_service.DispositionReportFaultMessage; + +/** + * The default jUDDI key generator. Generates a key like this: + * + * uddiScheme : domain : UUID + * + * where domain is the shortest keyGenerator domain. + * + * If no domain is set for this publihser, or the publisher is 'uddi' then + * it defaults to the RootDomain: + * + * uddiScheme : RootDomain : UUID + * + * @author Jeff Faath + */ +public class DefaultKeyGenerator implements KeyGenerator { + + public String generate(UddiEntityPublisher publisher) throws DispositionReportFaultMessage { + String domain = getDomain(publisher); + if (domain==null) { + String rootPartition = ""; + try + { rootPartition = AppConfig.getConfiguration().getString(Property.JUDDI_ROOT_PARTITION); } + catch(ConfigurationException ce) + { throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval", Property.JUDDI_ROOT_PARTITION));} + domain = rootPartition; + } + return domain + PARTITION_SEPARATOR + UUID.randomUUID(); + } + + public static String getDomain(UddiEntityPublisher publisher) { + String domain = null; + if (publisher==null || "uddi".equalsIgnoreCase(publisher.getAuthorizedName())) return domain; //default to the rootPartition + List domains = publisher.getKeyGeneratorKeys(); + if (domains!=null && !domains.isEmpty()) { + Iterator iter = domains.iterator(); + int partsMax = 1000; + //pick the KeyGenerator with the fewest amount of parts, ignoring the subdomain keys. + while (iter.hasNext()) { + String thisDomain = iter.next(); + String[] parts = thisDomain.split(":"); + if ((domain == null || (2 <= parts.length && parts.length < partsMax)) && thisDomain.length() + 37 < 255) { + partsMax = parts.length; + domain = thisDomain; + } + } + domain = domain.substring(0, domain.lastIndexOf(":")); + } + return domain; + } + } \ No newline at end of file diff --git a/juddi-core/src/main/java/org/apache/juddi/keygen/KeyGenerator.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/keygen/KeyGenerator.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/keygen/KeyGenerator.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/keygen/KeyGenerator.java index f9705fa69..f8b8b2e26 100644 --- a/juddi-core/src/main/java/org/apache/juddi/keygen/KeyGenerator.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/keygen/KeyGenerator.java @@ -1,35 +1,35 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.keygen; - -import org.apache.juddi.model.UddiEntityPublisher; -import org.uddi.v3_service.DispositionReportFaultMessage; - -/** - * @author Jeff Faath - */ -public interface KeyGenerator { - public static final String UDDI_SCHEME = "uddi"; - public static final String PARTITION_SEPARATOR = ":"; - public static final String KEYGENERATOR_SUFFIX = "keygenerator"; - - /* - * Generates a key that is used to save a UDDI entity. - */ - public String generate(UddiEntityPublisher publisher) throws DispositionReportFaultMessage; +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.keygen; + +import org.apache.juddi.model.UddiEntityPublisher; +import org.uddi.v3_service.DispositionReportFaultMessage; + +/** + * @author Jeff Faath + */ +public interface KeyGenerator { + public static final String UDDI_SCHEME = "uddi"; + public static final String PARTITION_SEPARATOR = ":"; + public static final String KEYGENERATOR_SUFFIX = "keygenerator"; + + /* + * Generates a key that is used to save a UDDI entity. + */ + public String generate(UddiEntityPublisher publisher) throws DispositionReportFaultMessage; } \ No newline at end of file diff --git a/juddi-core/src/main/java/org/apache/juddi/keygen/KeyGeneratorFactory.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/keygen/KeyGeneratorFactory.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/keygen/KeyGeneratorFactory.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/keygen/KeyGeneratorFactory.java index 487ccbbf2..7b739410b 100644 --- a/juddi-core/src/main/java/org/apache/juddi/keygen/KeyGeneratorFactory.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/keygen/KeyGeneratorFactory.java @@ -1,107 +1,107 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.keygen; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.ClassUtil; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.Property; - -/** - * Used to create the org.apache.juddi.keygen.KeyGenerator implementation - * as specified by the 'juddi.keygenerator' property. Defaults to - * org.apache.juddi.cryptor.DefaultKeyGenerator if an implementation is not - * specified. - * - * @author Jeff Faath - */ -public abstract class KeyGeneratorFactory { - private static Log log = LogFactory.getLog(KeyGeneratorFactory.class); - - // Key Generator default implementation - public static final String DEFAULT_IMPL = "org.apache.juddi.keygen.DefaultKeyGenerator"; - - // the shared Key Generator instance - private static KeyGenerator keyGenerator = null; - - /* - * Returns a new instance of a KeyGenerator. - * - * @return KeyGenerator - */ - public static synchronized KeyGenerator getKeyGenerator() { - if (keyGenerator == null) - keyGenerator = createKeyGenerator(); - return keyGenerator; - } - - public static synchronized KeyGenerator forceNewKeyGenerator() { - keyGenerator = null; - keyGenerator = createKeyGenerator(); - return keyGenerator; - } - - /* - * Returns a new instance of a Cryptor. - * - * @return Cryptor - */ - private static synchronized KeyGenerator createKeyGenerator() { - if (keyGenerator != null) - return keyGenerator; - - // grab class name of the Cryptor implementation to create - String className = System.getProperty(Property.JUDDI_KEYGENERATOR); - if (className==null){ - try { - // grab class name of the Authenticator implementation to create - className = AppConfig.getConfiguration().getString(Property.JUDDI_KEYGENERATOR, DEFAULT_IMPL); - } - catch(ConfigurationException ce) { - log.error("Configuration exception occurred retrieving: " + Property.JUDDI_KEYGENERATOR); - } - } - try { - // write the Cryptor implementation name to the log - log.debug("Configuration Key Generator Implementation = " + AppConfig.getConfiguration().getString(Property.JUDDI_KEYGENERATOR)); - } catch (ConfigurationException ex) { - } - log.debug("SysProp Key Generator Implementation = " + System.getProperty(Property.JUDDI_KEYGENERATOR)); - log.debug("Using Key Generator Implementation = " + className); - - Class keygenClass = null; - try { - // Use Loader to locate & load the Key Generator implementation - keygenClass = ClassUtil.forName(className,KeyGeneratorFactory.class); - // try to instantiate the Key Generator implementation - keyGenerator = (KeyGenerator)keygenClass.newInstance(); - } catch(ClassNotFoundException cnfe) { - throw new RuntimeException("The specified Key Generator class '" + className + "' was not found on classpath.",cnfe); - } catch(InstantiationException ie) { - throw new RuntimeException("The specified Key Generator class '" + className + "' cannot be instantiated.",ie); - } catch(IllegalAccessException iae) { - throw new RuntimeException("The specified Key Generator class '" + className + "' cannot be instantiated due to illegal access.",iae); - } catch(Exception e) { - throw new RuntimeException("Exception while attempting to instantiate the implementation of Key Generator: " + className + "\n" + e.getMessage()); - } - - return keyGenerator; - } +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.keygen; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.ClassUtil; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.Property; + +/** + * Used to create the org.apache.juddi.keygen.KeyGenerator implementation + * as specified by the 'juddi.keygenerator' property. Defaults to + * org.apache.juddi.cryptor.DefaultKeyGenerator if an implementation is not + * specified. + * + * @author Jeff Faath + */ +public abstract class KeyGeneratorFactory { + private static Log log = LogFactory.getLog(KeyGeneratorFactory.class); + + // Key Generator default implementation + public static final String DEFAULT_IMPL = "org.apache.juddi.keygen.DefaultKeyGenerator"; + + // the shared Key Generator instance + private static KeyGenerator keyGenerator = null; + + /* + * Returns a new instance of a KeyGenerator. + * + * @return KeyGenerator + */ + public static synchronized KeyGenerator getKeyGenerator() { + if (keyGenerator == null) + keyGenerator = createKeyGenerator(); + return keyGenerator; + } + + public static synchronized KeyGenerator forceNewKeyGenerator() { + keyGenerator = null; + keyGenerator = createKeyGenerator(); + return keyGenerator; + } + + /* + * Returns a new instance of a Cryptor. + * + * @return Cryptor + */ + private static synchronized KeyGenerator createKeyGenerator() { + if (keyGenerator != null) + return keyGenerator; + + // grab class name of the Cryptor implementation to create + String className = System.getProperty(Property.JUDDI_KEYGENERATOR); + if (className==null){ + try { + // grab class name of the Authenticator implementation to create + className = AppConfig.getConfiguration().getString(Property.JUDDI_KEYGENERATOR, DEFAULT_IMPL); + } + catch(ConfigurationException ce) { + log.error("Configuration exception occurred retrieving: " + Property.JUDDI_KEYGENERATOR); + } + } + try { + // write the Cryptor implementation name to the log + log.debug("Configuration Key Generator Implementation = " + AppConfig.getConfiguration().getString(Property.JUDDI_KEYGENERATOR)); + } catch (ConfigurationException ex) { + } + log.debug("SysProp Key Generator Implementation = " + System.getProperty(Property.JUDDI_KEYGENERATOR)); + log.debug("Using Key Generator Implementation = " + className); + + Class keygenClass = null; + try { + // Use Loader to locate & load the Key Generator implementation + keygenClass = ClassUtil.forName(className,KeyGeneratorFactory.class); + // try to instantiate the Key Generator implementation + keyGenerator = (KeyGenerator)keygenClass.newInstance(); + } catch(ClassNotFoundException cnfe) { + throw new RuntimeException("The specified Key Generator class '" + className + "' was not found on classpath.",cnfe); + } catch(InstantiationException ie) { + throw new RuntimeException("The specified Key Generator class '" + className + "' cannot be instantiated.",ie); + } catch(IllegalAccessException iae) { + throw new RuntimeException("The specified Key Generator class '" + className + "' cannot be instantiated due to illegal access.",iae); + } catch(Exception e) { + throw new RuntimeException("Exception while attempting to instantiate the implementation of Key Generator: " + className + "\n" + e.getMessage()); + } + + return keyGenerator; + } } \ No newline at end of file diff --git a/juddi-core/src/main/java/org/apache/juddi/keygen/package-info.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/keygen/package-info.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/keygen/package-info.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/keygen/package-info.java diff --git a/juddi-core/src/main/java/org/apache/juddi/mapping/MappingApiToModel.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/mapping/MappingApiToModel.java similarity index 98% rename from juddi-core/src/main/java/org/apache/juddi/mapping/MappingApiToModel.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/mapping/MappingApiToModel.java index aea10172d..aff03038e 100644 --- a/juddi-core/src/main/java/org/apache/juddi/mapping/MappingApiToModel.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/mapping/MappingApiToModel.java @@ -1,1692 +1,1692 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.mapping; - -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.HashSet; -import java.util.List; -import javax.persistence.EntityManager; -import javax.xml.bind.JAXB; -import javax.xml.bind.JAXBElement; -import javax.xml.transform.dom.DOMResult; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.api.impl.AuthenticatedService; -import org.apache.juddi.jaxb.JAXBMarshaller; -import org.apache.juddi.model.Address; -import org.apache.juddi.model.BindingTemplate; -import org.apache.juddi.model.BusinessEntity; -import org.apache.juddi.model.BusinessService; -import org.apache.juddi.model.CanonicalizationMethod; -import org.apache.juddi.model.Contact; -import org.apache.juddi.model.ControlMessage; -import org.apache.juddi.model.Edge; -import org.apache.juddi.model.EdgeReceiverAlternate; -import org.apache.juddi.model.KeyDataValue; -import org.apache.juddi.model.KeyInfo; -import org.apache.juddi.model.Node; -import org.apache.juddi.model.Operator; -import org.apache.juddi.model.OperatorStatusType; -import org.apache.juddi.model.Publisher; -import org.apache.juddi.model.Reference; -import org.apache.juddi.model.ReplicationConfigurationNode; -import org.apache.juddi.model.Signature; -import org.apache.juddi.model.SignatureMethod; -import org.apache.juddi.model.SignatureTransform; -import org.apache.juddi.model.SignatureTransformDataValue; -import org.apache.juddi.model.SignatureValue; -import org.apache.juddi.model.SignedInfo; -import org.apache.juddi.model.Tmodel; -import org.apache.juddi.model.UddiEntity; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.ValueNotAllowedException; -import org.uddi.api_v3.Description; -import org.uddi.api_v3.OperationalInfo; -import org.uddi.api_v3.SaveBinding; -import org.uddi.repl_v3.ChangeRecord; -import org.uddi.repl_v3.CommunicationGraph; -import org.uddi.repl_v3.ReplicationConfiguration; -import org.uddi.sub_v3.ObjectFactory; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.w3._2000._09.xmldsig_.DSAKeyValueType; -import org.w3._2000._09.xmldsig_.KeyInfoType; -import org.w3._2000._09.xmldsig_.KeyValueType; -import org.w3._2000._09.xmldsig_.PGPDataType; -import org.w3._2000._09.xmldsig_.RSAKeyValueType; -import org.w3._2000._09.xmldsig_.ReferenceType; -import org.w3._2000._09.xmldsig_.RetrievalMethodType; -import org.w3._2000._09.xmldsig_.SPKIDataType; -import org.w3._2000._09.xmldsig_.TransformType; -import org.w3._2000._09.xmldsig_.TransformsType; -import org.w3._2000._09.xmldsig_.X509DataType; -import org.w3._2000._09.xmldsig_.X509IssuerSerialType; -import org.w3c.dom.DOMException; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.ls.DOMImplementationLS; -import org.w3c.dom.ls.LSException; -import org.w3c.dom.ls.LSSerializer; - -/** - * Handles mapping from the internal jUDDL API Model to the JAXB/XML/WSDL UDDI - * data structures - * - * @author Jeff Faath - * @author Kurt T Stam - * @author Tom Cunningham - * @author Alex O'Ree - */ -public class MappingApiToModel { - - private static Log logger = LogFactory.getLog(MappingApiToModel.class); - - /** - * - * @param apiPublisher - * @param modelPublisher - * @throws DispositionReportFaultMessage - */ - public static void mapPublisher(org.apache.juddi.api_v3.Publisher apiPublisher, - org.apache.juddi.model.Publisher modelPublisher) - throws DispositionReportFaultMessage { - modelPublisher.setAuthorizedName(apiPublisher.getAuthorizedName()); - modelPublisher.setPublisherName(apiPublisher.getPublisherName()); - modelPublisher.setEmailAddress(apiPublisher.getEmailAddress()); - modelPublisher.setIsAdmin(apiPublisher.isIsAdmin()); - modelPublisher.setIsEnabled(apiPublisher.isIsEnabled()); - modelPublisher.setMaxBindingsPerService(apiPublisher.getMaxBindingsPerService()); - modelPublisher.setMaxBusinesses(apiPublisher.getMaxBusinesses()); - modelPublisher.setMaxServicesPerBusiness(apiPublisher.getMaxServicePerBusiness()); - modelPublisher.setMaxTmodels(apiPublisher.getMaxTModels()); - mapPublisherSignatures(apiPublisher.getSignature(), modelPublisher); - } - - /** - * - * @param apiBusinessEntity - * @param modelBusinessEntity - * @throws DispositionReportFaultMessage - */ - public static void mapBusinessEntity(org.uddi.api_v3.BusinessEntity apiBusinessEntity, - org.apache.juddi.model.BusinessEntity modelBusinessEntity) - throws DispositionReportFaultMessage { - - modelBusinessEntity.setEntityKey(apiBusinessEntity.getBusinessKey()); - - mapBusinessNames(apiBusinessEntity.getName(), modelBusinessEntity.getBusinessNames(), modelBusinessEntity); - mapBusinessDescriptions(apiBusinessEntity.getDescription(), modelBusinessEntity.getBusinessDescrs(), modelBusinessEntity); - mapDiscoveryUrls(apiBusinessEntity.getDiscoveryURLs(), modelBusinessEntity.getDiscoveryUrls(), modelBusinessEntity); - mapContacts(apiBusinessEntity.getContacts(), modelBusinessEntity.getContacts(), modelBusinessEntity); - mapBusinessIdentifiers(apiBusinessEntity.getIdentifierBag(), modelBusinessEntity.getBusinessIdentifiers(), modelBusinessEntity); - if (apiBusinessEntity.getCategoryBag() != null) { - modelBusinessEntity.setCategoryBag(new org.apache.juddi.model.BusinessCategoryBag(modelBusinessEntity)); - mapCategoryBag(apiBusinessEntity.getCategoryBag(), modelBusinessEntity.getCategoryBag()); - } - - mapBusinessServices(apiBusinessEntity.getBusinessServices(), - modelBusinessEntity.getBusinessServices(), - modelBusinessEntity.getServiceProjections(), - modelBusinessEntity); - - mapBusinessSignature(apiBusinessEntity.getSignature(), modelBusinessEntity); - } - - public static List mapApiSignaturesToModelSignatures(List apiSignatures) - throws DispositionReportFaultMessage { - List modelSignatures = new ArrayList(); - modelSignatures.clear(); - for (org.w3._2000._09.xmldsig_.SignatureType signatureType : apiSignatures) { - Signature modelSignature = new Signature(); - - org.w3._2000._09.xmldsig_.SignedInfoType apiSignedInfo = signatureType.getSignedInfo(); - SignedInfo modelSignedInfo = new SignedInfo(); - modelSignature.setSignedInfo(modelSignedInfo); - - String canonicalizationAlgMethod = apiSignedInfo.getCanonicalizationMethod().getAlgorithm(); - CanonicalizationMethod modelCanonMethod = new CanonicalizationMethod(); - modelSignedInfo.setCanonicalizationMethod(modelCanonMethod); - modelCanonMethod.setAlgorithm(canonicalizationAlgMethod); - - SignatureMethod modelSigMethod = new SignatureMethod(); - modelSignedInfo.setSignatureMethod(modelSigMethod); - String sigMethod = apiSignedInfo.getSignatureMethod().getAlgorithm(); - modelSigMethod.setAlgorithm(sigMethod); - - List apiReferenceList = apiSignedInfo.getReference(); - for (org.w3._2000._09.xmldsig_.ReferenceType apiReference : apiReferenceList) { - Reference ref = mapReference(modelSignedInfo, apiReference); - modelSignedInfo.getReference().add(ref); - } - - modelSignedInfo.setCanonicalizationMethod(modelCanonMethod); - - org.w3._2000._09.xmldsig_.SignatureValueType apiSignatureValue = signatureType.getSignatureValue(); - SignatureValue modelSignatureValue = new SignatureValue(); - byte[] signatureValueBytes = apiSignatureValue.getValue(); - String signatureValueXmlID = apiSignatureValue.getId(); - modelSignatureValue.setValue(signatureValueBytes); - modelSignatureValue.setXmlID(signatureValueXmlID); - modelSignature.setSignatureValue(modelSignatureValue); - - org.w3._2000._09.xmldsig_.KeyInfoType apiKeyInfo = signatureType.getKeyInfo(); - String apiKeyInfoXmlID = apiKeyInfo.getId(); - KeyInfo modelKeyInfo = new KeyInfo(); - modelSignature.setKeyInfo(modelKeyInfo); - modelKeyInfo.setXmlID(apiKeyInfoXmlID); - - List apiKeyInfoContentList = apiKeyInfo.getContent(); - List keyInfoDataValues = modelKeyInfo.getKeyDataValue(); - for (Object apiKeyInfoContentObj : apiKeyInfoContentList) { - if (apiKeyInfoContentObj instanceof JAXBElement) { - JAXBElement apiKeyInfoContentJAXB = (JAXBElement) apiKeyInfoContentObj; - String apiKeyInfoContentTagName = apiKeyInfoContentJAXB.getName().getLocalPart(); - if (apiKeyInfoContentJAXB.getValue() instanceof X509DataType) { - KeyDataValue modelX509KeyData = mapX509DataType(apiKeyInfoContentJAXB, modelKeyInfo); - keyInfoDataValues.add(modelX509KeyData); - } else if (apiKeyInfoContentTagName.equals("KeyName")) { - KeyDataValue modelKeyNameKDV = mapKeyName(apiKeyInfoContentJAXB); - modelKeyNameKDV.setKeyInfo(modelKeyInfo); - keyInfoDataValues.add(modelKeyNameKDV); - } else if (apiKeyInfoContentTagName.equals("KeyValue")) { - KeyDataValue modelKeyValueKDV = mapKeyValue(apiKeyInfoContentJAXB, keyInfoDataValues); - modelKeyValueKDV.setKeyInfo(modelKeyInfo); - keyInfoDataValues.add(modelKeyValueKDV); - } else if (apiKeyInfoContentTagName.equals("MgmtData")) { - KeyDataValue modelKeyValueKDV = new KeyDataValue(); - modelKeyValueKDV.setKeyDataName(apiKeyInfoContentTagName); - modelKeyValueKDV.setKeyDataType("String"); - modelKeyValueKDV.setKeyDataValueString((String) apiKeyInfoContentJAXB.getValue()); - modelKeyValueKDV.setKeyInfo(modelKeyInfo); - keyInfoDataValues.add(modelKeyValueKDV); - } else if (apiKeyInfoContentTagName.equals("RetrievalMethod")) { - RetrievalMethodType retrievalMethodType = (RetrievalMethodType) apiKeyInfoContentJAXB.getValue(); - KeyDataValue retrievalMethodTypeKDV = mapRetrievalMethod(apiKeyInfoContentTagName, modelKeyInfo, retrievalMethodType); - keyInfoDataValues.add(retrievalMethodTypeKDV); - } else if (apiKeyInfoContentTagName.equals("PGPData")) { - PGPDataType pgpDataType = (PGPDataType) apiKeyInfoContentJAXB.getValue(); - KeyDataValue pgpDataTypeKDV = mapPGPDataType(apiKeyInfoContentTagName, modelKeyInfo, pgpDataType); - keyInfoDataValues.add(pgpDataTypeKDV); - } else if (apiKeyInfoContentTagName.equals("SPKIData")) { - SPKIDataType spkiDataType = (SPKIDataType) apiKeyInfoContentJAXB.getValue(); - KeyDataValue spkiDataTypeKDV = mapSPKIDataType(apiKeyInfoContentTagName, modelKeyInfo, spkiDataType); - keyInfoDataValues.add(spkiDataTypeKDV); - } else { - throw new RuntimeException("Unrecognized tag: " + apiKeyInfoContentTagName + " type: " + apiKeyInfoContentJAXB.getValue().getClass().getCanonicalName()); - } - } - } - - modelSignatures.add(modelSignature); - } - return modelSignatures; - } - - /** - * - * @param apiSignatures - * @param modelBusinessService - * @throws DispositionReportFaultMessage - */ - public static void mapBusinessServiceSignature(List apiSignatures, BusinessService modelBusinessService) - throws DispositionReportFaultMessage { - List modelSignatures = mapApiSignaturesToModelSignatures(apiSignatures); - for (Signature modelSignature : modelSignatures) { - modelSignature.setBusinessService(modelBusinessService); - } - modelBusinessService.setSignatures(modelSignatures); - } - - /** - * - * @param apiSignatures - * @param modelTmodel - * @throws DispositionReportFaultMessage - */ - public static void mapTmodelSignatures(List apiSignatures, Tmodel modelTmodel) - throws DispositionReportFaultMessage { - List modelSignatures = mapApiSignaturesToModelSignatures(apiSignatures); - for (Signature modelSignature : modelSignatures) { - modelSignature.setTmodel(modelTmodel); - } - modelTmodel.setSignatures(modelSignatures); - } - - /** - * - * @param apiSignatures - * @param modelBindingTemplate - * @throws DispositionReportFaultMessage - */ - public static void mapBindingTemplateSignatures(List apiSignatures, BindingTemplate modelBindingTemplate) - throws DispositionReportFaultMessage { - List modelSignatures = mapApiSignaturesToModelSignatures(apiSignatures); - for (Signature modelSignature : modelSignatures) { - modelSignature.setBindingTemplate(modelBindingTemplate); - } - modelBindingTemplate.setSignatures(modelSignatures); - } - - /** - * - * @param apiSignatures - * @param modelPublisher - * @throws DispositionReportFaultMessage - */ - public static void mapPublisherSignatures(List apiSignatures, Publisher modelPublisher) - throws DispositionReportFaultMessage { - List modelSignatures = mapApiSignaturesToModelSignatures(apiSignatures); - for (Signature modelSignature : modelSignatures) { - modelSignature.setPublisher(modelPublisher); - } - modelPublisher.setSignatures(modelSignatures); - } - - /** - * - * @param apiSignatures - * @param modelBusinessEntity - * @throws DispositionReportFaultMessage - */ - public static void mapBusinessSignature(List apiSignatures, - org.apache.juddi.model.BusinessEntity modelBusinessEntity) - throws DispositionReportFaultMessage { - List modelSignatures = mapApiSignaturesToModelSignatures(apiSignatures); - for (Signature modelSignature : modelSignatures) { - modelSignature.setBusinessEntity(modelBusinessEntity); - } - modelBusinessEntity.setSignatures(modelSignatures); - } - - /** - * - * @param apiNameList - * @param modelNameList - * @param modelBusinessEntity - * @throws DispositionReportFaultMessage - */ - public static void mapBusinessNames(List apiNameList, - List modelNameList, - org.apache.juddi.model.BusinessEntity modelBusinessEntity) - throws DispositionReportFaultMessage { - modelNameList.clear(); - - for (org.uddi.api_v3.Name apiName : apiNameList) { - modelNameList.add(new org.apache.juddi.model.BusinessName(modelBusinessEntity, apiName.getLang(), apiName.getValue())); - } - } - - /** - * - * @param apiDescList - * @param modelDescList - * @param modelBusinessEntity - * @throws DispositionReportFaultMessage - */ - public static void mapBusinessDescriptions(List apiDescList, - List modelDescList, - org.apache.juddi.model.BusinessEntity modelBusinessEntity) - throws DispositionReportFaultMessage { - modelDescList.clear(); - - for (org.uddi.api_v3.Description apiDesc : apiDescList) { - modelDescList.add(new org.apache.juddi.model.BusinessDescr(modelBusinessEntity, apiDesc.getLang(), apiDesc.getValue())); - } - } - - /** - * - * @param apiDiscUrls - * @param modelDiscUrlList - * @param modelBusinessEntity - * @throws DispositionReportFaultMessage - */ - public static void mapDiscoveryUrls(org.uddi.api_v3.DiscoveryURLs apiDiscUrls, - List modelDiscUrlList, - org.apache.juddi.model.BusinessEntity modelBusinessEntity) - throws DispositionReportFaultMessage { - modelDiscUrlList.clear(); - - if (apiDiscUrls != null) { - List apiDiscUrlList = apiDiscUrls.getDiscoveryURL(); - for (org.uddi.api_v3.DiscoveryURL apiDiscUrl : apiDiscUrlList) { - modelDiscUrlList.add(new org.apache.juddi.model.DiscoveryUrl(modelBusinessEntity, apiDiscUrl.getUseType(), apiDiscUrl.getValue())); - } - } - } - - /** - * - * @param apiContacts - * @param modelContactList - * @param modelBusinessEntity - * @throws DispositionReportFaultMessage - */ - public static void mapContacts(org.uddi.api_v3.Contacts apiContacts, - List modelContactList, - org.apache.juddi.model.BusinessEntity modelBusinessEntity) - throws DispositionReportFaultMessage { - modelContactList.clear(); - - if (apiContacts != null) { - List apiContactList = apiContacts.getContact(); - for (org.uddi.api_v3.Contact apiContact : apiContactList) { - org.apache.juddi.model.Contact modelContact = new org.apache.juddi.model.Contact(modelBusinessEntity); - modelContact.setUseType(apiContact.getUseType()); - - mapPersonNames(apiContact.getPersonName(), modelContact.getPersonNames(), modelContact, modelBusinessEntity.getEntityKey()); - mapContactDescriptions(apiContact.getDescription(), modelContact.getContactDescrs(), modelContact, modelBusinessEntity.getEntityKey()); - mapContactEmails(apiContact.getEmail(), modelContact.getEmails(), modelContact, modelBusinessEntity.getEntityKey()); - mapContactPhones(apiContact.getPhone(), modelContact.getPhones(), modelContact, modelBusinessEntity.getEntityKey()); - mapContactAddresses(apiContact.getAddress(), modelContact.getAddresses(), modelContact); - - modelContactList.add(modelContact); - } - } - } - - /** - * - * @param apiDescList - * @param modelDescList - * @param modelContact - * @param businessKey - * @throws DispositionReportFaultMessage - */ - public static void mapContactDescriptions(List apiDescList, - List modelDescList, - org.apache.juddi.model.Contact modelContact, - String businessKey) - throws DispositionReportFaultMessage { - modelDescList.clear(); - - for (org.uddi.api_v3.Description apiDesc : apiDescList) { - modelDescList.add(new org.apache.juddi.model.ContactDescr(modelContact, apiDesc.getLang(), apiDesc.getValue())); - } - } - - /** - * - * @param apiPersonNameList - * @param modelPersonNameList - * @param modelContact - * @param businessKey - * @throws DispositionReportFaultMessage - */ - public static void mapPersonNames(List apiPersonNameList, - List modelPersonNameList, - org.apache.juddi.model.Contact modelContact, - String businessKey) - throws DispositionReportFaultMessage { - modelPersonNameList.clear(); - - for (org.uddi.api_v3.PersonName apiPersonName : apiPersonNameList) { - modelPersonNameList.add(new org.apache.juddi.model.PersonName(modelContact, apiPersonName.getLang(), apiPersonName.getValue())); - } - } - - /** - * - * @param apiEmailList - * @param modelEmailList - * @param modelContact - * @param businessKey - * @throws DispositionReportFaultMessage - */ - public static void mapContactEmails(List apiEmailList, - List modelEmailList, - org.apache.juddi.model.Contact modelContact, - String businessKey) - throws DispositionReportFaultMessage { - modelEmailList.clear(); - - for (org.uddi.api_v3.Email apiEmail : apiEmailList) { - modelEmailList.add(new org.apache.juddi.model.Email(modelContact, apiEmail.getUseType(), apiEmail.getValue())); - } - } - - /** - * - * @param apiPhoneList - * @param modelPhoneList - * @param modelContact - * @param businessKey - * @throws DispositionReportFaultMessage - */ - public static void mapContactPhones(List apiPhoneList, - List modelPhoneList, - org.apache.juddi.model.Contact modelContact, - String businessKey) - throws DispositionReportFaultMessage { - modelPhoneList.clear(); - - for (org.uddi.api_v3.Phone apiPhone : apiPhoneList) { - modelPhoneList.add(new org.apache.juddi.model.Phone(modelContact, apiPhone.getUseType(), apiPhone.getValue())); - } - } - - /** - * - * @param apiAddressList - * @param modelAddressList - * @param modelContact - * @param businessKey - * @throws DispositionReportFaultMessage - */ - public static void mapContactAddresses(List apiAddressList, - List modelAddressList, - org.apache.juddi.model.Contact modelContact - ) - throws DispositionReportFaultMessage { - modelAddressList.clear(); - - for (org.uddi.api_v3.Address apiAddress : apiAddressList) { - org.apache.juddi.model.Address modelAddress = new org.apache.juddi.model.Address(modelContact); - modelAddress.setSortCode(apiAddress.getSortCode()); - modelAddress.setTmodelKey(apiAddress.getTModelKey()); - modelAddress.setUseType(apiAddress.getUseType()); - - mapAddressLines(apiAddress.getAddressLine(), modelAddress.getAddressLines(), modelAddress, modelContact.getId()); - - modelAddressList.add(modelAddress); - } - } - - /** - * - * @param apiAddressLineList - * @param modelAddressLineList - * @param modelAddress - * - * @param contactId - * @throws DispositionReportFaultMessage - */ - public static void mapAddressLines(List apiAddressLineList, - List modelAddressLineList, - org.apache.juddi.model.Address modelAddress, - Long contactId) - throws DispositionReportFaultMessage { - modelAddressLineList.clear(); - - for (org.uddi.api_v3.AddressLine apiAddressLine : apiAddressLineList) { - modelAddressLineList.add(new org.apache.juddi.model.AddressLine(modelAddress, apiAddressLine.getValue(), apiAddressLine.getKeyName(), apiAddressLine.getKeyValue())); - } - } - - /** - * - * @param apiIdentifierBag - * @param modelIdentifierList - * @param modelBusinessEntity - * @throws DispositionReportFaultMessage - */ - public static void mapBusinessIdentifiers(org.uddi.api_v3.IdentifierBag apiIdentifierBag, - List modelIdentifierList, - org.apache.juddi.model.BusinessEntity modelBusinessEntity) - throws DispositionReportFaultMessage { - modelIdentifierList.clear(); - - if (apiIdentifierBag != null) { - List apiKeyedRefList = apiIdentifierBag.getKeyedReference(); - for (org.uddi.api_v3.KeyedReference apiKeyedRef : apiKeyedRefList) { - modelIdentifierList.add(new org.apache.juddi.model.BusinessIdentifier(modelBusinessEntity, apiKeyedRef.getTModelKey(), apiKeyedRef.getKeyName(), apiKeyedRef.getKeyValue())); - } - } - } - - /** - * - * @param apiBusinessServices - * @param modelBusinessServiceList - * @param modelServiceProjectionList - * @param modelBusinessEntity - * @throws DispositionReportFaultMessage - */ - public static void mapBusinessServices(org.uddi.api_v3.BusinessServices apiBusinessServices, - List modelBusinessServiceList, - List modelServiceProjectionList, - org.apache.juddi.model.BusinessEntity modelBusinessEntity) - throws DispositionReportFaultMessage { - modelBusinessServiceList.clear(); - if (apiBusinessServices != null) { - List apiBusinessServiceList = apiBusinessServices.getBusinessService(); - for (org.uddi.api_v3.BusinessService apiBusinessService : apiBusinessServiceList) { - org.apache.juddi.model.BusinessService modelBusinessService = new org.apache.juddi.model.BusinessService(); - - // If the parent businessEntity key and the service businessEntity key (if provided) do not match, it's a projection. - if (apiBusinessService.getBusinessKey() != null && apiBusinessService.getBusinessKey().length() > 0 - && !modelBusinessEntity.getEntityKey().equalsIgnoreCase(apiBusinessService.getBusinessKey())) { - - modelBusinessService.setEntityKey(apiBusinessService.getServiceKey()); - org.apache.juddi.model.ServiceProjection modelServiceProjection = new org.apache.juddi.model.ServiceProjection(modelBusinessEntity, modelBusinessService); - - modelServiceProjectionList.add(modelServiceProjection); - } else { - mapBusinessService(apiBusinessService, modelBusinessService, modelBusinessEntity); - modelBusinessServiceList.add(modelBusinessService); - } - } - } - } - - /** - * - * @param apiBusinessService - * @param modelBusinessService - * @param modelBusinessEntity - * @throws DispositionReportFaultMessage - */ - public static void mapBusinessService(org.uddi.api_v3.BusinessService apiBusinessService, - org.apache.juddi.model.BusinessService modelBusinessService, - org.apache.juddi.model.BusinessEntity modelBusinessEntity) - throws DispositionReportFaultMessage { - - modelBusinessService.setBusinessEntity(modelBusinessEntity); - modelBusinessService.setEntityKey(apiBusinessService.getServiceKey()); - - mapServiceNames(apiBusinessService.getName(), modelBusinessService.getServiceNames(), modelBusinessService); - mapServiceDescriptions(apiBusinessService.getDescription(), modelBusinessService.getServiceDescrs(), modelBusinessService); - if (apiBusinessService.getCategoryBag() != null) { - modelBusinessService.setCategoryBag(new org.apache.juddi.model.ServiceCategoryBag(modelBusinessService)); - mapCategoryBag(apiBusinessService.getCategoryBag(), modelBusinessService.getCategoryBag()); - } - - mapBindingTemplates(apiBusinessService.getBindingTemplates(), modelBusinessService.getBindingTemplates(), modelBusinessService); - mapBusinessServiceSignature(apiBusinessService.getSignature(), modelBusinessService); - } - - /** - * - * @param apiNameList - * @param modelNameList - * @param modelBusinessService - * @throws DispositionReportFaultMessage - */ - public static void mapServiceNames(List apiNameList, - List modelNameList, - org.apache.juddi.model.BusinessService modelBusinessService) - throws DispositionReportFaultMessage { - modelNameList.clear(); - - for (org.uddi.api_v3.Name apiName : apiNameList) { - modelNameList.add(new org.apache.juddi.model.ServiceName(modelBusinessService, apiName.getLang(), apiName.getValue())); - } - } - - /** - * - * @param apiDescList - * @param modelDescList - * @param modelBusinessService - * @throws DispositionReportFaultMessage - */ - public static void mapServiceDescriptions(List apiDescList, - List modelDescList, - org.apache.juddi.model.BusinessService modelBusinessService) - throws DispositionReportFaultMessage { - modelDescList.clear(); - - for (org.uddi.api_v3.Description apiDesc : apiDescList) { - modelDescList.add(new org.apache.juddi.model.ServiceDescr(modelBusinessService, apiDesc.getLang(), apiDesc.getValue())); - } - } - - /** - * - * @param apiBindingTemplates - * @param modelBindingTemplateList - * @param modelBusinessService - * @throws DispositionReportFaultMessage - */ - public static void mapBindingTemplates(org.uddi.api_v3.BindingTemplates apiBindingTemplates, - List modelBindingTemplateList, - org.apache.juddi.model.BusinessService modelBusinessService) - throws DispositionReportFaultMessage { - modelBindingTemplateList.clear(); - - if (apiBindingTemplates != null) { - List apiBindingTemplateList = apiBindingTemplates.getBindingTemplate(); - for (org.uddi.api_v3.BindingTemplate apiBindingTemplate : apiBindingTemplateList) { - org.apache.juddi.model.BindingTemplate modelBindingTemplate = new org.apache.juddi.model.BindingTemplate(); - - mapBindingTemplate(apiBindingTemplate, modelBindingTemplate, modelBusinessService); - - modelBindingTemplateList.add(modelBindingTemplate); - } - } - } - - /** - * - * @param apiBindingTemplate - * @param modelBindingTemplate - * @param modelBusinessService - * @throws DispositionReportFaultMessage - */ - public static void mapBindingTemplate(org.uddi.api_v3.BindingTemplate apiBindingTemplate, - org.apache.juddi.model.BindingTemplate modelBindingTemplate, - org.apache.juddi.model.BusinessService modelBusinessService) - throws DispositionReportFaultMessage { - - modelBindingTemplate.setBusinessService(modelBusinessService); - modelBindingTemplate.setEntityKey(apiBindingTemplate.getBindingKey()); - if (apiBindingTemplate.getAccessPoint() != null) { - modelBindingTemplate.setAccessPointType(apiBindingTemplate.getAccessPoint().getUseType()); - modelBindingTemplate.setAccessPointUrl(apiBindingTemplate.getAccessPoint().getValue()); - } - if (apiBindingTemplate.getHostingRedirector() != null) { - modelBindingTemplate.setHostingRedirector(apiBindingTemplate.getHostingRedirector().getBindingKey()); - } - - mapBindingDescriptions(apiBindingTemplate.getDescription(), modelBindingTemplate.getBindingDescrs(), modelBindingTemplate); - if (apiBindingTemplate.getCategoryBag() != null) { - modelBindingTemplate.setCategoryBag(new org.apache.juddi.model.BindingCategoryBag(modelBindingTemplate)); - mapCategoryBag(apiBindingTemplate.getCategoryBag(), modelBindingTemplate.getCategoryBag()); - } - mapTModelInstanceDetails(apiBindingTemplate.getTModelInstanceDetails(), modelBindingTemplate.getTmodelInstanceInfos(), modelBindingTemplate); - mapBindingTemplateSignatures(apiBindingTemplate.getSignature(), modelBindingTemplate); - } - - /** - * - * @param apiDescList - * @param modelDescList - * @param modelBindingTemplate - * @throws DispositionReportFaultMessage - */ - public static void mapBindingDescriptions(List apiDescList, - List modelDescList, - org.apache.juddi.model.BindingTemplate modelBindingTemplate) - throws DispositionReportFaultMessage { - modelDescList.clear(); - for (org.uddi.api_v3.Description apiDesc : apiDescList) { - modelDescList.add(new org.apache.juddi.model.BindingDescr(modelBindingTemplate, apiDesc.getLang(), apiDesc.getValue())); - } - } - - /** - * - * @param apiCategoryBag - * @param modelCategoryBag - * @throws DispositionReportFaultMessage - */ - public static void mapCategoryBag(org.uddi.api_v3.CategoryBag apiCategoryBag, - org.apache.juddi.model.CategoryBag modelCategoryBag) - throws DispositionReportFaultMessage { - - if (apiCategoryBag != null) { - List krList = apiCategoryBag.getKeyedReference(); - for (Object elem : krList) { - if (elem instanceof org.uddi.api_v3.KeyedReference) { - List modelKeyedReferences = modelCategoryBag.getKeyedReferences(); - //modelKeyedReferences.clear(); - org.uddi.api_v3.KeyedReference apiKeyedReference = (org.uddi.api_v3.KeyedReference) elem; - modelKeyedReferences.add(new org.apache.juddi.model.KeyedReference(modelCategoryBag, - apiKeyedReference.getTModelKey(), apiKeyedReference.getKeyName(), apiKeyedReference.getKeyValue())); - } - } - List krgList = apiCategoryBag.getKeyedReferenceGroup(); - for (org.uddi.api_v3.KeyedReferenceGroup elem : krgList) { - if (elem instanceof org.uddi.api_v3.KeyedReferenceGroup) { - org.uddi.api_v3.KeyedReferenceGroup apiKeyedReferenceGroup = (org.uddi.api_v3.KeyedReferenceGroup) elem; - - org.apache.juddi.model.KeyedReferenceGroup modelKeyedReferenceGroup = new org.apache.juddi.model.KeyedReferenceGroup(); - List modelKeyedReferenceGroups = modelCategoryBag.getKeyedReferenceGroups(); - //modelKeyedReferenceGroups.clear(); - - mapKeyedReferenceGroup(apiKeyedReferenceGroup, modelKeyedReferenceGroup, modelCategoryBag); - - modelKeyedReferenceGroups.add(modelKeyedReferenceGroup); - } - } - } - } - - /** - * - * @param apiKeyedReferenceGroup - * @param modelKeyedReferenceGroup - * @param modelCategoryBag - * @throws DispositionReportFaultMessage - */ - public static void mapKeyedReferenceGroup(org.uddi.api_v3.KeyedReferenceGroup apiKeyedReferenceGroup, - org.apache.juddi.model.KeyedReferenceGroup modelKeyedReferenceGroup, - org.apache.juddi.model.CategoryBag modelCategoryBag) - throws DispositionReportFaultMessage { - if (apiKeyedReferenceGroup != null) { - modelKeyedReferenceGroup.setCategoryBag(modelCategoryBag); - modelKeyedReferenceGroup.setTmodelKey(apiKeyedReferenceGroup.getTModelKey()); - - if (apiKeyedReferenceGroup.getKeyedReference() != null) { - List modelKeyedReferences = modelKeyedReferenceGroup.getKeyedReferences(); - for (org.uddi.api_v3.KeyedReference apiKeyedReference : apiKeyedReferenceGroup.getKeyedReference()) { - modelKeyedReferences.add(new org.apache.juddi.model.KeyedReference(modelKeyedReferenceGroup, - apiKeyedReference.getTModelKey(), apiKeyedReference.getKeyName(), apiKeyedReference.getKeyValue())); - } - } - - } - - } - - /** - * - * @param apiTModelInstDetails - * @param modelTModelInstInfoList - * @param modelBindingTemplate - * @throws DispositionReportFaultMessage - */ - public static void mapTModelInstanceDetails(org.uddi.api_v3.TModelInstanceDetails apiTModelInstDetails, - List modelTModelInstInfoList, - org.apache.juddi.model.BindingTemplate modelBindingTemplate) - throws DispositionReportFaultMessage { - modelTModelInstInfoList.clear(); - - if (apiTModelInstDetails != null) { - List apiTModelInstInfoList = apiTModelInstDetails.getTModelInstanceInfo(); - for (org.uddi.api_v3.TModelInstanceInfo apiTModelInstInfo : apiTModelInstInfoList) { - org.apache.juddi.model.TmodelInstanceInfo modelTModelInstInfo = new org.apache.juddi.model.TmodelInstanceInfo(modelBindingTemplate, apiTModelInstInfo.getTModelKey()); - - mapTModelInstanceInfoDescriptions(apiTModelInstInfo.getDescription(), modelTModelInstInfo.getTmodelInstanceInfoDescrs(), modelTModelInstInfo); - mapInstanceDetails(apiTModelInstInfo.getInstanceDetails(), modelTModelInstInfo); - - modelTModelInstInfoList.add(modelTModelInstInfo); - } - } - } - - /** - * - * @param apiDescList - * @param modelDescList - * @param modelTModelInstInfo - * @throws DispositionReportFaultMessage - */ - public static void mapTModelInstanceInfoDescriptions(List apiDescList, - List modelDescList, - org.apache.juddi.model.TmodelInstanceInfo modelTModelInstInfo) - throws DispositionReportFaultMessage { - modelDescList.clear(); - - for (org.uddi.api_v3.Description apiDesc : apiDescList) { - modelDescList.add(new org.apache.juddi.model.TmodelInstanceInfoDescr(modelTModelInstInfo, apiDesc.getLang(), apiDesc.getValue())); - } - } - - /** - * - * @param apiInstanceDetails - * @param modelTmodelInstInfo - * @throws DispositionReportFaultMessage - */ - public static void mapInstanceDetails(org.uddi.api_v3.InstanceDetails apiInstanceDetails, - org.apache.juddi.model.TmodelInstanceInfo modelTmodelInstInfo) - throws DispositionReportFaultMessage { - modelTmodelInstInfo.getInstanceDetailsDescrs().clear(); - - if (apiInstanceDetails != null) { - List descriptions = apiInstanceDetails.getDescription(); - List overviewdocs = apiInstanceDetails.getOverviewDoc(); - for (org.uddi.api_v3.Description apiDesc : descriptions) { - org.apache.juddi.model.InstanceDetailsDescr modelInstanceDetailsDescr - = new org.apache.juddi.model.InstanceDetailsDescr( - modelTmodelInstInfo, apiDesc.getLang(), apiDesc.getValue()); - modelTmodelInstInfo.getInstanceDetailsDescrs().add(modelInstanceDetailsDescr); - } - for (org.uddi.api_v3.OverviewDoc apiOverviewDoc : overviewdocs) { - org.apache.juddi.model.OverviewDoc modelOverviewDoc = new org.apache.juddi.model.OverviewDoc(modelTmodelInstInfo); - mapOverviewDoc(apiOverviewDoc, modelOverviewDoc); - modelTmodelInstInfo.getOverviewDocs().add(modelOverviewDoc); - } - modelTmodelInstInfo.setInstanceParms((String) apiInstanceDetails.getInstanceParms()); - } - } - - /** - * - * @param apiOverviewDoc - * @param modelOverviewDoc - * @throws DispositionReportFaultMessage - */ - public static void mapOverviewDoc(org.uddi.api_v3.OverviewDoc apiOverviewDoc, - org.apache.juddi.model.OverviewDoc modelOverviewDoc) - throws DispositionReportFaultMessage { - if (apiOverviewDoc != null) { - - List descContent = apiOverviewDoc.getDescription(); - for (Object elem : descContent) { - org.uddi.api_v3.Description description = (org.uddi.api_v3.Description) elem; - if (description != null) { - org.apache.juddi.model.OverviewDocDescr modelOverviewDocDescr = new org.apache.juddi.model.OverviewDocDescr( - modelOverviewDoc, description.getLang(), description.getValue()); - modelOverviewDoc.getOverviewDocDescrs().add(modelOverviewDocDescr); - } - } - - org.uddi.api_v3.OverviewURL elem = apiOverviewDoc.getOverviewURL(); - if (elem instanceof org.uddi.api_v3.OverviewURL) { - org.uddi.api_v3.OverviewURL overviewURL = elem; - modelOverviewDoc.setOverviewUrl(overviewURL.getValue()); - modelOverviewDoc.setOverviewUrlUseType(overviewURL.getUseType()); - } - - } - } - - /** - * - * @param apiTModel - * @param modelTModel - * @throws DispositionReportFaultMessage - */ - public static void mapTModel(org.uddi.api_v3.TModel apiTModel, - org.apache.juddi.model.Tmodel modelTModel) - throws DispositionReportFaultMessage { - - modelTModel.setEntityKey(apiTModel.getTModelKey()); - modelTModel.setName(apiTModel.getName().getValue()); - modelTModel.setLangCode(apiTModel.getName().getLang()); - modelTModel.setDeleted(apiTModel.isDeleted()); - - mapTModelDescriptions(apiTModel.getDescription(), modelTModel.getTmodelDescrs(), modelTModel); - mapTModelIdentifiers(apiTModel.getIdentifierBag(), modelTModel.getTmodelIdentifiers(), modelTModel); - if (apiTModel.getCategoryBag() != null) { - modelTModel.setCategoryBag(new org.apache.juddi.model.TmodelCategoryBag(modelTModel)); - mapCategoryBag(apiTModel.getCategoryBag(), modelTModel.getCategoryBag()); - } - mapTModelOverviewDocs(apiTModel.getOverviewDoc(), modelTModel.getOverviewDocs(), modelTModel); - mapTmodelSignatures(apiTModel.getSignature(), modelTModel); - } - - /** - * - * @param apiDescList - * @param modelDescList - * @param modelTModel - * @throws DispositionReportFaultMessage - */ - public static void mapTModelDescriptions(List apiDescList, - List modelDescList, - org.apache.juddi.model.Tmodel modelTModel) - throws DispositionReportFaultMessage { - modelDescList.clear(); - - for (org.uddi.api_v3.Description apiDesc : apiDescList) { - modelDescList.add(new org.apache.juddi.model.TmodelDescr(modelTModel, apiDesc.getLang(), apiDesc.getValue())); - } - } - - /** - * - * @param apiIdentifierBag - * @param modelIdentifierList - * @param modelTModel - * @throws DispositionReportFaultMessage - */ - public static void mapTModelIdentifiers(org.uddi.api_v3.IdentifierBag apiIdentifierBag, - List modelIdentifierList, - org.apache.juddi.model.Tmodel modelTModel) - throws DispositionReportFaultMessage { - modelIdentifierList.clear(); - - if (apiIdentifierBag != null) { - List apiKeyedRefList = apiIdentifierBag.getKeyedReference(); - for (org.uddi.api_v3.KeyedReference apiKeyedRef : apiKeyedRefList) { - modelIdentifierList.add(new org.apache.juddi.model.TmodelIdentifier(modelTModel, apiKeyedRef.getTModelKey(), apiKeyedRef.getKeyName(), apiKeyedRef.getKeyValue())); - } - } - } - - /** - * - * @param apiOverviewDocList - * @param modelOverviewDocList - * @param modelTmodel - * @throws DispositionReportFaultMessage - */ - public static void mapTModelOverviewDocs(List apiOverviewDocList, - List modelOverviewDocList, - org.apache.juddi.model.Tmodel modelTmodel) - throws DispositionReportFaultMessage { - modelOverviewDocList.clear(); - - for (org.uddi.api_v3.OverviewDoc apiOverviewDoc : apiOverviewDocList) { - org.apache.juddi.model.OverviewDoc modelOverviewDoc = new org.apache.juddi.model.OverviewDoc(modelTmodel); - mapOverviewDoc(apiOverviewDoc, modelOverviewDoc); - modelTmodel.getOverviewDocs().add(modelOverviewDoc); - } - } - - /** - * note that when using this, it does not reference the instance of the - * specific businesses, it will create new ones. be sure to overwrite - * them with the correct references - * - * @param apiPubAssertion - * @param modelPubAssertion - * @throws DispositionReportFaultMessage - */ - public static void mapPublisherAssertion(org.uddi.api_v3.PublisherAssertion apiPubAssertion, - org.apache.juddi.model.PublisherAssertion modelPubAssertion) - throws DispositionReportFaultMessage { - - modelPubAssertion.setId(new org.apache.juddi.model.PublisherAssertionId(apiPubAssertion.getFromKey(), apiPubAssertion.getToKey())); - - org.apache.juddi.model.BusinessEntity beFrom = new org.apache.juddi.model.BusinessEntity(); - beFrom.setEntityKey(apiPubAssertion.getFromKey()); - modelPubAssertion.setBusinessEntityByFromKey(beFrom); - - org.apache.juddi.model.BusinessEntity beTo = new org.apache.juddi.model.BusinessEntity(); - beFrom.setEntityKey(apiPubAssertion.getToKey()); - modelPubAssertion.setBusinessEntityByToKey(beTo); - - org.uddi.api_v3.KeyedReference apiKeyedRef = apiPubAssertion.getKeyedReference(); - if (apiKeyedRef != null) { - modelPubAssertion.setTmodelKey(apiKeyedRef.getTModelKey()); - modelPubAssertion.setKeyName(apiKeyedRef.getKeyName()); - modelPubAssertion.setKeyValue(apiKeyedRef.getKeyValue()); - } - if (!apiPubAssertion.getSignature().isEmpty()) { - modelPubAssertion.setSignatures(mapApiSignaturesToModelSignatures(apiPubAssertion.getSignature())); - for (Signature s : modelPubAssertion.getSignatures()) { - s.setPublisherAssertionFromKey(modelPubAssertion.getBusinessEntityByFromKey().getEntityKey()); - s.setPublisherAssertionToKey(modelPubAssertion.getBusinessEntityByToKey().getEntityKey()); - - } - - } - } - - /** - * - * @param apiSubscription - * @param modelSubscription - * @throws DispositionReportFaultMessage - */ - public static void mapSubscription(org.uddi.sub_v3.Subscription apiSubscription, - org.apache.juddi.model.Subscription modelSubscription) - throws DispositionReportFaultMessage { - - modelSubscription.setSubscriptionKey(apiSubscription.getSubscriptionKey()); - modelSubscription.setBindingKey(apiSubscription.getBindingKey()); - if (apiSubscription.getNotificationInterval() != null) { - modelSubscription.setNotificationInterval(apiSubscription.getNotificationInterval().toString()); - } - modelSubscription.setMaxEntities(apiSubscription.getMaxEntities()); - if (apiSubscription.getExpiresAfter() != null) { - GregorianCalendar gc = apiSubscription.getExpiresAfter().toGregorianCalendar(); - modelSubscription.setExpiresAfter(new Date(gc.getTimeInMillis())); - } - - if (apiSubscription.isBrief() != null) { - modelSubscription.setBrief(apiSubscription.isBrief()); - } else { - modelSubscription.setBrief(Boolean.FALSE); - } - - String rawFilter = JAXBMarshaller.marshallToString(new ObjectFactory().createSubscriptionFilter(apiSubscription.getSubscriptionFilter()), "org.uddi.sub_v3"); - logger.debug("marshalled subscription filter: " + rawFilter); - modelSubscription.setSubscriptionFilter(rawFilter); - - } - - /** - * - * @param apiClientSubscriptionInfo - * @param modelClientSubscriptionInfo - * @throws DispositionReportFaultMessage - */ - public static void mapClientSubscriptionInfo(org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo, - org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo) - throws DispositionReportFaultMessage { - - modelClientSubscriptionInfo.setLastNotified(new Date()); - modelClientSubscriptionInfo.setSubscriptionKey(apiClientSubscriptionInfo.getSubscriptionKey()); - if (apiClientSubscriptionInfo.getFromClerk() != null) { - org.apache.juddi.model.Clerk modelClerk = new org.apache.juddi.model.Clerk(); - mapClerk(apiClientSubscriptionInfo.getFromClerk(), modelClerk); - modelClientSubscriptionInfo.setFromClerk(modelClerk); - } - if (apiClientSubscriptionInfo.getToClerk() != null) { - org.apache.juddi.model.Clerk modelToClerk = new org.apache.juddi.model.Clerk(); - mapClerk(apiClientSubscriptionInfo.getToClerk(), modelToClerk); - modelClientSubscriptionInfo.setToClerk(modelToClerk); - } - - } - - /** - * - * @param apiClerk - * @param modelClerk - */ - public static void mapClerk(org.apache.juddi.api_v3.Clerk apiClerk, org.apache.juddi.model.Clerk modelClerk) { - if (apiClerk != null) { - - modelClerk.setClerkName(apiClerk.getName()); - modelClerk.setCred(apiClerk.getPassword()); - modelClerk.setPublisherId(apiClerk.getPublisher()); - if (apiClerk.getNode() != null) { - org.apache.juddi.model.Node modelNode = new org.apache.juddi.model.Node(); - mapNode(apiClerk.getNode(), modelNode); - modelClerk.setNode(modelNode.getName()); - } - } - } - - /** - * - * @param apiNode - * @param modelNode - */ - public static void mapNode(org.apache.juddi.api_v3.Node apiNode, org.apache.juddi.model.Node modelNode) { - if (apiNode != null) { - - modelNode.setCustodyTransferUrl(apiNode.getCustodyTransferUrl()); - modelNode.setInquiryUrl(apiNode.getInquiryUrl()); - modelNode.setJuddiApiUrl(apiNode.getJuddiApiUrl()); - modelNode.setName(apiNode.getName()); - modelNode.setClientName(apiNode.getClientName()); - modelNode.setProxyTransport(apiNode.getProxyTransport()); - modelNode.setPublishUrl(apiNode.getPublishUrl()); - modelNode.setSecurityUrl(apiNode.getSecurityUrl()); - modelNode.setSubscriptionUrl(apiNode.getSubscriptionUrl()); - modelNode.setSubscriptionListenerUrl(apiNode.getSubscriptionListenerUrl()); - modelNode.setReplicationUrl(apiNode.getReplicationUrl()); - modelNode.setFactoryInitial(apiNode.getFactoryInitial()); - modelNode.setFactoryNamingProvider(apiNode.getFactoryNamingProvider()); - modelNode.setFactoryURLPkgs(apiNode.getFactoryURLPkgs()); - } - } - - private static Reference mapReference(SignedInfo modelSignedInfo, ReferenceType apiReference) { - Reference ref = new Reference(); - ref.setSignedInfo(modelSignedInfo); - String refUri = apiReference.getURI(); - if (refUri == null) { - refUri = ""; - } - ref.setUri(refUri); - List apiTransformList = apiReference.getTransforms().getTransform(); - for (org.w3._2000._09.xmldsig_.TransformType apiTransform : apiTransformList) { - SignatureTransform modelTransform = new SignatureTransform(); - modelTransform.setReference(ref); - modelTransform.setTransform(apiTransform.getAlgorithm()); - - for (Object xform : apiTransform.getContent()) { - SignatureTransformDataValue sdv = mapSignatureTransformDataValue(xform); - sdv.setSignatureTransform(modelTransform); - modelTransform.getSignatureTransformDataValue().add(sdv); - } - - ref.getTransforms().add(modelTransform); - } - String digestMethodStr = apiReference.getDigestMethod().getAlgorithm(); - byte[] digestValueBytes = apiReference.getDigestValue(); - ref.setDigestMethod(digestMethodStr); - ref.setDigestValue(digestValueBytes); - return ref; - } - - private static KeyDataValue mapX509DataType(JAXBElement apiKeyInfoContentJAXB, KeyInfo modelKeyInfo) throws RuntimeException { - X509DataType apiKeyInfoContent = (X509DataType) apiKeyInfoContentJAXB.getValue(); - KeyDataValue modelX509KeyData = new KeyDataValue(); - modelX509KeyData.setKeyDataType(X509DataType.class.getSimpleName()); - modelX509KeyData.setKeyDataName(apiKeyInfoContentJAXB.getName().getLocalPart()); - modelX509KeyData.setKeyInfo(modelKeyInfo); - List x509IssuerSerialOrX509SKIOrX509SubjectNameList = apiKeyInfoContent.getX509IssuerSerialOrX509SKIOrX509SubjectName(); - for (Object x509IssuerSerialOrX509SKIOrX509SubjectNameObj : x509IssuerSerialOrX509SKIOrX509SubjectNameList) { - JAXBElement x509IssuerSerialOrX509SKIOrX509SubjectNameJAXB = (JAXBElement) x509IssuerSerialOrX509SKIOrX509SubjectNameObj; - String tagName = x509IssuerSerialOrX509SKIOrX509SubjectNameJAXB.getName().getLocalPart(); - Object x509IssuerSerialOrX509SKIOrX509SubjectName = x509IssuerSerialOrX509SKIOrX509SubjectNameJAXB.getValue(); - - KeyDataValue modelKeyInfoValue = new KeyDataValue(); - modelKeyInfoValue.setKeyDataName(tagName); - if (x509IssuerSerialOrX509SKIOrX509SubjectName instanceof byte[]) { - modelKeyInfoValue.setKeyDataValueBytes((byte[]) x509IssuerSerialOrX509SKIOrX509SubjectName); - } else if (x509IssuerSerialOrX509SKIOrX509SubjectName instanceof String) { - modelKeyInfoValue.setKeyDataValueString((String) x509IssuerSerialOrX509SKIOrX509SubjectName); - } else if (x509IssuerSerialOrX509SKIOrX509SubjectName instanceof X509IssuerSerialType) { - modelKeyInfoValue.setKeyDataType(X509IssuerSerialType.class.getSimpleName()); - X509IssuerSerialType x509IssuerSerialType = (X509IssuerSerialType) x509IssuerSerialOrX509SKIOrX509SubjectName; - modelKeyInfoValue.setKeyDataValueString(x509IssuerSerialType.getX509IssuerName()); - modelKeyInfoValue.setKeyDataValueBytes(x509IssuerSerialType.getX509SerialNumber().toByteArray()); - } else if (x509IssuerSerialOrX509SKIOrX509SubjectName != null) { - throw new RuntimeException("Unrecognized Value for Element: " + tagName + ": " + x509IssuerSerialOrX509SKIOrX509SubjectName.getClass().getCanonicalName()); - } - modelKeyInfoValue.setKeyDataValue(modelX509KeyData); - modelX509KeyData.getKeyDataValueList().add(modelKeyInfoValue); - } - return modelX509KeyData; - } - - private static KeyDataValue mapKeyName(JAXBElement apiKeyInfoContentJAXB) { - KeyDataValue modelKeyNameKDV = new KeyDataValue(); - modelKeyNameKDV.setKeyDataType(String.class.getSimpleName()); - modelKeyNameKDV.setKeyDataName(apiKeyInfoContentJAXB.getName().getLocalPart()); - modelKeyNameKDV.setKeyDataValueString((String) apiKeyInfoContentJAXB.getValue()); - return modelKeyNameKDV; - } - - private static KeyDataValue mapKeyValue(JAXBElement apiKeyInfoContentJAXB, List keyInfoDataValues) { - KeyValueType kvt = (KeyValueType) apiKeyInfoContentJAXB.getValue(); - KeyDataValue modelKeyValueKDV = new KeyDataValue(); - modelKeyValueKDV.setKeyDataType(KeyValueType.class.getSimpleName()); - modelKeyValueKDV.setKeyDataName(apiKeyInfoContentJAXB.getName().getLocalPart()); - keyInfoDataValues.add(modelKeyValueKDV); - List kvObjList = kvt.getContent(); - for (Object kvObj : kvObjList) { - if (kvObj instanceof JAXBElement) { - JAXBElement kvJAXB = (JAXBElement) kvObj; - Object childVal = kvJAXB.getValue(); - - KeyDataValue childKDV = new KeyDataValue(); - childKDV.setKeyDataValue(modelKeyValueKDV); - childKDV.setKeyDataName(kvJAXB.getName().getLocalPart()); - childKDV.setKeyDataType(childVal.getClass().getSimpleName()); - modelKeyValueKDV.getKeyDataValueList().add(childKDV); - - if (childVal instanceof DSAKeyValueType) { - DSAKeyValueType dsaKeyVal = (DSAKeyValueType) childVal; - String dsaKeyValueTagName = kvJAXB.getName().getLocalPart(); - KeyDataValue dsaKeyValKDV = new KeyDataValue(null, DSAKeyValueType.class.getSimpleName(), dsaKeyValueTagName, null, null, childKDV); - childKDV.getKeyDataValueList().add(dsaKeyValKDV); - - KeyDataValue gValKDV = new KeyDataValue(null, byte[].class.getSimpleName(), "G", dsaKeyVal.getG(), null, dsaKeyValKDV); - dsaKeyValKDV.getKeyDataValueList().add(gValKDV); - - KeyDataValue jValKDV = new KeyDataValue(null, byte[].class.getSimpleName(), "J", dsaKeyVal.getJ(), null, dsaKeyValKDV); - dsaKeyValKDV.getKeyDataValueList().add(jValKDV); - - KeyDataValue pValKDV = new KeyDataValue(null, byte[].class.getSimpleName(), "P", dsaKeyVal.getP(), null, dsaKeyValKDV); - dsaKeyValKDV.getKeyDataValueList().add(pValKDV); - - KeyDataValue pGenCounterValKDV = new KeyDataValue(null, byte[].class.getSimpleName(), "PgenCounter", dsaKeyVal.getPgenCounter(), null, dsaKeyValKDV); - dsaKeyValKDV.getKeyDataValueList().add(pGenCounterValKDV); - - KeyDataValue qValKDV = new KeyDataValue(null, byte[].class.getSimpleName(), "Q", dsaKeyVal.getQ(), null, dsaKeyValKDV); - dsaKeyValKDV.getKeyDataValueList().add(qValKDV); - - KeyDataValue seedValKDV = new KeyDataValue(null, byte[].class.getSimpleName(), "Seed", dsaKeyVal.getSeed(), null, dsaKeyValKDV); - dsaKeyValKDV.getKeyDataValueList().add(seedValKDV); - - KeyDataValue yValKDV = new KeyDataValue(null, byte[].class.getSimpleName(), "Y", dsaKeyVal.getY(), null, dsaKeyValKDV); - dsaKeyValKDV.getKeyDataValueList().add(yValKDV); - } else if (childVal instanceof RSAKeyValueType) { - RSAKeyValueType rsaKeyVal = (RSAKeyValueType) childVal; - String rsaKeyValueTagName = kvJAXB.getName().getLocalPart(); - KeyDataValue rsaKeyValKDV = new KeyDataValue(null, RSAKeyValueType.class.getSimpleName(), rsaKeyValueTagName, null, null, childKDV); - childKDV.getKeyDataValueList().add(rsaKeyValKDV); - - KeyDataValue exponentValKDV = new KeyDataValue(null, byte[].class.getSimpleName(), "Exponent", rsaKeyVal.getExponent(), null, rsaKeyValKDV); - rsaKeyValKDV.getKeyDataValueList().add(exponentValKDV); - - KeyDataValue modulusValKDV = new KeyDataValue(null, byte[].class.getSimpleName(), "Modulus", rsaKeyVal.getModulus(), null, rsaKeyValKDV); - rsaKeyValKDV.getKeyDataValueList().add(modulusValKDV); - } - } - } - return modelKeyValueKDV; - } - - private static KeyDataValue mapRetrievalMethod(String apiKeyInfoContentTagName, KeyInfo modelKeyInfo, RetrievalMethodType retrievalMethodType) { - KeyDataValue retrievalMethodTypeKDV = new KeyDataValue(); - retrievalMethodTypeKDV.setKeyDataName(apiKeyInfoContentTagName); - retrievalMethodTypeKDV.setKeyDataType(RetrievalMethodType.class.getSimpleName()); - retrievalMethodTypeKDV.setKeyInfo(modelKeyInfo); - KeyDataValue uriKDV = new KeyDataValue(); - uriKDV.setKeyDataName("URI"); - uriKDV.setKeyDataType(String.class.getSimpleName()); - uriKDV.setKeyDataValue(retrievalMethodTypeKDV); - uriKDV.setKeyDataValueString(retrievalMethodType.getURI()); - retrievalMethodTypeKDV.getKeyDataValueList().add(uriKDV); - KeyDataValue typeKDV = new KeyDataValue(); - typeKDV.setKeyDataName("Type"); - typeKDV.setKeyDataType(String.class.getSimpleName()); - typeKDV.setKeyDataValue(retrievalMethodTypeKDV); - typeKDV.setKeyDataValueString(retrievalMethodType.getType()); - retrievalMethodTypeKDV.getKeyDataValueList().add(typeKDV); - TransformsType transformsType = retrievalMethodType.getTransforms(); - if (transformsType != null) { - List tTypeList = transformsType.getTransform(); - for (TransformType tType : tTypeList) { - KeyDataValue transformKDV = new KeyDataValue(); - transformKDV.setKeyDataName("Transform"); - transformKDV.setKeyDataType(String.class.getSimpleName()); - transformKDV.setKeyDataValue(retrievalMethodTypeKDV); - transformKDV.setKeyDataValueString(tType.getAlgorithm()); - - for (Object xform : tType.getContent()) { - SignatureTransformDataValue stdv = mapSignatureTransformDataValue(xform); - KeyDataValue transformContentKDV = new KeyDataValue(); - transformContentKDV.setKeyDataType(stdv.getContentType()); - transformContentKDV.setKeyDataValueBytes(stdv.getContentBytes()); - transformContentKDV.setKeyDataValue(transformKDV); - transformKDV.getKeyDataValueList().add(transformContentKDV); - } - - retrievalMethodTypeKDV.getKeyDataValueList().add(transformKDV); - } - } - return retrievalMethodTypeKDV; - } - - private static KeyDataValue mapPGPDataType(String apiKeyInfoContentTagName, KeyInfo modelKeyInfo, PGPDataType pgpDataType) { - KeyDataValue pgpDataTypeKDV = new KeyDataValue(); - pgpDataTypeKDV.setKeyDataName(apiKeyInfoContentTagName); - pgpDataTypeKDV.setKeyDataType(PGPDataType.class.getSimpleName()); - pgpDataTypeKDV.setKeyInfo(modelKeyInfo); - - List pgpDataValues = pgpDataType.getContent(); - for (Object pgpDataValue : pgpDataValues) { - if (pgpDataValue instanceof JAXBElement) { - JAXBElement pgpDataJAXB = (JAXBElement) pgpDataValue; - String tagName = pgpDataJAXB.getName().getLocalPart(); - - KeyDataValue keyIDKDV = new KeyDataValue(); - keyIDKDV.setKeyDataName(tagName); - keyIDKDV.setKeyDataValue(pgpDataTypeKDV); - if (pgpDataJAXB.getValue() instanceof String) { - keyIDKDV.setKeyDataValueString((String) pgpDataJAXB.getValue()); - } else { - keyIDKDV.setKeyDataValueBytes((byte[]) pgpDataJAXB.getValue()); - } - pgpDataTypeKDV.getKeyDataValueList().add(keyIDKDV); - } - } - return pgpDataTypeKDV; - } - - private static KeyDataValue mapSPKIDataType(String apiKeyInfoContentTagName, KeyInfo modelKeyInfo, SPKIDataType spkiDataType) { - KeyDataValue spkiDataTypeKDV = new KeyDataValue(); - spkiDataTypeKDV.setKeyDataName(apiKeyInfoContentTagName); - spkiDataTypeKDV.setKeyDataType(SPKIDataType.class.getSimpleName()); - spkiDataTypeKDV.setKeyInfo(modelKeyInfo); - - List spkiDataValues = spkiDataType.getSPKISexpAndAny(); - for (Object spkiDataValue : spkiDataValues) { - if (spkiDataValue instanceof JAXBElement) { - JAXBElement spkiDataJAXB = (JAXBElement) spkiDataValue; - String tagName = spkiDataJAXB.getName().getLocalPart(); - - KeyDataValue keyIDKDV = new KeyDataValue(); - keyIDKDV.setKeyDataName(tagName); - keyIDKDV.setKeyDataValue(spkiDataTypeKDV); - if (spkiDataJAXB.getValue() instanceof String) { - keyIDKDV.setKeyDataValueString((String) spkiDataJAXB.getValue()); - } else { - keyIDKDV.setKeyDataValueBytes((byte[]) spkiDataJAXB.getValue()); - } - spkiDataTypeKDV.getKeyDataValueList().add(keyIDKDV); - } else { - throw new RuntimeException("Unrecognized type: " + spkiDataValue.getClass().getCanonicalName()); - } - } - return spkiDataTypeKDV; - } - - private static SignatureTransformDataValue mapSignatureTransformDataValue(Object xform) { - SignatureTransformDataValue sdv = new SignatureTransformDataValue(); - if (xform instanceof String) { - sdv.setContentType(String.class.getSimpleName()); - String xformStr = xform.toString(); - try { - byte[] xformBytes = xformStr.getBytes(AuthenticatedService.UTF8); - sdv.setContentBytes(xformBytes); - } catch (Exception e) { - throw new RuntimeException("Failed to encode string due to: " + e.getMessage(), e); - } - } else if (xform instanceof Element) { - sdv.setContentType(Element.class.getCanonicalName()); - Element xformEl = (Element) xform; - String str = serializeTransformElement(xformEl); - try { - sdv.setContentBytes(str.getBytes(AuthenticatedService.UTF8)); - } catch (Exception e) { - throw new RuntimeException("Failed to encode string due to: " + e.getMessage(), e); - } - } else if (xform instanceof byte[]) { - sdv.setContentType(byte[].class.getSimpleName()); - sdv.setContentBytes((byte[]) xform); - } else if (xform instanceof JAXBElement) { - sdv.setContentType(Element.class.getCanonicalName()); - JAXBElement xformJAXB = (JAXBElement) xform; - DOMResult domResult = new DOMResult(); - JAXB.marshal(xformJAXB, domResult); - Element xformEl = ((Document) domResult.getNode()).getDocumentElement(); - String str = serializeTransformElement(xformEl); - try { - sdv.setContentBytes(str.getBytes(AuthenticatedService.UTF8)); - } catch (Exception e) { - throw new RuntimeException("Failed to encode string due to: " + e.getMessage(), e); - } - } else { - throw new RuntimeException("Unrecognized type: " + xform.getClass().getCanonicalName()); - } - return sdv; - } - - private static String serializeTransformElement(Element xformEl) throws DOMException, LSException { - Document document = xformEl.getOwnerDocument(); - DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation(); - LSSerializer serializer = domImplLS.createLSSerializer(); -// serializer.getDomConfig().setParameter("namespaces", true); -// serializer.getDomConfig().setParameter("namespace-declarations", true); - serializer.getDomConfig().setParameter("canonical-form", false); - serializer.getDomConfig().setParameter("xml-declaration", false); - String str = serializer.writeToString(xformEl); - return str; - } - - public static org.apache.juddi.model.ChangeRecord mapChangeRecord(ChangeRecord rec) throws UnsupportedEncodingException { - org.apache.juddi.model.ChangeRecord r = new org.apache.juddi.model.ChangeRecord(); - //r.setId(rec.getChangeID().getOriginatingUSN()); - r.setOriginatingUSN(rec.getChangeID().getOriginatingUSN()); - if (r.getOriginatingUSN() == null) { - // logger.warn("strange, the getOriginatingUSN is null!!"); - // JAXB.marshal(rec, System.out); - // Thread.dumpStack(); - } - r.setNodeID(rec.getChangeID().getNodeID()); - if (rec.getChangeRecordNewData() != null) { - r.setRecordType(org.apache.juddi.model.ChangeRecord.RecordType.ChangeRecordNewData); - r.setEntityKey(rec.getChangeRecordNewData().getOperationalInfo().getEntityKey()); - if (rec.getChangeRecordNewData().getOperationalInfo().getEntityKey() == null) { - throw new UnsupportedEncodingException("entity key is null! make sure it's filled out before saving!"); - } - } else if (rec.getChangeRecordAcknowledgement() != null) { - r.setRecordType(org.apache.juddi.model.ChangeRecord.RecordType.ChangeRecordAcknowledgement); - } else if (rec.getChangeRecordConditionFailed() != null) { - r.setRecordType(org.apache.juddi.model.ChangeRecord.RecordType.ChangeRecordConditionFailed); - } else if (rec.getChangeRecordCorrection() != null) { - r.setRecordType(org.apache.juddi.model.ChangeRecord.RecordType.ChangeRecordCorrection); - } else if (rec.getChangeRecordDelete() != null) { - r.setRecordType(org.apache.juddi.model.ChangeRecord.RecordType.ChangeRecordDelete); - if (rec.getChangeRecordDelete().getTModelKey() != null) { - r.setEntityKey(rec.getChangeRecordDelete().getTModelKey()); - } - if (rec.getChangeRecordDelete().getBindingKey() != null) { - r.setEntityKey(rec.getChangeRecordDelete().getBindingKey()); - } - if (rec.getChangeRecordDelete().getBusinessKey() != null) { - r.setEntityKey(rec.getChangeRecordDelete().getBusinessKey()); - } - if (rec.getChangeRecordDelete().getServiceKey() != null) { - r.setEntityKey(rec.getChangeRecordDelete().getServiceKey()); - } - } else if (rec.getChangeRecordDeleteAssertion() != null) { - r.setRecordType(org.apache.juddi.model.ChangeRecord.RecordType.ChangeRecordDeleteAssertion); - } else if (rec.getChangeRecordHide() != null) { - r.setRecordType(org.apache.juddi.model.ChangeRecord.RecordType.ChangeRecordHide); - r.setEntityKey(rec.getChangeRecordHide().getTModelKey()); - } else if (rec.getChangeRecordNewDataConditional() != null) { - r.setRecordType(org.apache.juddi.model.ChangeRecord.RecordType.ChangeRecordNewDataConditional); - } else if (rec.getChangeRecordNull() != null) { - r.setRecordType(org.apache.juddi.model.ChangeRecord.RecordType.ChangeRecordNull); - } else if (rec.getChangeRecordPublisherAssertion() != null) { - r.setRecordType(org.apache.juddi.model.ChangeRecord.RecordType.ChangeRecordPublisherAssertion); - } else { - throw new UnsupportedEncodingException("unknown type!"); - } - - StringWriter sw = new StringWriter(); - JAXB.marshal(rec, sw); - r.setContents(sw.toString().getBytes(AuthenticatedService.UTF8)); - return r; - - } - - public static void mapOperationalInfo(UddiEntity model, OperationalInfo operationalInfo) { - if (operationalInfo == null || model == null) { - return; - } - if (operationalInfo.getCreated() != null) { - model.setCreated(operationalInfo.getCreated().toGregorianCalendar().getTime()); - } - model.setAuthorizedName(operationalInfo.getAuthorizedName()); - if (operationalInfo.getModified() != null) { - model.setModified(operationalInfo.getModified().toGregorianCalendar().getTime()); - } - if (operationalInfo.getModifiedIncludingChildren() != null) { - model.setModifiedIncludingChildren(operationalInfo.getModifiedIncludingChildren().toGregorianCalendar().getTime()); - } - model.setNodeId(operationalInfo.getNodeID()); - - } - - public static void mapOperationalInfoIncludingChildren(BusinessEntity model, OperationalInfo operationalInfo) { - if (operationalInfo == null || model == null) { - return; - } - if (operationalInfo.getCreated() != null) { - model.setCreated(operationalInfo.getCreated().toGregorianCalendar().getTime()); - } - model.setAuthorizedName(operationalInfo.getAuthorizedName()); - if (operationalInfo.getModified() != null) { - model.setModified(operationalInfo.getModified().toGregorianCalendar().getTime()); - } - if (operationalInfo.getModifiedIncludingChildren() != null) { - model.setModifiedIncludingChildren(operationalInfo.getModifiedIncludingChildren().toGregorianCalendar().getTime()); - } - model.setNodeId(operationalInfo.getNodeID()); - for (int i = 0; i < model.getBusinessServices().size(); i++) { - mapOperationalInfo(model.getBusinessServices().get(i), operationalInfo); - for (int k = 0; k < model.getBusinessServices().get(i).getBindingTemplates().size(); k++) { - mapOperationalInfo(model.getBusinessServices().get(i).getBindingTemplates().get(k), operationalInfo); - } - } - - } - - public static void mapReplicationConfiguration(ReplicationConfiguration replicationConfiguration, org.apache.juddi.model.ReplicationConfiguration model, EntityManager em) throws DispositionReportFaultMessage { - if (replicationConfiguration == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.replication.configNull")); - } - model.setMaximumTimeToGetChanges(replicationConfiguration.getMaximumTimeToGetChanges()); - model.setMaximumTimeToSyncRegistry(replicationConfiguration.getMaximumTimeToSyncRegistry()); - //this is set by the service when saving - model.setSerialNumber(null); - - //the spec doesn't specify what the format should be, however there was an example - //2002 03 04 1859Z - SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddkkmmZ"); - model.setTimeOfConfigurationUpdate(sdf.format(new Date())); - if (replicationConfiguration.getRegistryContact() != null) { - model.setContact(mapContact(replicationConfiguration.getRegistryContact().getContact(), model)); - } - mapCommunicationGraph(model, replicationConfiguration.getCommunicationGraph(), em); - model.setOperator(mapOperators(replicationConfiguration, model)); - if (replicationConfiguration.getSignature() != null) { - model.setSignatures(mapApiSignaturesToModelSignatures(replicationConfiguration.getSignature())); - } - - } - - private static Contact mapContact(org.uddi.api_v3.Contact contact, org.apache.juddi.model.ReplicationConfiguration model) throws DispositionReportFaultMessage { - Contact cmodel = new Contact(); - cmodel.setReplicationConfigId(model); - cmodel.setAddresses(new ArrayList
()); - mapContactAddresses(contact.getAddress(), cmodel.getAddresses(), cmodel); - if (cmodel.getAddresses().isEmpty()) { - cmodel.setAddresses(null); - } - return cmodel; - } - - private static List mapOperators(ReplicationConfiguration cfg, org.apache.juddi.model.ReplicationConfiguration modelparent) throws DispositionReportFaultMessage { - if (cfg == null) { - return null; - } - List api = cfg.getOperator(); - if (api == null) { - return null; - } - List model = new ArrayList(); - for (int i = 0; i < api.size(); i++) { - Operator op = new Operator(); - op.setParent(modelparent); - - op.setSoapReplicationURL(api.get(i).getSoapReplicationURL()); - - if (!api.get(i).getContact().isEmpty()) { - op.setContact(new ArrayList()); - for (int k = 0; k < api.get(i).getContact().size(); k++) { - op.getContact().add(mapContact(api.get(i).getContact().get(k), null)); - } - } - op.setOperatorNodeID(api.get(i).getOperatorNodeID()); - op.setOperatorStatus(mapOperatorStatus(api.get(i).getOperatorStatus())); - if (!api.get(i).getKeyInfo().isEmpty()) { - op.setKeyInfo(new ArrayList()); - for (int k = 0; k < api.get(i).getKeyInfo().size(); k++) { - org.apache.juddi.model.KeyInfo modelKeyInfo = new KeyInfo(); - modelKeyInfo.setXmlID(api.get(i).getKeyInfo().get(i).getId()); - modelKeyInfo.setKeyDataValue(new ArrayList()); - if (api.get(i).getKeyInfo().get(i).getContent() != null) { - modelKeyInfo.setKeyDataValue(new ArrayList()); - for (int x = 0; x < api.get(i).getKeyInfo().get(k).getContent().size(); x++) { - mapKeyValue((JAXBElement) api.get(i).getKeyInfo().get(k).getContent().get(x), modelKeyInfo.getKeyDataValue()); - } - } - op.getKeyInfo().add(modelKeyInfo); - } - - } - model.add(op); - - } - return model; - } - - private static OperatorStatusType mapOperatorStatus(org.uddi.repl_v3.OperatorStatusType operatorStatus) { - switch (operatorStatus) { - case NEW: - return OperatorStatusType.NEW; - case NORMAL: - return OperatorStatusType.NORMAL; - case RESIGNED: - return OperatorStatusType.RESIGNED; - } - return null; - } - - private static void mapCommunicationGraph(org.apache.juddi.model.ReplicationConfiguration model, CommunicationGraph communicationGraph, EntityManager em) throws ValueNotAllowedException { - - if (model == null) { - return; - } - - /** - * Following the listing of nodes is the controlledMessage - * element that lists the set of messages over which this - * communication graph is intended to administer control of. If - * a message element local name is listed in the - * controlledMessage element, then such messages SHALL only be - * sent between nodes that are listed in the subsequent edges of - * the graph. In contrast, communication restrictions are not - * imposed on replication messages not identified in the - * controlledMessage element. - */ - if (communicationGraph.getControlledMessage() != null) { - model.setControlMessage(new ArrayList()); - - for (int k = 0; k < communicationGraph.getControlledMessage().size(); k++) { - ControlMessage BC = new ControlMessage(communicationGraph.getControlledMessage().get(k)); - BC.setReplicationConfiguration(model); - - model.getControlMessage().add(BC); - } - } - - for (int i = 0; i < communicationGraph.getNode().size(); i++) { - ReplicationConfigurationNode replicationConfigurationNode = new ReplicationConfigurationNode(); - - replicationConfigurationNode.setNodeName(communicationGraph.getNode().get(i)); - replicationConfigurationNode.setParent(model); - model.getNode().add(replicationConfigurationNode); - } - if (communicationGraph.getEdge() != null && !communicationGraph.getEdge().isEmpty()) { - List ret = new ArrayList(); - for (int i = 0; i < communicationGraph.getEdge().size(); i++) { - Edge e = new Edge(); - e.setReplicationConfiguration(model); - - e.setMessageReceiver(communicationGraph.getEdge().get(i).getMessageReceiver()); - e.setMessageSender(communicationGraph.getEdge().get(i).getMessageSender()); - - /** - * The message elements contain the local name - * of the Replication API message elements. They - * indicate that only messages of the type - * explicitly identified for a particular edge - * MAY be sent from the specified messageSender - * to the specified messageReceiver. - */ - if (communicationGraph.getEdge().get(i).getMessage() != null) { - e.setMessage(new ArrayList()); - for (int k = 0; k < communicationGraph.getEdge().get(i).getMessage().size(); k++) { - ControlMessage controlMessage = new ControlMessage(communicationGraph.getEdge().get(i).getMessage().get(k)); - controlMessage.setReplicationConfiguration(model); - controlMessage.setParentEdge(e); - e.getMessages().add(controlMessage); - } - } - if (communicationGraph.getEdge().get(i).getMessageReceiverAlternate() != null) { - List eras = new ArrayList(); - for (String s : communicationGraph.getEdge().get(i).getMessageReceiverAlternate()) { - EdgeReceiverAlternate x = new EdgeReceiverAlternate(); - x.setParent(e); - x.setReceiverAlternate(s); - eras.add(x); - } - e.setMessageReceiverAlternate(eras); - - } - - ret.add(e); - } - model.setEdge(ret); - } - } - - public static void mapOperationalInfoIncludingChildren(BusinessService model, OperationalInfo operationalInfo) { - if (operationalInfo == null || model == null) { - return; - } - if (operationalInfo.getCreated() != null) { - model.setCreated(operationalInfo.getCreated().toGregorianCalendar().getTime()); - } - model.setAuthorizedName(operationalInfo.getAuthorizedName()); - if (operationalInfo.getModified() != null) { - model.setModified(operationalInfo.getModified().toGregorianCalendar().getTime()); - } - if (operationalInfo.getModifiedIncludingChildren() != null) { - model.setModifiedIncludingChildren(operationalInfo.getModifiedIncludingChildren().toGregorianCalendar().getTime()); - } - model.setNodeId(operationalInfo.getNodeID()); - - for (int k = 0; k < model.getBindingTemplates().size(); k++) { - mapOperationalInfo(model.getBindingTemplates().get(k), operationalInfo); - } - - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.mapping; + +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashSet; +import java.util.List; +import javax.persistence.EntityManager; +import javax.xml.bind.JAXB; +import javax.xml.bind.JAXBElement; +import javax.xml.transform.dom.DOMResult; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.api.impl.AuthenticatedService; +import org.apache.juddi.jaxb.JAXBMarshaller; +import org.apache.juddi.model.Address; +import org.apache.juddi.model.BindingTemplate; +import org.apache.juddi.model.BusinessEntity; +import org.apache.juddi.model.BusinessService; +import org.apache.juddi.model.CanonicalizationMethod; +import org.apache.juddi.model.Contact; +import org.apache.juddi.model.ControlMessage; +import org.apache.juddi.model.Edge; +import org.apache.juddi.model.EdgeReceiverAlternate; +import org.apache.juddi.model.KeyDataValue; +import org.apache.juddi.model.KeyInfo; +import org.apache.juddi.model.Node; +import org.apache.juddi.model.Operator; +import org.apache.juddi.model.OperatorStatusType; +import org.apache.juddi.model.Publisher; +import org.apache.juddi.model.Reference; +import org.apache.juddi.model.ReplicationConfigurationNode; +import org.apache.juddi.model.Signature; +import org.apache.juddi.model.SignatureMethod; +import org.apache.juddi.model.SignatureTransform; +import org.apache.juddi.model.SignatureTransformDataValue; +import org.apache.juddi.model.SignatureValue; +import org.apache.juddi.model.SignedInfo; +import org.apache.juddi.model.Tmodel; +import org.apache.juddi.model.UddiEntity; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.ValueNotAllowedException; +import org.uddi.api_v3.Description; +import org.uddi.api_v3.OperationalInfo; +import org.uddi.api_v3.SaveBinding; +import org.uddi.repl_v3.ChangeRecord; +import org.uddi.repl_v3.CommunicationGraph; +import org.uddi.repl_v3.ReplicationConfiguration; +import org.uddi.sub_v3.ObjectFactory; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.w3._2000._09.xmldsig_.DSAKeyValueType; +import org.w3._2000._09.xmldsig_.KeyInfoType; +import org.w3._2000._09.xmldsig_.KeyValueType; +import org.w3._2000._09.xmldsig_.PGPDataType; +import org.w3._2000._09.xmldsig_.RSAKeyValueType; +import org.w3._2000._09.xmldsig_.ReferenceType; +import org.w3._2000._09.xmldsig_.RetrievalMethodType; +import org.w3._2000._09.xmldsig_.SPKIDataType; +import org.w3._2000._09.xmldsig_.TransformType; +import org.w3._2000._09.xmldsig_.TransformsType; +import org.w3._2000._09.xmldsig_.X509DataType; +import org.w3._2000._09.xmldsig_.X509IssuerSerialType; +import org.w3c.dom.DOMException; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.ls.DOMImplementationLS; +import org.w3c.dom.ls.LSException; +import org.w3c.dom.ls.LSSerializer; + +/** + * Handles mapping from the internal jUDDL API Model to the JAXB/XML/WSDL UDDI + * data structures + * + * @author Jeff Faath + * @author Kurt T Stam + * @author Tom Cunningham + * @author Alex O'Ree + */ +public class MappingApiToModel { + + private static Log logger = LogFactory.getLog(MappingApiToModel.class); + + /** + * + * @param apiPublisher + * @param modelPublisher + * @throws DispositionReportFaultMessage + */ + public static void mapPublisher(org.apache.juddi.api_v3.Publisher apiPublisher, + org.apache.juddi.model.Publisher modelPublisher) + throws DispositionReportFaultMessage { + modelPublisher.setAuthorizedName(apiPublisher.getAuthorizedName()); + modelPublisher.setPublisherName(apiPublisher.getPublisherName()); + modelPublisher.setEmailAddress(apiPublisher.getEmailAddress()); + modelPublisher.setIsAdmin(apiPublisher.isIsAdmin()); + modelPublisher.setIsEnabled(apiPublisher.isIsEnabled()); + modelPublisher.setMaxBindingsPerService(apiPublisher.getMaxBindingsPerService()); + modelPublisher.setMaxBusinesses(apiPublisher.getMaxBusinesses()); + modelPublisher.setMaxServicesPerBusiness(apiPublisher.getMaxServicePerBusiness()); + modelPublisher.setMaxTmodels(apiPublisher.getMaxTModels()); + mapPublisherSignatures(apiPublisher.getSignature(), modelPublisher); + } + + /** + * + * @param apiBusinessEntity + * @param modelBusinessEntity + * @throws DispositionReportFaultMessage + */ + public static void mapBusinessEntity(org.uddi.api_v3.BusinessEntity apiBusinessEntity, + org.apache.juddi.model.BusinessEntity modelBusinessEntity) + throws DispositionReportFaultMessage { + + modelBusinessEntity.setEntityKey(apiBusinessEntity.getBusinessKey()); + + mapBusinessNames(apiBusinessEntity.getName(), modelBusinessEntity.getBusinessNames(), modelBusinessEntity); + mapBusinessDescriptions(apiBusinessEntity.getDescription(), modelBusinessEntity.getBusinessDescrs(), modelBusinessEntity); + mapDiscoveryUrls(apiBusinessEntity.getDiscoveryURLs(), modelBusinessEntity.getDiscoveryUrls(), modelBusinessEntity); + mapContacts(apiBusinessEntity.getContacts(), modelBusinessEntity.getContacts(), modelBusinessEntity); + mapBusinessIdentifiers(apiBusinessEntity.getIdentifierBag(), modelBusinessEntity.getBusinessIdentifiers(), modelBusinessEntity); + if (apiBusinessEntity.getCategoryBag() != null) { + modelBusinessEntity.setCategoryBag(new org.apache.juddi.model.BusinessCategoryBag(modelBusinessEntity)); + mapCategoryBag(apiBusinessEntity.getCategoryBag(), modelBusinessEntity.getCategoryBag()); + } + + mapBusinessServices(apiBusinessEntity.getBusinessServices(), + modelBusinessEntity.getBusinessServices(), + modelBusinessEntity.getServiceProjections(), + modelBusinessEntity); + + mapBusinessSignature(apiBusinessEntity.getSignature(), modelBusinessEntity); + } + + public static List mapApiSignaturesToModelSignatures(List apiSignatures) + throws DispositionReportFaultMessage { + List modelSignatures = new ArrayList(); + modelSignatures.clear(); + for (org.w3._2000._09.xmldsig_.SignatureType signatureType : apiSignatures) { + Signature modelSignature = new Signature(); + + org.w3._2000._09.xmldsig_.SignedInfoType apiSignedInfo = signatureType.getSignedInfo(); + SignedInfo modelSignedInfo = new SignedInfo(); + modelSignature.setSignedInfo(modelSignedInfo); + + String canonicalizationAlgMethod = apiSignedInfo.getCanonicalizationMethod().getAlgorithm(); + CanonicalizationMethod modelCanonMethod = new CanonicalizationMethod(); + modelSignedInfo.setCanonicalizationMethod(modelCanonMethod); + modelCanonMethod.setAlgorithm(canonicalizationAlgMethod); + + SignatureMethod modelSigMethod = new SignatureMethod(); + modelSignedInfo.setSignatureMethod(modelSigMethod); + String sigMethod = apiSignedInfo.getSignatureMethod().getAlgorithm(); + modelSigMethod.setAlgorithm(sigMethod); + + List apiReferenceList = apiSignedInfo.getReference(); + for (org.w3._2000._09.xmldsig_.ReferenceType apiReference : apiReferenceList) { + Reference ref = mapReference(modelSignedInfo, apiReference); + modelSignedInfo.getReference().add(ref); + } + + modelSignedInfo.setCanonicalizationMethod(modelCanonMethod); + + org.w3._2000._09.xmldsig_.SignatureValueType apiSignatureValue = signatureType.getSignatureValue(); + SignatureValue modelSignatureValue = new SignatureValue(); + byte[] signatureValueBytes = apiSignatureValue.getValue(); + String signatureValueXmlID = apiSignatureValue.getId(); + modelSignatureValue.setValue(signatureValueBytes); + modelSignatureValue.setXmlID(signatureValueXmlID); + modelSignature.setSignatureValue(modelSignatureValue); + + org.w3._2000._09.xmldsig_.KeyInfoType apiKeyInfo = signatureType.getKeyInfo(); + String apiKeyInfoXmlID = apiKeyInfo.getId(); + KeyInfo modelKeyInfo = new KeyInfo(); + modelSignature.setKeyInfo(modelKeyInfo); + modelKeyInfo.setXmlID(apiKeyInfoXmlID); + + List apiKeyInfoContentList = apiKeyInfo.getContent(); + List keyInfoDataValues = modelKeyInfo.getKeyDataValue(); + for (Object apiKeyInfoContentObj : apiKeyInfoContentList) { + if (apiKeyInfoContentObj instanceof JAXBElement) { + JAXBElement apiKeyInfoContentJAXB = (JAXBElement) apiKeyInfoContentObj; + String apiKeyInfoContentTagName = apiKeyInfoContentJAXB.getName().getLocalPart(); + if (apiKeyInfoContentJAXB.getValue() instanceof X509DataType) { + KeyDataValue modelX509KeyData = mapX509DataType(apiKeyInfoContentJAXB, modelKeyInfo); + keyInfoDataValues.add(modelX509KeyData); + } else if (apiKeyInfoContentTagName.equals("KeyName")) { + KeyDataValue modelKeyNameKDV = mapKeyName(apiKeyInfoContentJAXB); + modelKeyNameKDV.setKeyInfo(modelKeyInfo); + keyInfoDataValues.add(modelKeyNameKDV); + } else if (apiKeyInfoContentTagName.equals("KeyValue")) { + KeyDataValue modelKeyValueKDV = mapKeyValue(apiKeyInfoContentJAXB, keyInfoDataValues); + modelKeyValueKDV.setKeyInfo(modelKeyInfo); + keyInfoDataValues.add(modelKeyValueKDV); + } else if (apiKeyInfoContentTagName.equals("MgmtData")) { + KeyDataValue modelKeyValueKDV = new KeyDataValue(); + modelKeyValueKDV.setKeyDataName(apiKeyInfoContentTagName); + modelKeyValueKDV.setKeyDataType("String"); + modelKeyValueKDV.setKeyDataValueString((String) apiKeyInfoContentJAXB.getValue()); + modelKeyValueKDV.setKeyInfo(modelKeyInfo); + keyInfoDataValues.add(modelKeyValueKDV); + } else if (apiKeyInfoContentTagName.equals("RetrievalMethod")) { + RetrievalMethodType retrievalMethodType = (RetrievalMethodType) apiKeyInfoContentJAXB.getValue(); + KeyDataValue retrievalMethodTypeKDV = mapRetrievalMethod(apiKeyInfoContentTagName, modelKeyInfo, retrievalMethodType); + keyInfoDataValues.add(retrievalMethodTypeKDV); + } else if (apiKeyInfoContentTagName.equals("PGPData")) { + PGPDataType pgpDataType = (PGPDataType) apiKeyInfoContentJAXB.getValue(); + KeyDataValue pgpDataTypeKDV = mapPGPDataType(apiKeyInfoContentTagName, modelKeyInfo, pgpDataType); + keyInfoDataValues.add(pgpDataTypeKDV); + } else if (apiKeyInfoContentTagName.equals("SPKIData")) { + SPKIDataType spkiDataType = (SPKIDataType) apiKeyInfoContentJAXB.getValue(); + KeyDataValue spkiDataTypeKDV = mapSPKIDataType(apiKeyInfoContentTagName, modelKeyInfo, spkiDataType); + keyInfoDataValues.add(spkiDataTypeKDV); + } else { + throw new RuntimeException("Unrecognized tag: " + apiKeyInfoContentTagName + " type: " + apiKeyInfoContentJAXB.getValue().getClass().getCanonicalName()); + } + } + } + + modelSignatures.add(modelSignature); + } + return modelSignatures; + } + + /** + * + * @param apiSignatures + * @param modelBusinessService + * @throws DispositionReportFaultMessage + */ + public static void mapBusinessServiceSignature(List apiSignatures, BusinessService modelBusinessService) + throws DispositionReportFaultMessage { + List modelSignatures = mapApiSignaturesToModelSignatures(apiSignatures); + for (Signature modelSignature : modelSignatures) { + modelSignature.setBusinessService(modelBusinessService); + } + modelBusinessService.setSignatures(modelSignatures); + } + + /** + * + * @param apiSignatures + * @param modelTmodel + * @throws DispositionReportFaultMessage + */ + public static void mapTmodelSignatures(List apiSignatures, Tmodel modelTmodel) + throws DispositionReportFaultMessage { + List modelSignatures = mapApiSignaturesToModelSignatures(apiSignatures); + for (Signature modelSignature : modelSignatures) { + modelSignature.setTmodel(modelTmodel); + } + modelTmodel.setSignatures(modelSignatures); + } + + /** + * + * @param apiSignatures + * @param modelBindingTemplate + * @throws DispositionReportFaultMessage + */ + public static void mapBindingTemplateSignatures(List apiSignatures, BindingTemplate modelBindingTemplate) + throws DispositionReportFaultMessage { + List modelSignatures = mapApiSignaturesToModelSignatures(apiSignatures); + for (Signature modelSignature : modelSignatures) { + modelSignature.setBindingTemplate(modelBindingTemplate); + } + modelBindingTemplate.setSignatures(modelSignatures); + } + + /** + * + * @param apiSignatures + * @param modelPublisher + * @throws DispositionReportFaultMessage + */ + public static void mapPublisherSignatures(List apiSignatures, Publisher modelPublisher) + throws DispositionReportFaultMessage { + List modelSignatures = mapApiSignaturesToModelSignatures(apiSignatures); + for (Signature modelSignature : modelSignatures) { + modelSignature.setPublisher(modelPublisher); + } + modelPublisher.setSignatures(modelSignatures); + } + + /** + * + * @param apiSignatures + * @param modelBusinessEntity + * @throws DispositionReportFaultMessage + */ + public static void mapBusinessSignature(List apiSignatures, + org.apache.juddi.model.BusinessEntity modelBusinessEntity) + throws DispositionReportFaultMessage { + List modelSignatures = mapApiSignaturesToModelSignatures(apiSignatures); + for (Signature modelSignature : modelSignatures) { + modelSignature.setBusinessEntity(modelBusinessEntity); + } + modelBusinessEntity.setSignatures(modelSignatures); + } + + /** + * + * @param apiNameList + * @param modelNameList + * @param modelBusinessEntity + * @throws DispositionReportFaultMessage + */ + public static void mapBusinessNames(List apiNameList, + List modelNameList, + org.apache.juddi.model.BusinessEntity modelBusinessEntity) + throws DispositionReportFaultMessage { + modelNameList.clear(); + + for (org.uddi.api_v3.Name apiName : apiNameList) { + modelNameList.add(new org.apache.juddi.model.BusinessName(modelBusinessEntity, apiName.getLang(), apiName.getValue())); + } + } + + /** + * + * @param apiDescList + * @param modelDescList + * @param modelBusinessEntity + * @throws DispositionReportFaultMessage + */ + public static void mapBusinessDescriptions(List apiDescList, + List modelDescList, + org.apache.juddi.model.BusinessEntity modelBusinessEntity) + throws DispositionReportFaultMessage { + modelDescList.clear(); + + for (org.uddi.api_v3.Description apiDesc : apiDescList) { + modelDescList.add(new org.apache.juddi.model.BusinessDescr(modelBusinessEntity, apiDesc.getLang(), apiDesc.getValue())); + } + } + + /** + * + * @param apiDiscUrls + * @param modelDiscUrlList + * @param modelBusinessEntity + * @throws DispositionReportFaultMessage + */ + public static void mapDiscoveryUrls(org.uddi.api_v3.DiscoveryURLs apiDiscUrls, + List modelDiscUrlList, + org.apache.juddi.model.BusinessEntity modelBusinessEntity) + throws DispositionReportFaultMessage { + modelDiscUrlList.clear(); + + if (apiDiscUrls != null) { + List apiDiscUrlList = apiDiscUrls.getDiscoveryURL(); + for (org.uddi.api_v3.DiscoveryURL apiDiscUrl : apiDiscUrlList) { + modelDiscUrlList.add(new org.apache.juddi.model.DiscoveryUrl(modelBusinessEntity, apiDiscUrl.getUseType(), apiDiscUrl.getValue())); + } + } + } + + /** + * + * @param apiContacts + * @param modelContactList + * @param modelBusinessEntity + * @throws DispositionReportFaultMessage + */ + public static void mapContacts(org.uddi.api_v3.Contacts apiContacts, + List modelContactList, + org.apache.juddi.model.BusinessEntity modelBusinessEntity) + throws DispositionReportFaultMessage { + modelContactList.clear(); + + if (apiContacts != null) { + List apiContactList = apiContacts.getContact(); + for (org.uddi.api_v3.Contact apiContact : apiContactList) { + org.apache.juddi.model.Contact modelContact = new org.apache.juddi.model.Contact(modelBusinessEntity); + modelContact.setUseType(apiContact.getUseType()); + + mapPersonNames(apiContact.getPersonName(), modelContact.getPersonNames(), modelContact, modelBusinessEntity.getEntityKey()); + mapContactDescriptions(apiContact.getDescription(), modelContact.getContactDescrs(), modelContact, modelBusinessEntity.getEntityKey()); + mapContactEmails(apiContact.getEmail(), modelContact.getEmails(), modelContact, modelBusinessEntity.getEntityKey()); + mapContactPhones(apiContact.getPhone(), modelContact.getPhones(), modelContact, modelBusinessEntity.getEntityKey()); + mapContactAddresses(apiContact.getAddress(), modelContact.getAddresses(), modelContact); + + modelContactList.add(modelContact); + } + } + } + + /** + * + * @param apiDescList + * @param modelDescList + * @param modelContact + * @param businessKey + * @throws DispositionReportFaultMessage + */ + public static void mapContactDescriptions(List apiDescList, + List modelDescList, + org.apache.juddi.model.Contact modelContact, + String businessKey) + throws DispositionReportFaultMessage { + modelDescList.clear(); + + for (org.uddi.api_v3.Description apiDesc : apiDescList) { + modelDescList.add(new org.apache.juddi.model.ContactDescr(modelContact, apiDesc.getLang(), apiDesc.getValue())); + } + } + + /** + * + * @param apiPersonNameList + * @param modelPersonNameList + * @param modelContact + * @param businessKey + * @throws DispositionReportFaultMessage + */ + public static void mapPersonNames(List apiPersonNameList, + List modelPersonNameList, + org.apache.juddi.model.Contact modelContact, + String businessKey) + throws DispositionReportFaultMessage { + modelPersonNameList.clear(); + + for (org.uddi.api_v3.PersonName apiPersonName : apiPersonNameList) { + modelPersonNameList.add(new org.apache.juddi.model.PersonName(modelContact, apiPersonName.getLang(), apiPersonName.getValue())); + } + } + + /** + * + * @param apiEmailList + * @param modelEmailList + * @param modelContact + * @param businessKey + * @throws DispositionReportFaultMessage + */ + public static void mapContactEmails(List apiEmailList, + List modelEmailList, + org.apache.juddi.model.Contact modelContact, + String businessKey) + throws DispositionReportFaultMessage { + modelEmailList.clear(); + + for (org.uddi.api_v3.Email apiEmail : apiEmailList) { + modelEmailList.add(new org.apache.juddi.model.Email(modelContact, apiEmail.getUseType(), apiEmail.getValue())); + } + } + + /** + * + * @param apiPhoneList + * @param modelPhoneList + * @param modelContact + * @param businessKey + * @throws DispositionReportFaultMessage + */ + public static void mapContactPhones(List apiPhoneList, + List modelPhoneList, + org.apache.juddi.model.Contact modelContact, + String businessKey) + throws DispositionReportFaultMessage { + modelPhoneList.clear(); + + for (org.uddi.api_v3.Phone apiPhone : apiPhoneList) { + modelPhoneList.add(new org.apache.juddi.model.Phone(modelContact, apiPhone.getUseType(), apiPhone.getValue())); + } + } + + /** + * + * @param apiAddressList + * @param modelAddressList + * @param modelContact + * @param businessKey + * @throws DispositionReportFaultMessage + */ + public static void mapContactAddresses(List apiAddressList, + List modelAddressList, + org.apache.juddi.model.Contact modelContact + ) + throws DispositionReportFaultMessage { + modelAddressList.clear(); + + for (org.uddi.api_v3.Address apiAddress : apiAddressList) { + org.apache.juddi.model.Address modelAddress = new org.apache.juddi.model.Address(modelContact); + modelAddress.setSortCode(apiAddress.getSortCode()); + modelAddress.setTmodelKey(apiAddress.getTModelKey()); + modelAddress.setUseType(apiAddress.getUseType()); + + mapAddressLines(apiAddress.getAddressLine(), modelAddress.getAddressLines(), modelAddress, modelContact.getId()); + + modelAddressList.add(modelAddress); + } + } + + /** + * + * @param apiAddressLineList + * @param modelAddressLineList + * @param modelAddress + * + * @param contactId + * @throws DispositionReportFaultMessage + */ + public static void mapAddressLines(List apiAddressLineList, + List modelAddressLineList, + org.apache.juddi.model.Address modelAddress, + Long contactId) + throws DispositionReportFaultMessage { + modelAddressLineList.clear(); + + for (org.uddi.api_v3.AddressLine apiAddressLine : apiAddressLineList) { + modelAddressLineList.add(new org.apache.juddi.model.AddressLine(modelAddress, apiAddressLine.getValue(), apiAddressLine.getKeyName(), apiAddressLine.getKeyValue())); + } + } + + /** + * + * @param apiIdentifierBag + * @param modelIdentifierList + * @param modelBusinessEntity + * @throws DispositionReportFaultMessage + */ + public static void mapBusinessIdentifiers(org.uddi.api_v3.IdentifierBag apiIdentifierBag, + List modelIdentifierList, + org.apache.juddi.model.BusinessEntity modelBusinessEntity) + throws DispositionReportFaultMessage { + modelIdentifierList.clear(); + + if (apiIdentifierBag != null) { + List apiKeyedRefList = apiIdentifierBag.getKeyedReference(); + for (org.uddi.api_v3.KeyedReference apiKeyedRef : apiKeyedRefList) { + modelIdentifierList.add(new org.apache.juddi.model.BusinessIdentifier(modelBusinessEntity, apiKeyedRef.getTModelKey(), apiKeyedRef.getKeyName(), apiKeyedRef.getKeyValue())); + } + } + } + + /** + * + * @param apiBusinessServices + * @param modelBusinessServiceList + * @param modelServiceProjectionList + * @param modelBusinessEntity + * @throws DispositionReportFaultMessage + */ + public static void mapBusinessServices(org.uddi.api_v3.BusinessServices apiBusinessServices, + List modelBusinessServiceList, + List modelServiceProjectionList, + org.apache.juddi.model.BusinessEntity modelBusinessEntity) + throws DispositionReportFaultMessage { + modelBusinessServiceList.clear(); + if (apiBusinessServices != null) { + List apiBusinessServiceList = apiBusinessServices.getBusinessService(); + for (org.uddi.api_v3.BusinessService apiBusinessService : apiBusinessServiceList) { + org.apache.juddi.model.BusinessService modelBusinessService = new org.apache.juddi.model.BusinessService(); + + // If the parent businessEntity key and the service businessEntity key (if provided) do not match, it's a projection. + if (apiBusinessService.getBusinessKey() != null && apiBusinessService.getBusinessKey().length() > 0 + && !modelBusinessEntity.getEntityKey().equalsIgnoreCase(apiBusinessService.getBusinessKey())) { + + modelBusinessService.setEntityKey(apiBusinessService.getServiceKey()); + org.apache.juddi.model.ServiceProjection modelServiceProjection = new org.apache.juddi.model.ServiceProjection(modelBusinessEntity, modelBusinessService); + + modelServiceProjectionList.add(modelServiceProjection); + } else { + mapBusinessService(apiBusinessService, modelBusinessService, modelBusinessEntity); + modelBusinessServiceList.add(modelBusinessService); + } + } + } + } + + /** + * + * @param apiBusinessService + * @param modelBusinessService + * @param modelBusinessEntity + * @throws DispositionReportFaultMessage + */ + public static void mapBusinessService(org.uddi.api_v3.BusinessService apiBusinessService, + org.apache.juddi.model.BusinessService modelBusinessService, + org.apache.juddi.model.BusinessEntity modelBusinessEntity) + throws DispositionReportFaultMessage { + + modelBusinessService.setBusinessEntity(modelBusinessEntity); + modelBusinessService.setEntityKey(apiBusinessService.getServiceKey()); + + mapServiceNames(apiBusinessService.getName(), modelBusinessService.getServiceNames(), modelBusinessService); + mapServiceDescriptions(apiBusinessService.getDescription(), modelBusinessService.getServiceDescrs(), modelBusinessService); + if (apiBusinessService.getCategoryBag() != null) { + modelBusinessService.setCategoryBag(new org.apache.juddi.model.ServiceCategoryBag(modelBusinessService)); + mapCategoryBag(apiBusinessService.getCategoryBag(), modelBusinessService.getCategoryBag()); + } + + mapBindingTemplates(apiBusinessService.getBindingTemplates(), modelBusinessService.getBindingTemplates(), modelBusinessService); + mapBusinessServiceSignature(apiBusinessService.getSignature(), modelBusinessService); + } + + /** + * + * @param apiNameList + * @param modelNameList + * @param modelBusinessService + * @throws DispositionReportFaultMessage + */ + public static void mapServiceNames(List apiNameList, + List modelNameList, + org.apache.juddi.model.BusinessService modelBusinessService) + throws DispositionReportFaultMessage { + modelNameList.clear(); + + for (org.uddi.api_v3.Name apiName : apiNameList) { + modelNameList.add(new org.apache.juddi.model.ServiceName(modelBusinessService, apiName.getLang(), apiName.getValue())); + } + } + + /** + * + * @param apiDescList + * @param modelDescList + * @param modelBusinessService + * @throws DispositionReportFaultMessage + */ + public static void mapServiceDescriptions(List apiDescList, + List modelDescList, + org.apache.juddi.model.BusinessService modelBusinessService) + throws DispositionReportFaultMessage { + modelDescList.clear(); + + for (org.uddi.api_v3.Description apiDesc : apiDescList) { + modelDescList.add(new org.apache.juddi.model.ServiceDescr(modelBusinessService, apiDesc.getLang(), apiDesc.getValue())); + } + } + + /** + * + * @param apiBindingTemplates + * @param modelBindingTemplateList + * @param modelBusinessService + * @throws DispositionReportFaultMessage + */ + public static void mapBindingTemplates(org.uddi.api_v3.BindingTemplates apiBindingTemplates, + List modelBindingTemplateList, + org.apache.juddi.model.BusinessService modelBusinessService) + throws DispositionReportFaultMessage { + modelBindingTemplateList.clear(); + + if (apiBindingTemplates != null) { + List apiBindingTemplateList = apiBindingTemplates.getBindingTemplate(); + for (org.uddi.api_v3.BindingTemplate apiBindingTemplate : apiBindingTemplateList) { + org.apache.juddi.model.BindingTemplate modelBindingTemplate = new org.apache.juddi.model.BindingTemplate(); + + mapBindingTemplate(apiBindingTemplate, modelBindingTemplate, modelBusinessService); + + modelBindingTemplateList.add(modelBindingTemplate); + } + } + } + + /** + * + * @param apiBindingTemplate + * @param modelBindingTemplate + * @param modelBusinessService + * @throws DispositionReportFaultMessage + */ + public static void mapBindingTemplate(org.uddi.api_v3.BindingTemplate apiBindingTemplate, + org.apache.juddi.model.BindingTemplate modelBindingTemplate, + org.apache.juddi.model.BusinessService modelBusinessService) + throws DispositionReportFaultMessage { + + modelBindingTemplate.setBusinessService(modelBusinessService); + modelBindingTemplate.setEntityKey(apiBindingTemplate.getBindingKey()); + if (apiBindingTemplate.getAccessPoint() != null) { + modelBindingTemplate.setAccessPointType(apiBindingTemplate.getAccessPoint().getUseType()); + modelBindingTemplate.setAccessPointUrl(apiBindingTemplate.getAccessPoint().getValue()); + } + if (apiBindingTemplate.getHostingRedirector() != null) { + modelBindingTemplate.setHostingRedirector(apiBindingTemplate.getHostingRedirector().getBindingKey()); + } + + mapBindingDescriptions(apiBindingTemplate.getDescription(), modelBindingTemplate.getBindingDescrs(), modelBindingTemplate); + if (apiBindingTemplate.getCategoryBag() != null) { + modelBindingTemplate.setCategoryBag(new org.apache.juddi.model.BindingCategoryBag(modelBindingTemplate)); + mapCategoryBag(apiBindingTemplate.getCategoryBag(), modelBindingTemplate.getCategoryBag()); + } + mapTModelInstanceDetails(apiBindingTemplate.getTModelInstanceDetails(), modelBindingTemplate.getTmodelInstanceInfos(), modelBindingTemplate); + mapBindingTemplateSignatures(apiBindingTemplate.getSignature(), modelBindingTemplate); + } + + /** + * + * @param apiDescList + * @param modelDescList + * @param modelBindingTemplate + * @throws DispositionReportFaultMessage + */ + public static void mapBindingDescriptions(List apiDescList, + List modelDescList, + org.apache.juddi.model.BindingTemplate modelBindingTemplate) + throws DispositionReportFaultMessage { + modelDescList.clear(); + for (org.uddi.api_v3.Description apiDesc : apiDescList) { + modelDescList.add(new org.apache.juddi.model.BindingDescr(modelBindingTemplate, apiDesc.getLang(), apiDesc.getValue())); + } + } + + /** + * + * @param apiCategoryBag + * @param modelCategoryBag + * @throws DispositionReportFaultMessage + */ + public static void mapCategoryBag(org.uddi.api_v3.CategoryBag apiCategoryBag, + org.apache.juddi.model.CategoryBag modelCategoryBag) + throws DispositionReportFaultMessage { + + if (apiCategoryBag != null) { + List krList = apiCategoryBag.getKeyedReference(); + for (Object elem : krList) { + if (elem instanceof org.uddi.api_v3.KeyedReference) { + List modelKeyedReferences = modelCategoryBag.getKeyedReferences(); + //modelKeyedReferences.clear(); + org.uddi.api_v3.KeyedReference apiKeyedReference = (org.uddi.api_v3.KeyedReference) elem; + modelKeyedReferences.add(new org.apache.juddi.model.KeyedReference(modelCategoryBag, + apiKeyedReference.getTModelKey(), apiKeyedReference.getKeyName(), apiKeyedReference.getKeyValue())); + } + } + List krgList = apiCategoryBag.getKeyedReferenceGroup(); + for (org.uddi.api_v3.KeyedReferenceGroup elem : krgList) { + if (elem instanceof org.uddi.api_v3.KeyedReferenceGroup) { + org.uddi.api_v3.KeyedReferenceGroup apiKeyedReferenceGroup = (org.uddi.api_v3.KeyedReferenceGroup) elem; + + org.apache.juddi.model.KeyedReferenceGroup modelKeyedReferenceGroup = new org.apache.juddi.model.KeyedReferenceGroup(); + List modelKeyedReferenceGroups = modelCategoryBag.getKeyedReferenceGroups(); + //modelKeyedReferenceGroups.clear(); + + mapKeyedReferenceGroup(apiKeyedReferenceGroup, modelKeyedReferenceGroup, modelCategoryBag); + + modelKeyedReferenceGroups.add(modelKeyedReferenceGroup); + } + } + } + } + + /** + * + * @param apiKeyedReferenceGroup + * @param modelKeyedReferenceGroup + * @param modelCategoryBag + * @throws DispositionReportFaultMessage + */ + public static void mapKeyedReferenceGroup(org.uddi.api_v3.KeyedReferenceGroup apiKeyedReferenceGroup, + org.apache.juddi.model.KeyedReferenceGroup modelKeyedReferenceGroup, + org.apache.juddi.model.CategoryBag modelCategoryBag) + throws DispositionReportFaultMessage { + if (apiKeyedReferenceGroup != null) { + modelKeyedReferenceGroup.setCategoryBag(modelCategoryBag); + modelKeyedReferenceGroup.setTmodelKey(apiKeyedReferenceGroup.getTModelKey()); + + if (apiKeyedReferenceGroup.getKeyedReference() != null) { + List modelKeyedReferences = modelKeyedReferenceGroup.getKeyedReferences(); + for (org.uddi.api_v3.KeyedReference apiKeyedReference : apiKeyedReferenceGroup.getKeyedReference()) { + modelKeyedReferences.add(new org.apache.juddi.model.KeyedReference(modelKeyedReferenceGroup, + apiKeyedReference.getTModelKey(), apiKeyedReference.getKeyName(), apiKeyedReference.getKeyValue())); + } + } + + } + + } + + /** + * + * @param apiTModelInstDetails + * @param modelTModelInstInfoList + * @param modelBindingTemplate + * @throws DispositionReportFaultMessage + */ + public static void mapTModelInstanceDetails(org.uddi.api_v3.TModelInstanceDetails apiTModelInstDetails, + List modelTModelInstInfoList, + org.apache.juddi.model.BindingTemplate modelBindingTemplate) + throws DispositionReportFaultMessage { + modelTModelInstInfoList.clear(); + + if (apiTModelInstDetails != null) { + List apiTModelInstInfoList = apiTModelInstDetails.getTModelInstanceInfo(); + for (org.uddi.api_v3.TModelInstanceInfo apiTModelInstInfo : apiTModelInstInfoList) { + org.apache.juddi.model.TmodelInstanceInfo modelTModelInstInfo = new org.apache.juddi.model.TmodelInstanceInfo(modelBindingTemplate, apiTModelInstInfo.getTModelKey()); + + mapTModelInstanceInfoDescriptions(apiTModelInstInfo.getDescription(), modelTModelInstInfo.getTmodelInstanceInfoDescrs(), modelTModelInstInfo); + mapInstanceDetails(apiTModelInstInfo.getInstanceDetails(), modelTModelInstInfo); + + modelTModelInstInfoList.add(modelTModelInstInfo); + } + } + } + + /** + * + * @param apiDescList + * @param modelDescList + * @param modelTModelInstInfo + * @throws DispositionReportFaultMessage + */ + public static void mapTModelInstanceInfoDescriptions(List apiDescList, + List modelDescList, + org.apache.juddi.model.TmodelInstanceInfo modelTModelInstInfo) + throws DispositionReportFaultMessage { + modelDescList.clear(); + + for (org.uddi.api_v3.Description apiDesc : apiDescList) { + modelDescList.add(new org.apache.juddi.model.TmodelInstanceInfoDescr(modelTModelInstInfo, apiDesc.getLang(), apiDesc.getValue())); + } + } + + /** + * + * @param apiInstanceDetails + * @param modelTmodelInstInfo + * @throws DispositionReportFaultMessage + */ + public static void mapInstanceDetails(org.uddi.api_v3.InstanceDetails apiInstanceDetails, + org.apache.juddi.model.TmodelInstanceInfo modelTmodelInstInfo) + throws DispositionReportFaultMessage { + modelTmodelInstInfo.getInstanceDetailsDescrs().clear(); + + if (apiInstanceDetails != null) { + List descriptions = apiInstanceDetails.getDescription(); + List overviewdocs = apiInstanceDetails.getOverviewDoc(); + for (org.uddi.api_v3.Description apiDesc : descriptions) { + org.apache.juddi.model.InstanceDetailsDescr modelInstanceDetailsDescr + = new org.apache.juddi.model.InstanceDetailsDescr( + modelTmodelInstInfo, apiDesc.getLang(), apiDesc.getValue()); + modelTmodelInstInfo.getInstanceDetailsDescrs().add(modelInstanceDetailsDescr); + } + for (org.uddi.api_v3.OverviewDoc apiOverviewDoc : overviewdocs) { + org.apache.juddi.model.OverviewDoc modelOverviewDoc = new org.apache.juddi.model.OverviewDoc(modelTmodelInstInfo); + mapOverviewDoc(apiOverviewDoc, modelOverviewDoc); + modelTmodelInstInfo.getOverviewDocs().add(modelOverviewDoc); + } + modelTmodelInstInfo.setInstanceParms((String) apiInstanceDetails.getInstanceParms()); + } + } + + /** + * + * @param apiOverviewDoc + * @param modelOverviewDoc + * @throws DispositionReportFaultMessage + */ + public static void mapOverviewDoc(org.uddi.api_v3.OverviewDoc apiOverviewDoc, + org.apache.juddi.model.OverviewDoc modelOverviewDoc) + throws DispositionReportFaultMessage { + if (apiOverviewDoc != null) { + + List descContent = apiOverviewDoc.getDescription(); + for (Object elem : descContent) { + org.uddi.api_v3.Description description = (org.uddi.api_v3.Description) elem; + if (description != null) { + org.apache.juddi.model.OverviewDocDescr modelOverviewDocDescr = new org.apache.juddi.model.OverviewDocDescr( + modelOverviewDoc, description.getLang(), description.getValue()); + modelOverviewDoc.getOverviewDocDescrs().add(modelOverviewDocDescr); + } + } + + org.uddi.api_v3.OverviewURL elem = apiOverviewDoc.getOverviewURL(); + if (elem instanceof org.uddi.api_v3.OverviewURL) { + org.uddi.api_v3.OverviewURL overviewURL = elem; + modelOverviewDoc.setOverviewUrl(overviewURL.getValue()); + modelOverviewDoc.setOverviewUrlUseType(overviewURL.getUseType()); + } + + } + } + + /** + * + * @param apiTModel + * @param modelTModel + * @throws DispositionReportFaultMessage + */ + public static void mapTModel(org.uddi.api_v3.TModel apiTModel, + org.apache.juddi.model.Tmodel modelTModel) + throws DispositionReportFaultMessage { + + modelTModel.setEntityKey(apiTModel.getTModelKey()); + modelTModel.setName(apiTModel.getName().getValue()); + modelTModel.setLangCode(apiTModel.getName().getLang()); + modelTModel.setDeleted(apiTModel.isDeleted()); + + mapTModelDescriptions(apiTModel.getDescription(), modelTModel.getTmodelDescrs(), modelTModel); + mapTModelIdentifiers(apiTModel.getIdentifierBag(), modelTModel.getTmodelIdentifiers(), modelTModel); + if (apiTModel.getCategoryBag() != null) { + modelTModel.setCategoryBag(new org.apache.juddi.model.TmodelCategoryBag(modelTModel)); + mapCategoryBag(apiTModel.getCategoryBag(), modelTModel.getCategoryBag()); + } + mapTModelOverviewDocs(apiTModel.getOverviewDoc(), modelTModel.getOverviewDocs(), modelTModel); + mapTmodelSignatures(apiTModel.getSignature(), modelTModel); + } + + /** + * + * @param apiDescList + * @param modelDescList + * @param modelTModel + * @throws DispositionReportFaultMessage + */ + public static void mapTModelDescriptions(List apiDescList, + List modelDescList, + org.apache.juddi.model.Tmodel modelTModel) + throws DispositionReportFaultMessage { + modelDescList.clear(); + + for (org.uddi.api_v3.Description apiDesc : apiDescList) { + modelDescList.add(new org.apache.juddi.model.TmodelDescr(modelTModel, apiDesc.getLang(), apiDesc.getValue())); + } + } + + /** + * + * @param apiIdentifierBag + * @param modelIdentifierList + * @param modelTModel + * @throws DispositionReportFaultMessage + */ + public static void mapTModelIdentifiers(org.uddi.api_v3.IdentifierBag apiIdentifierBag, + List modelIdentifierList, + org.apache.juddi.model.Tmodel modelTModel) + throws DispositionReportFaultMessage { + modelIdentifierList.clear(); + + if (apiIdentifierBag != null) { + List apiKeyedRefList = apiIdentifierBag.getKeyedReference(); + for (org.uddi.api_v3.KeyedReference apiKeyedRef : apiKeyedRefList) { + modelIdentifierList.add(new org.apache.juddi.model.TmodelIdentifier(modelTModel, apiKeyedRef.getTModelKey(), apiKeyedRef.getKeyName(), apiKeyedRef.getKeyValue())); + } + } + } + + /** + * + * @param apiOverviewDocList + * @param modelOverviewDocList + * @param modelTmodel + * @throws DispositionReportFaultMessage + */ + public static void mapTModelOverviewDocs(List apiOverviewDocList, + List modelOverviewDocList, + org.apache.juddi.model.Tmodel modelTmodel) + throws DispositionReportFaultMessage { + modelOverviewDocList.clear(); + + for (org.uddi.api_v3.OverviewDoc apiOverviewDoc : apiOverviewDocList) { + org.apache.juddi.model.OverviewDoc modelOverviewDoc = new org.apache.juddi.model.OverviewDoc(modelTmodel); + mapOverviewDoc(apiOverviewDoc, modelOverviewDoc); + modelTmodel.getOverviewDocs().add(modelOverviewDoc); + } + } + + /** + * note that when using this, it does not reference the instance of the + * specific businesses, it will create new ones. be sure to overwrite + * them with the correct references + * + * @param apiPubAssertion + * @param modelPubAssertion + * @throws DispositionReportFaultMessage + */ + public static void mapPublisherAssertion(org.uddi.api_v3.PublisherAssertion apiPubAssertion, + org.apache.juddi.model.PublisherAssertion modelPubAssertion) + throws DispositionReportFaultMessage { + + modelPubAssertion.setId(new org.apache.juddi.model.PublisherAssertionId(apiPubAssertion.getFromKey(), apiPubAssertion.getToKey())); + + org.apache.juddi.model.BusinessEntity beFrom = new org.apache.juddi.model.BusinessEntity(); + beFrom.setEntityKey(apiPubAssertion.getFromKey()); + modelPubAssertion.setBusinessEntityByFromKey(beFrom); + + org.apache.juddi.model.BusinessEntity beTo = new org.apache.juddi.model.BusinessEntity(); + beFrom.setEntityKey(apiPubAssertion.getToKey()); + modelPubAssertion.setBusinessEntityByToKey(beTo); + + org.uddi.api_v3.KeyedReference apiKeyedRef = apiPubAssertion.getKeyedReference(); + if (apiKeyedRef != null) { + modelPubAssertion.setTmodelKey(apiKeyedRef.getTModelKey()); + modelPubAssertion.setKeyName(apiKeyedRef.getKeyName()); + modelPubAssertion.setKeyValue(apiKeyedRef.getKeyValue()); + } + if (!apiPubAssertion.getSignature().isEmpty()) { + modelPubAssertion.setSignatures(mapApiSignaturesToModelSignatures(apiPubAssertion.getSignature())); + for (Signature s : modelPubAssertion.getSignatures()) { + s.setPublisherAssertionFromKey(modelPubAssertion.getBusinessEntityByFromKey().getEntityKey()); + s.setPublisherAssertionToKey(modelPubAssertion.getBusinessEntityByToKey().getEntityKey()); + + } + + } + } + + /** + * + * @param apiSubscription + * @param modelSubscription + * @throws DispositionReportFaultMessage + */ + public static void mapSubscription(org.uddi.sub_v3.Subscription apiSubscription, + org.apache.juddi.model.Subscription modelSubscription) + throws DispositionReportFaultMessage { + + modelSubscription.setSubscriptionKey(apiSubscription.getSubscriptionKey()); + modelSubscription.setBindingKey(apiSubscription.getBindingKey()); + if (apiSubscription.getNotificationInterval() != null) { + modelSubscription.setNotificationInterval(apiSubscription.getNotificationInterval().toString()); + } + modelSubscription.setMaxEntities(apiSubscription.getMaxEntities()); + if (apiSubscription.getExpiresAfter() != null) { + GregorianCalendar gc = apiSubscription.getExpiresAfter().toGregorianCalendar(); + modelSubscription.setExpiresAfter(new Date(gc.getTimeInMillis())); + } + + if (apiSubscription.isBrief() != null) { + modelSubscription.setBrief(apiSubscription.isBrief()); + } else { + modelSubscription.setBrief(Boolean.FALSE); + } + + String rawFilter = JAXBMarshaller.marshallToString(new ObjectFactory().createSubscriptionFilter(apiSubscription.getSubscriptionFilter()), "org.uddi.sub_v3"); + logger.debug("marshalled subscription filter: " + rawFilter); + modelSubscription.setSubscriptionFilter(rawFilter); + + } + + /** + * + * @param apiClientSubscriptionInfo + * @param modelClientSubscriptionInfo + * @throws DispositionReportFaultMessage + */ + public static void mapClientSubscriptionInfo(org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo, + org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo) + throws DispositionReportFaultMessage { + + modelClientSubscriptionInfo.setLastNotified(new Date()); + modelClientSubscriptionInfo.setSubscriptionKey(apiClientSubscriptionInfo.getSubscriptionKey()); + if (apiClientSubscriptionInfo.getFromClerk() != null) { + org.apache.juddi.model.Clerk modelClerk = new org.apache.juddi.model.Clerk(); + mapClerk(apiClientSubscriptionInfo.getFromClerk(), modelClerk); + modelClientSubscriptionInfo.setFromClerk(modelClerk); + } + if (apiClientSubscriptionInfo.getToClerk() != null) { + org.apache.juddi.model.Clerk modelToClerk = new org.apache.juddi.model.Clerk(); + mapClerk(apiClientSubscriptionInfo.getToClerk(), modelToClerk); + modelClientSubscriptionInfo.setToClerk(modelToClerk); + } + + } + + /** + * + * @param apiClerk + * @param modelClerk + */ + public static void mapClerk(org.apache.juddi.api_v3.Clerk apiClerk, org.apache.juddi.model.Clerk modelClerk) { + if (apiClerk != null) { + + modelClerk.setClerkName(apiClerk.getName()); + modelClerk.setCred(apiClerk.getPassword()); + modelClerk.setPublisherId(apiClerk.getPublisher()); + if (apiClerk.getNode() != null) { + org.apache.juddi.model.Node modelNode = new org.apache.juddi.model.Node(); + mapNode(apiClerk.getNode(), modelNode); + modelClerk.setNode(modelNode.getName()); + } + } + } + + /** + * + * @param apiNode + * @param modelNode + */ + public static void mapNode(org.apache.juddi.api_v3.Node apiNode, org.apache.juddi.model.Node modelNode) { + if (apiNode != null) { + + modelNode.setCustodyTransferUrl(apiNode.getCustodyTransferUrl()); + modelNode.setInquiryUrl(apiNode.getInquiryUrl()); + modelNode.setJuddiApiUrl(apiNode.getJuddiApiUrl()); + modelNode.setName(apiNode.getName()); + modelNode.setClientName(apiNode.getClientName()); + modelNode.setProxyTransport(apiNode.getProxyTransport()); + modelNode.setPublishUrl(apiNode.getPublishUrl()); + modelNode.setSecurityUrl(apiNode.getSecurityUrl()); + modelNode.setSubscriptionUrl(apiNode.getSubscriptionUrl()); + modelNode.setSubscriptionListenerUrl(apiNode.getSubscriptionListenerUrl()); + modelNode.setReplicationUrl(apiNode.getReplicationUrl()); + modelNode.setFactoryInitial(apiNode.getFactoryInitial()); + modelNode.setFactoryNamingProvider(apiNode.getFactoryNamingProvider()); + modelNode.setFactoryURLPkgs(apiNode.getFactoryURLPkgs()); + } + } + + private static Reference mapReference(SignedInfo modelSignedInfo, ReferenceType apiReference) { + Reference ref = new Reference(); + ref.setSignedInfo(modelSignedInfo); + String refUri = apiReference.getURI(); + if (refUri == null) { + refUri = ""; + } + ref.setUri(refUri); + List apiTransformList = apiReference.getTransforms().getTransform(); + for (org.w3._2000._09.xmldsig_.TransformType apiTransform : apiTransformList) { + SignatureTransform modelTransform = new SignatureTransform(); + modelTransform.setReference(ref); + modelTransform.setTransform(apiTransform.getAlgorithm()); + + for (Object xform : apiTransform.getContent()) { + SignatureTransformDataValue sdv = mapSignatureTransformDataValue(xform); + sdv.setSignatureTransform(modelTransform); + modelTransform.getSignatureTransformDataValue().add(sdv); + } + + ref.getTransforms().add(modelTransform); + } + String digestMethodStr = apiReference.getDigestMethod().getAlgorithm(); + byte[] digestValueBytes = apiReference.getDigestValue(); + ref.setDigestMethod(digestMethodStr); + ref.setDigestValue(digestValueBytes); + return ref; + } + + private static KeyDataValue mapX509DataType(JAXBElement apiKeyInfoContentJAXB, KeyInfo modelKeyInfo) throws RuntimeException { + X509DataType apiKeyInfoContent = (X509DataType) apiKeyInfoContentJAXB.getValue(); + KeyDataValue modelX509KeyData = new KeyDataValue(); + modelX509KeyData.setKeyDataType(X509DataType.class.getSimpleName()); + modelX509KeyData.setKeyDataName(apiKeyInfoContentJAXB.getName().getLocalPart()); + modelX509KeyData.setKeyInfo(modelKeyInfo); + List x509IssuerSerialOrX509SKIOrX509SubjectNameList = apiKeyInfoContent.getX509IssuerSerialOrX509SKIOrX509SubjectName(); + for (Object x509IssuerSerialOrX509SKIOrX509SubjectNameObj : x509IssuerSerialOrX509SKIOrX509SubjectNameList) { + JAXBElement x509IssuerSerialOrX509SKIOrX509SubjectNameJAXB = (JAXBElement) x509IssuerSerialOrX509SKIOrX509SubjectNameObj; + String tagName = x509IssuerSerialOrX509SKIOrX509SubjectNameJAXB.getName().getLocalPart(); + Object x509IssuerSerialOrX509SKIOrX509SubjectName = x509IssuerSerialOrX509SKIOrX509SubjectNameJAXB.getValue(); + + KeyDataValue modelKeyInfoValue = new KeyDataValue(); + modelKeyInfoValue.setKeyDataName(tagName); + if (x509IssuerSerialOrX509SKIOrX509SubjectName instanceof byte[]) { + modelKeyInfoValue.setKeyDataValueBytes((byte[]) x509IssuerSerialOrX509SKIOrX509SubjectName); + } else if (x509IssuerSerialOrX509SKIOrX509SubjectName instanceof String) { + modelKeyInfoValue.setKeyDataValueString((String) x509IssuerSerialOrX509SKIOrX509SubjectName); + } else if (x509IssuerSerialOrX509SKIOrX509SubjectName instanceof X509IssuerSerialType) { + modelKeyInfoValue.setKeyDataType(X509IssuerSerialType.class.getSimpleName()); + X509IssuerSerialType x509IssuerSerialType = (X509IssuerSerialType) x509IssuerSerialOrX509SKIOrX509SubjectName; + modelKeyInfoValue.setKeyDataValueString(x509IssuerSerialType.getX509IssuerName()); + modelKeyInfoValue.setKeyDataValueBytes(x509IssuerSerialType.getX509SerialNumber().toByteArray()); + } else if (x509IssuerSerialOrX509SKIOrX509SubjectName != null) { + throw new RuntimeException("Unrecognized Value for Element: " + tagName + ": " + x509IssuerSerialOrX509SKIOrX509SubjectName.getClass().getCanonicalName()); + } + modelKeyInfoValue.setKeyDataValue(modelX509KeyData); + modelX509KeyData.getKeyDataValueList().add(modelKeyInfoValue); + } + return modelX509KeyData; + } + + private static KeyDataValue mapKeyName(JAXBElement apiKeyInfoContentJAXB) { + KeyDataValue modelKeyNameKDV = new KeyDataValue(); + modelKeyNameKDV.setKeyDataType(String.class.getSimpleName()); + modelKeyNameKDV.setKeyDataName(apiKeyInfoContentJAXB.getName().getLocalPart()); + modelKeyNameKDV.setKeyDataValueString((String) apiKeyInfoContentJAXB.getValue()); + return modelKeyNameKDV; + } + + private static KeyDataValue mapKeyValue(JAXBElement apiKeyInfoContentJAXB, List keyInfoDataValues) { + KeyValueType kvt = (KeyValueType) apiKeyInfoContentJAXB.getValue(); + KeyDataValue modelKeyValueKDV = new KeyDataValue(); + modelKeyValueKDV.setKeyDataType(KeyValueType.class.getSimpleName()); + modelKeyValueKDV.setKeyDataName(apiKeyInfoContentJAXB.getName().getLocalPart()); + keyInfoDataValues.add(modelKeyValueKDV); + List kvObjList = kvt.getContent(); + for (Object kvObj : kvObjList) { + if (kvObj instanceof JAXBElement) { + JAXBElement kvJAXB = (JAXBElement) kvObj; + Object childVal = kvJAXB.getValue(); + + KeyDataValue childKDV = new KeyDataValue(); + childKDV.setKeyDataValue(modelKeyValueKDV); + childKDV.setKeyDataName(kvJAXB.getName().getLocalPart()); + childKDV.setKeyDataType(childVal.getClass().getSimpleName()); + modelKeyValueKDV.getKeyDataValueList().add(childKDV); + + if (childVal instanceof DSAKeyValueType) { + DSAKeyValueType dsaKeyVal = (DSAKeyValueType) childVal; + String dsaKeyValueTagName = kvJAXB.getName().getLocalPart(); + KeyDataValue dsaKeyValKDV = new KeyDataValue(null, DSAKeyValueType.class.getSimpleName(), dsaKeyValueTagName, null, null, childKDV); + childKDV.getKeyDataValueList().add(dsaKeyValKDV); + + KeyDataValue gValKDV = new KeyDataValue(null, byte[].class.getSimpleName(), "G", dsaKeyVal.getG(), null, dsaKeyValKDV); + dsaKeyValKDV.getKeyDataValueList().add(gValKDV); + + KeyDataValue jValKDV = new KeyDataValue(null, byte[].class.getSimpleName(), "J", dsaKeyVal.getJ(), null, dsaKeyValKDV); + dsaKeyValKDV.getKeyDataValueList().add(jValKDV); + + KeyDataValue pValKDV = new KeyDataValue(null, byte[].class.getSimpleName(), "P", dsaKeyVal.getP(), null, dsaKeyValKDV); + dsaKeyValKDV.getKeyDataValueList().add(pValKDV); + + KeyDataValue pGenCounterValKDV = new KeyDataValue(null, byte[].class.getSimpleName(), "PgenCounter", dsaKeyVal.getPgenCounter(), null, dsaKeyValKDV); + dsaKeyValKDV.getKeyDataValueList().add(pGenCounterValKDV); + + KeyDataValue qValKDV = new KeyDataValue(null, byte[].class.getSimpleName(), "Q", dsaKeyVal.getQ(), null, dsaKeyValKDV); + dsaKeyValKDV.getKeyDataValueList().add(qValKDV); + + KeyDataValue seedValKDV = new KeyDataValue(null, byte[].class.getSimpleName(), "Seed", dsaKeyVal.getSeed(), null, dsaKeyValKDV); + dsaKeyValKDV.getKeyDataValueList().add(seedValKDV); + + KeyDataValue yValKDV = new KeyDataValue(null, byte[].class.getSimpleName(), "Y", dsaKeyVal.getY(), null, dsaKeyValKDV); + dsaKeyValKDV.getKeyDataValueList().add(yValKDV); + } else if (childVal instanceof RSAKeyValueType) { + RSAKeyValueType rsaKeyVal = (RSAKeyValueType) childVal; + String rsaKeyValueTagName = kvJAXB.getName().getLocalPart(); + KeyDataValue rsaKeyValKDV = new KeyDataValue(null, RSAKeyValueType.class.getSimpleName(), rsaKeyValueTagName, null, null, childKDV); + childKDV.getKeyDataValueList().add(rsaKeyValKDV); + + KeyDataValue exponentValKDV = new KeyDataValue(null, byte[].class.getSimpleName(), "Exponent", rsaKeyVal.getExponent(), null, rsaKeyValKDV); + rsaKeyValKDV.getKeyDataValueList().add(exponentValKDV); + + KeyDataValue modulusValKDV = new KeyDataValue(null, byte[].class.getSimpleName(), "Modulus", rsaKeyVal.getModulus(), null, rsaKeyValKDV); + rsaKeyValKDV.getKeyDataValueList().add(modulusValKDV); + } + } + } + return modelKeyValueKDV; + } + + private static KeyDataValue mapRetrievalMethod(String apiKeyInfoContentTagName, KeyInfo modelKeyInfo, RetrievalMethodType retrievalMethodType) { + KeyDataValue retrievalMethodTypeKDV = new KeyDataValue(); + retrievalMethodTypeKDV.setKeyDataName(apiKeyInfoContentTagName); + retrievalMethodTypeKDV.setKeyDataType(RetrievalMethodType.class.getSimpleName()); + retrievalMethodTypeKDV.setKeyInfo(modelKeyInfo); + KeyDataValue uriKDV = new KeyDataValue(); + uriKDV.setKeyDataName("URI"); + uriKDV.setKeyDataType(String.class.getSimpleName()); + uriKDV.setKeyDataValue(retrievalMethodTypeKDV); + uriKDV.setKeyDataValueString(retrievalMethodType.getURI()); + retrievalMethodTypeKDV.getKeyDataValueList().add(uriKDV); + KeyDataValue typeKDV = new KeyDataValue(); + typeKDV.setKeyDataName("Type"); + typeKDV.setKeyDataType(String.class.getSimpleName()); + typeKDV.setKeyDataValue(retrievalMethodTypeKDV); + typeKDV.setKeyDataValueString(retrievalMethodType.getType()); + retrievalMethodTypeKDV.getKeyDataValueList().add(typeKDV); + TransformsType transformsType = retrievalMethodType.getTransforms(); + if (transformsType != null) { + List tTypeList = transformsType.getTransform(); + for (TransformType tType : tTypeList) { + KeyDataValue transformKDV = new KeyDataValue(); + transformKDV.setKeyDataName("Transform"); + transformKDV.setKeyDataType(String.class.getSimpleName()); + transformKDV.setKeyDataValue(retrievalMethodTypeKDV); + transformKDV.setKeyDataValueString(tType.getAlgorithm()); + + for (Object xform : tType.getContent()) { + SignatureTransformDataValue stdv = mapSignatureTransformDataValue(xform); + KeyDataValue transformContentKDV = new KeyDataValue(); + transformContentKDV.setKeyDataType(stdv.getContentType()); + transformContentKDV.setKeyDataValueBytes(stdv.getContentBytes()); + transformContentKDV.setKeyDataValue(transformKDV); + transformKDV.getKeyDataValueList().add(transformContentKDV); + } + + retrievalMethodTypeKDV.getKeyDataValueList().add(transformKDV); + } + } + return retrievalMethodTypeKDV; + } + + private static KeyDataValue mapPGPDataType(String apiKeyInfoContentTagName, KeyInfo modelKeyInfo, PGPDataType pgpDataType) { + KeyDataValue pgpDataTypeKDV = new KeyDataValue(); + pgpDataTypeKDV.setKeyDataName(apiKeyInfoContentTagName); + pgpDataTypeKDV.setKeyDataType(PGPDataType.class.getSimpleName()); + pgpDataTypeKDV.setKeyInfo(modelKeyInfo); + + List pgpDataValues = pgpDataType.getContent(); + for (Object pgpDataValue : pgpDataValues) { + if (pgpDataValue instanceof JAXBElement) { + JAXBElement pgpDataJAXB = (JAXBElement) pgpDataValue; + String tagName = pgpDataJAXB.getName().getLocalPart(); + + KeyDataValue keyIDKDV = new KeyDataValue(); + keyIDKDV.setKeyDataName(tagName); + keyIDKDV.setKeyDataValue(pgpDataTypeKDV); + if (pgpDataJAXB.getValue() instanceof String) { + keyIDKDV.setKeyDataValueString((String) pgpDataJAXB.getValue()); + } else { + keyIDKDV.setKeyDataValueBytes((byte[]) pgpDataJAXB.getValue()); + } + pgpDataTypeKDV.getKeyDataValueList().add(keyIDKDV); + } + } + return pgpDataTypeKDV; + } + + private static KeyDataValue mapSPKIDataType(String apiKeyInfoContentTagName, KeyInfo modelKeyInfo, SPKIDataType spkiDataType) { + KeyDataValue spkiDataTypeKDV = new KeyDataValue(); + spkiDataTypeKDV.setKeyDataName(apiKeyInfoContentTagName); + spkiDataTypeKDV.setKeyDataType(SPKIDataType.class.getSimpleName()); + spkiDataTypeKDV.setKeyInfo(modelKeyInfo); + + List spkiDataValues = spkiDataType.getSPKISexpAndAny(); + for (Object spkiDataValue : spkiDataValues) { + if (spkiDataValue instanceof JAXBElement) { + JAXBElement spkiDataJAXB = (JAXBElement) spkiDataValue; + String tagName = spkiDataJAXB.getName().getLocalPart(); + + KeyDataValue keyIDKDV = new KeyDataValue(); + keyIDKDV.setKeyDataName(tagName); + keyIDKDV.setKeyDataValue(spkiDataTypeKDV); + if (spkiDataJAXB.getValue() instanceof String) { + keyIDKDV.setKeyDataValueString((String) spkiDataJAXB.getValue()); + } else { + keyIDKDV.setKeyDataValueBytes((byte[]) spkiDataJAXB.getValue()); + } + spkiDataTypeKDV.getKeyDataValueList().add(keyIDKDV); + } else { + throw new RuntimeException("Unrecognized type: " + spkiDataValue.getClass().getCanonicalName()); + } + } + return spkiDataTypeKDV; + } + + private static SignatureTransformDataValue mapSignatureTransformDataValue(Object xform) { + SignatureTransformDataValue sdv = new SignatureTransformDataValue(); + if (xform instanceof String) { + sdv.setContentType(String.class.getSimpleName()); + String xformStr = xform.toString(); + try { + byte[] xformBytes = xformStr.getBytes(AuthenticatedService.UTF8); + sdv.setContentBytes(xformBytes); + } catch (Exception e) { + throw new RuntimeException("Failed to encode string due to: " + e.getMessage(), e); + } + } else if (xform instanceof Element) { + sdv.setContentType(Element.class.getCanonicalName()); + Element xformEl = (Element) xform; + String str = serializeTransformElement(xformEl); + try { + sdv.setContentBytes(str.getBytes(AuthenticatedService.UTF8)); + } catch (Exception e) { + throw new RuntimeException("Failed to encode string due to: " + e.getMessage(), e); + } + } else if (xform instanceof byte[]) { + sdv.setContentType(byte[].class.getSimpleName()); + sdv.setContentBytes((byte[]) xform); + } else if (xform instanceof JAXBElement) { + sdv.setContentType(Element.class.getCanonicalName()); + JAXBElement xformJAXB = (JAXBElement) xform; + DOMResult domResult = new DOMResult(); + JAXB.marshal(xformJAXB, domResult); + Element xformEl = ((Document) domResult.getNode()).getDocumentElement(); + String str = serializeTransformElement(xformEl); + try { + sdv.setContentBytes(str.getBytes(AuthenticatedService.UTF8)); + } catch (Exception e) { + throw new RuntimeException("Failed to encode string due to: " + e.getMessage(), e); + } + } else { + throw new RuntimeException("Unrecognized type: " + xform.getClass().getCanonicalName()); + } + return sdv; + } + + private static String serializeTransformElement(Element xformEl) throws DOMException, LSException { + Document document = xformEl.getOwnerDocument(); + DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation(); + LSSerializer serializer = domImplLS.createLSSerializer(); +// serializer.getDomConfig().setParameter("namespaces", true); +// serializer.getDomConfig().setParameter("namespace-declarations", true); + serializer.getDomConfig().setParameter("canonical-form", false); + serializer.getDomConfig().setParameter("xml-declaration", false); + String str = serializer.writeToString(xformEl); + return str; + } + + public static org.apache.juddi.model.ChangeRecord mapChangeRecord(ChangeRecord rec) throws UnsupportedEncodingException { + org.apache.juddi.model.ChangeRecord r = new org.apache.juddi.model.ChangeRecord(); + //r.setId(rec.getChangeID().getOriginatingUSN()); + r.setOriginatingUSN(rec.getChangeID().getOriginatingUSN()); + if (r.getOriginatingUSN() == null) { + // logger.warn("strange, the getOriginatingUSN is null!!"); + // JAXB.marshal(rec, System.out); + // Thread.dumpStack(); + } + r.setNodeID(rec.getChangeID().getNodeID()); + if (rec.getChangeRecordNewData() != null) { + r.setRecordType(org.apache.juddi.model.ChangeRecord.RecordType.ChangeRecordNewData); + r.setEntityKey(rec.getChangeRecordNewData().getOperationalInfo().getEntityKey()); + if (rec.getChangeRecordNewData().getOperationalInfo().getEntityKey() == null) { + throw new UnsupportedEncodingException("entity key is null! make sure it's filled out before saving!"); + } + } else if (rec.getChangeRecordAcknowledgement() != null) { + r.setRecordType(org.apache.juddi.model.ChangeRecord.RecordType.ChangeRecordAcknowledgement); + } else if (rec.getChangeRecordConditionFailed() != null) { + r.setRecordType(org.apache.juddi.model.ChangeRecord.RecordType.ChangeRecordConditionFailed); + } else if (rec.getChangeRecordCorrection() != null) { + r.setRecordType(org.apache.juddi.model.ChangeRecord.RecordType.ChangeRecordCorrection); + } else if (rec.getChangeRecordDelete() != null) { + r.setRecordType(org.apache.juddi.model.ChangeRecord.RecordType.ChangeRecordDelete); + if (rec.getChangeRecordDelete().getTModelKey() != null) { + r.setEntityKey(rec.getChangeRecordDelete().getTModelKey()); + } + if (rec.getChangeRecordDelete().getBindingKey() != null) { + r.setEntityKey(rec.getChangeRecordDelete().getBindingKey()); + } + if (rec.getChangeRecordDelete().getBusinessKey() != null) { + r.setEntityKey(rec.getChangeRecordDelete().getBusinessKey()); + } + if (rec.getChangeRecordDelete().getServiceKey() != null) { + r.setEntityKey(rec.getChangeRecordDelete().getServiceKey()); + } + } else if (rec.getChangeRecordDeleteAssertion() != null) { + r.setRecordType(org.apache.juddi.model.ChangeRecord.RecordType.ChangeRecordDeleteAssertion); + } else if (rec.getChangeRecordHide() != null) { + r.setRecordType(org.apache.juddi.model.ChangeRecord.RecordType.ChangeRecordHide); + r.setEntityKey(rec.getChangeRecordHide().getTModelKey()); + } else if (rec.getChangeRecordNewDataConditional() != null) { + r.setRecordType(org.apache.juddi.model.ChangeRecord.RecordType.ChangeRecordNewDataConditional); + } else if (rec.getChangeRecordNull() != null) { + r.setRecordType(org.apache.juddi.model.ChangeRecord.RecordType.ChangeRecordNull); + } else if (rec.getChangeRecordPublisherAssertion() != null) { + r.setRecordType(org.apache.juddi.model.ChangeRecord.RecordType.ChangeRecordPublisherAssertion); + } else { + throw new UnsupportedEncodingException("unknown type!"); + } + + StringWriter sw = new StringWriter(); + JAXB.marshal(rec, sw); + r.setContents(sw.toString().getBytes(AuthenticatedService.UTF8)); + return r; + + } + + public static void mapOperationalInfo(UddiEntity model, OperationalInfo operationalInfo) { + if (operationalInfo == null || model == null) { + return; + } + if (operationalInfo.getCreated() != null) { + model.setCreated(operationalInfo.getCreated().toGregorianCalendar().getTime()); + } + model.setAuthorizedName(operationalInfo.getAuthorizedName()); + if (operationalInfo.getModified() != null) { + model.setModified(operationalInfo.getModified().toGregorianCalendar().getTime()); + } + if (operationalInfo.getModifiedIncludingChildren() != null) { + model.setModifiedIncludingChildren(operationalInfo.getModifiedIncludingChildren().toGregorianCalendar().getTime()); + } + model.setNodeId(operationalInfo.getNodeID()); + + } + + public static void mapOperationalInfoIncludingChildren(BusinessEntity model, OperationalInfo operationalInfo) { + if (operationalInfo == null || model == null) { + return; + } + if (operationalInfo.getCreated() != null) { + model.setCreated(operationalInfo.getCreated().toGregorianCalendar().getTime()); + } + model.setAuthorizedName(operationalInfo.getAuthorizedName()); + if (operationalInfo.getModified() != null) { + model.setModified(operationalInfo.getModified().toGregorianCalendar().getTime()); + } + if (operationalInfo.getModifiedIncludingChildren() != null) { + model.setModifiedIncludingChildren(operationalInfo.getModifiedIncludingChildren().toGregorianCalendar().getTime()); + } + model.setNodeId(operationalInfo.getNodeID()); + for (int i = 0; i < model.getBusinessServices().size(); i++) { + mapOperationalInfo(model.getBusinessServices().get(i), operationalInfo); + for (int k = 0; k < model.getBusinessServices().get(i).getBindingTemplates().size(); k++) { + mapOperationalInfo(model.getBusinessServices().get(i).getBindingTemplates().get(k), operationalInfo); + } + } + + } + + public static void mapReplicationConfiguration(ReplicationConfiguration replicationConfiguration, org.apache.juddi.model.ReplicationConfiguration model, EntityManager em) throws DispositionReportFaultMessage { + if (replicationConfiguration == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.replication.configNull")); + } + model.setMaximumTimeToGetChanges(replicationConfiguration.getMaximumTimeToGetChanges()); + model.setMaximumTimeToSyncRegistry(replicationConfiguration.getMaximumTimeToSyncRegistry()); + //this is set by the service when saving + model.setSerialNumber(null); + + //the spec doesn't specify what the format should be, however there was an example + //2002 03 04 1859Z + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddkkmmZ"); + model.setTimeOfConfigurationUpdate(sdf.format(new Date())); + if (replicationConfiguration.getRegistryContact() != null) { + model.setContact(mapContact(replicationConfiguration.getRegistryContact().getContact(), model)); + } + mapCommunicationGraph(model, replicationConfiguration.getCommunicationGraph(), em); + model.setOperator(mapOperators(replicationConfiguration, model)); + if (replicationConfiguration.getSignature() != null) { + model.setSignatures(mapApiSignaturesToModelSignatures(replicationConfiguration.getSignature())); + } + + } + + private static Contact mapContact(org.uddi.api_v3.Contact contact, org.apache.juddi.model.ReplicationConfiguration model) throws DispositionReportFaultMessage { + Contact cmodel = new Contact(); + cmodel.setReplicationConfigId(model); + cmodel.setAddresses(new ArrayList
()); + mapContactAddresses(contact.getAddress(), cmodel.getAddresses(), cmodel); + if (cmodel.getAddresses().isEmpty()) { + cmodel.setAddresses(null); + } + return cmodel; + } + + private static List mapOperators(ReplicationConfiguration cfg, org.apache.juddi.model.ReplicationConfiguration modelparent) throws DispositionReportFaultMessage { + if (cfg == null) { + return null; + } + List api = cfg.getOperator(); + if (api == null) { + return null; + } + List model = new ArrayList(); + for (int i = 0; i < api.size(); i++) { + Operator op = new Operator(); + op.setParent(modelparent); + + op.setSoapReplicationURL(api.get(i).getSoapReplicationURL()); + + if (!api.get(i).getContact().isEmpty()) { + op.setContact(new ArrayList()); + for (int k = 0; k < api.get(i).getContact().size(); k++) { + op.getContact().add(mapContact(api.get(i).getContact().get(k), null)); + } + } + op.setOperatorNodeID(api.get(i).getOperatorNodeID()); + op.setOperatorStatus(mapOperatorStatus(api.get(i).getOperatorStatus())); + if (!api.get(i).getKeyInfo().isEmpty()) { + op.setKeyInfo(new ArrayList()); + for (int k = 0; k < api.get(i).getKeyInfo().size(); k++) { + org.apache.juddi.model.KeyInfo modelKeyInfo = new KeyInfo(); + modelKeyInfo.setXmlID(api.get(i).getKeyInfo().get(i).getId()); + modelKeyInfo.setKeyDataValue(new ArrayList()); + if (api.get(i).getKeyInfo().get(i).getContent() != null) { + modelKeyInfo.setKeyDataValue(new ArrayList()); + for (int x = 0; x < api.get(i).getKeyInfo().get(k).getContent().size(); x++) { + mapKeyValue((JAXBElement) api.get(i).getKeyInfo().get(k).getContent().get(x), modelKeyInfo.getKeyDataValue()); + } + } + op.getKeyInfo().add(modelKeyInfo); + } + + } + model.add(op); + + } + return model; + } + + private static OperatorStatusType mapOperatorStatus(org.uddi.repl_v3.OperatorStatusType operatorStatus) { + switch (operatorStatus) { + case NEW: + return OperatorStatusType.NEW; + case NORMAL: + return OperatorStatusType.NORMAL; + case RESIGNED: + return OperatorStatusType.RESIGNED; + } + return null; + } + + private static void mapCommunicationGraph(org.apache.juddi.model.ReplicationConfiguration model, CommunicationGraph communicationGraph, EntityManager em) throws ValueNotAllowedException { + + if (model == null) { + return; + } + + /** + * Following the listing of nodes is the controlledMessage + * element that lists the set of messages over which this + * communication graph is intended to administer control of. If + * a message element local name is listed in the + * controlledMessage element, then such messages SHALL only be + * sent between nodes that are listed in the subsequent edges of + * the graph. In contrast, communication restrictions are not + * imposed on replication messages not identified in the + * controlledMessage element. + */ + if (communicationGraph.getControlledMessage() != null) { + model.setControlMessage(new ArrayList()); + + for (int k = 0; k < communicationGraph.getControlledMessage().size(); k++) { + ControlMessage BC = new ControlMessage(communicationGraph.getControlledMessage().get(k)); + BC.setReplicationConfiguration(model); + + model.getControlMessage().add(BC); + } + } + + for (int i = 0; i < communicationGraph.getNode().size(); i++) { + ReplicationConfigurationNode replicationConfigurationNode = new ReplicationConfigurationNode(); + + replicationConfigurationNode.setNodeName(communicationGraph.getNode().get(i)); + replicationConfigurationNode.setParent(model); + model.getNode().add(replicationConfigurationNode); + } + if (communicationGraph.getEdge() != null && !communicationGraph.getEdge().isEmpty()) { + List ret = new ArrayList(); + for (int i = 0; i < communicationGraph.getEdge().size(); i++) { + Edge e = new Edge(); + e.setReplicationConfiguration(model); + + e.setMessageReceiver(communicationGraph.getEdge().get(i).getMessageReceiver()); + e.setMessageSender(communicationGraph.getEdge().get(i).getMessageSender()); + + /** + * The message elements contain the local name + * of the Replication API message elements. They + * indicate that only messages of the type + * explicitly identified for a particular edge + * MAY be sent from the specified messageSender + * to the specified messageReceiver. + */ + if (communicationGraph.getEdge().get(i).getMessage() != null) { + e.setMessage(new ArrayList()); + for (int k = 0; k < communicationGraph.getEdge().get(i).getMessage().size(); k++) { + ControlMessage controlMessage = new ControlMessage(communicationGraph.getEdge().get(i).getMessage().get(k)); + controlMessage.setReplicationConfiguration(model); + controlMessage.setParentEdge(e); + e.getMessages().add(controlMessage); + } + } + if (communicationGraph.getEdge().get(i).getMessageReceiverAlternate() != null) { + List eras = new ArrayList(); + for (String s : communicationGraph.getEdge().get(i).getMessageReceiverAlternate()) { + EdgeReceiverAlternate x = new EdgeReceiverAlternate(); + x.setParent(e); + x.setReceiverAlternate(s); + eras.add(x); + } + e.setMessageReceiverAlternate(eras); + + } + + ret.add(e); + } + model.setEdge(ret); + } + } + + public static void mapOperationalInfoIncludingChildren(BusinessService model, OperationalInfo operationalInfo) { + if (operationalInfo == null || model == null) { + return; + } + if (operationalInfo.getCreated() != null) { + model.setCreated(operationalInfo.getCreated().toGregorianCalendar().getTime()); + } + model.setAuthorizedName(operationalInfo.getAuthorizedName()); + if (operationalInfo.getModified() != null) { + model.setModified(operationalInfo.getModified().toGregorianCalendar().getTime()); + } + if (operationalInfo.getModifiedIncludingChildren() != null) { + model.setModifiedIncludingChildren(operationalInfo.getModifiedIncludingChildren().toGregorianCalendar().getTime()); + } + model.setNodeId(operationalInfo.getNodeID()); + + for (int k = 0; k < model.getBindingTemplates().size(); k++) { + mapOperationalInfo(model.getBindingTemplates().get(k), operationalInfo); + } + + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/mapping/MappingModelToApi.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/mapping/MappingModelToApi.java similarity index 98% rename from juddi-core/src/main/java/org/apache/juddi/mapping/MappingModelToApi.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/mapping/MappingModelToApi.java index 24bb67452..81d862cca 100644 --- a/juddi-core/src/main/java/org/apache/juddi/mapping/MappingModelToApi.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/mapping/MappingModelToApi.java @@ -1,1364 +1,1364 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.mapping; - -import java.math.BigInteger; -import java.util.GregorianCalendar; -import javax.xml.datatype.DatatypeConfigurationException; -import javax.xml.datatype.DatatypeFactory; -import org.w3._2000._09.xmldsig_.X509IssuerSerialType; -import java.io.ByteArrayInputStream; -import java.io.StringReader; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.persistence.EntityManager; -import javax.xml.bind.JAXB; -import javax.xml.bind.JAXBElement; - -import javax.xml.bind.JAXBException; -import javax.xml.namespace.QName; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.Property; -import org.apache.juddi.jaxb.JAXBMarshaller; -import org.apache.juddi.model.CanonicalizationMethod; -import org.apache.juddi.model.ControlMessage; -import org.apache.juddi.model.Edge; -import org.apache.juddi.model.EdgeReceiverAlternate; -import org.apache.juddi.model.KeyInfo; -import org.apache.juddi.model.OverviewDoc; -import org.apache.juddi.model.Reference; -import org.apache.juddi.model.SignatureTransform; -import org.apache.juddi.model.SignatureValue; -import org.apache.juddi.model.SignedInfo; -import org.apache.juddi.model.UddiEntity; -import org.apache.juddi.model.KeyDataValue; -import org.apache.juddi.model.Node; -import org.apache.juddi.model.ReplicationConfiguration; -import org.apache.juddi.model.ReplicationConfigurationNode; -import org.apache.juddi.model.Signature; -import org.apache.juddi.model.SignatureTransformDataValue; -import org.apache.juddi.subscription.TypeConvertor; -import org.apache.juddi.v3.client.cryptor.XmlUtils; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.FatalErrorException; -import org.uddi.api_v3.BusinessEntity; -import org.uddi.api_v3.CompletionStatus; -import org.uddi.api_v3.Contact; -import org.uddi.api_v3.Contacts; -import org.uddi.api_v3.OperationalInfo; -import org.uddi.api_v3.PersonName; -import org.uddi.repl_v3.ChangeRecord; -import org.uddi.repl_v3.ChangeRecordIDType; -import org.uddi.repl_v3.CommunicationGraph; -import org.uddi.repl_v3.Operator; -import org.uddi.repl_v3.OperatorStatusType; -import org.uddi.sub_v3.SubscriptionFilter; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.w3._2000._09.xmldsig_.CanonicalizationMethodType; -import org.w3._2000._09.xmldsig_.DSAKeyValueType; -import org.w3._2000._09.xmldsig_.DigestMethodType; -import org.w3._2000._09.xmldsig_.KeyInfoType; -import org.w3._2000._09.xmldsig_.KeyValueType; -import org.w3._2000._09.xmldsig_.PGPDataType; -import org.w3._2000._09.xmldsig_.RSAKeyValueType; -import org.w3._2000._09.xmldsig_.ReferenceType; -import org.w3._2000._09.xmldsig_.RetrievalMethodType; -import org.w3._2000._09.xmldsig_.SPKIDataType; -import org.w3._2000._09.xmldsig_.SignatureMethodType; -import org.w3._2000._09.xmldsig_.SignatureType; -import org.w3._2000._09.xmldsig_.SignatureValueType; -import org.w3._2000._09.xmldsig_.SignedInfoType; -import org.w3._2000._09.xmldsig_.TransformType; -import org.w3._2000._09.xmldsig_.TransformsType; -import org.w3._2000._09.xmldsig_.X509DataType; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -/** - * @author Jeff Faath - * @author Kurt T Stam - */ -public class MappingModelToApi { - - private static Log logger = LogFactory.getLog(MappingModelToApi.class); - - public static void mapPublisher(org.apache.juddi.model.Publisher modelPublisher, - org.apache.juddi.api_v3.Publisher apiPublisher) - throws DispositionReportFaultMessage { - - apiPublisher.setAuthorizedName(modelPublisher.getAuthorizedName()); - apiPublisher.setPublisherName(modelPublisher.getPublisherName()); - apiPublisher.setEmailAddress(modelPublisher.getEmailAddress()); - apiPublisher.setIsAdmin(modelPublisher.getIsAdmin()); - apiPublisher.setIsEnabled(modelPublisher.getIsEnabled()); - apiPublisher.setMaxBindingsPerService(modelPublisher.getMaxBindingsPerService()); - apiPublisher.setMaxBusinesses(modelPublisher.getMaxBusinesses()); - apiPublisher.setMaxServicePerBusiness(modelPublisher.getMaxServicesPerBusiness()); - apiPublisher.setMaxTModels(modelPublisher.getMaxTmodels()); - mapSignature(modelPublisher.getSignatures(), apiPublisher.getSignature()); - } - - public static void mapBusinessEntity(org.apache.juddi.model.BusinessEntity modelBusinessEntity, - org.uddi.api_v3.BusinessEntity apiBusinessEntity) - throws DispositionReportFaultMessage { - - apiBusinessEntity.setBusinessKey(modelBusinessEntity.getEntityKey()); - - mapBusinessNames(modelBusinessEntity.getBusinessNames(), apiBusinessEntity.getName()); - mapBusinessDescriptions(modelBusinessEntity.getBusinessDescrs(), apiBusinessEntity.getDescription()); - - mapDiscoveryUrls(modelBusinessEntity.getDiscoveryUrls(), apiBusinessEntity.getDiscoveryURLs(), apiBusinessEntity); - mapContacts(modelBusinessEntity.getContacts(), apiBusinessEntity.getContacts(), apiBusinessEntity); - mapBusinessIdentifiers(modelBusinessEntity.getBusinessIdentifiers(), apiBusinessEntity.getIdentifierBag(), apiBusinessEntity); - apiBusinessEntity.setCategoryBag(mapCategoryBag(modelBusinessEntity.getCategoryBag(), apiBusinessEntity.getCategoryBag())); - - mapBusinessServices(modelBusinessEntity.getBusinessServices(), modelBusinessEntity.getServiceProjections(), apiBusinessEntity.getBusinessServices(), apiBusinessEntity); - - mapSignature(modelBusinessEntity.getSignatures(), apiBusinessEntity.getSignature()); - } - - public static void mapSignature(List signatureList, - List apiSignatureList) - throws DispositionReportFaultMessage { - apiSignatureList.clear(); - for (org.apache.juddi.model.Signature modelSig : signatureList) { - SignatureType apiSignature = new SignatureType(); - apiSignature.setId(modelSig.getXmlID()); - - SignedInfo modelSignedInfo = modelSig.getSignedInfo(); - SignedInfoType apiSignedInfoType = new SignedInfoType(); - apiSignature.setSignedInfo(apiSignedInfoType); - // Canonicalization method - CanonicalizationMethod modelCanonMethod = modelSignedInfo.getCanonicalizationMethod(); - CanonicalizationMethodType apiCanonMethod = new CanonicalizationMethodType(); - apiCanonMethod.setAlgorithm(modelCanonMethod.getAlgorithm()); - apiSignedInfoType.setCanonicalizationMethod(apiCanonMethod); - - // Signature Method - String sigAlg = modelSignedInfo.getSignatureMethod().getAlgorithm(); - SignatureMethodType apiSigMethod = new SignatureMethodType(); - apiSigMethod.setAlgorithm(sigAlg); - apiSignedInfoType.setSignatureMethod(apiSigMethod); - - // References - List modelReferenceList = modelSignedInfo.getReference(); - List apiReferenceList = apiSignedInfoType.getReference(); - for (Reference modelRef : modelReferenceList) { - ReferenceType apiRef = new ReferenceType(); - String refUri = modelRef.getUri(); - if (refUri == null) { - refUri = ""; - } - apiRef.setURI(refUri); - - List modelSigTransformList = modelRef.getTransforms(); - TransformsType apiTransformsType = apiRef.getTransforms(); - if (apiTransformsType == null) { - apiTransformsType = new TransformsType(); - apiRef.setTransforms(apiTransformsType); - } - List apiTransformList = apiTransformsType.getTransform(); - for (SignatureTransform modelSigTransform : modelSigTransformList) { - String modelTransformAlgStr = modelSigTransform.getTransform(); - TransformType apiTransform = new TransformType(); - apiTransform.setAlgorithm(modelTransformAlgStr); - - List sigTransformSDVList = modelSigTransform.getSignatureTransformDataValue(); - for (SignatureTransformDataValue sigTransformSDV : sigTransformSDVList) { - String type = sigTransformSDV.getContentType(); - byte[] xformBytes = sigTransformSDV.getContentBytes(); - Object transformObject = convertDataToTransformContent(type, xformBytes); - apiTransform.getContent().add(transformObject); - } - - apiTransformList.add(apiTransform); - } - - String digestMethodStr = modelRef.getDigestMethod(); - byte[] digestValBytes = modelRef.getDigestValue(); - - DigestMethodType apiDigestMethod = new DigestMethodType(); - apiDigestMethod.setAlgorithm(digestMethodStr); - apiRef.setDigestMethod(apiDigestMethod); - apiRef.setDigestValue(digestValBytes); - - apiReferenceList.add(apiRef); - } - - // Signature Value - SignatureValueType apiSignatureValue = new SignatureValueType(); - SignatureValue modelSigValue = modelSig.getSignatureValue(); - apiSignatureValue.setId(modelSigValue.getXmlID()); - apiSignatureValue.setValue(modelSigValue.getValue()); - - apiSignature.setSignatureValue(apiSignatureValue); - - KeyInfoType apiKeyInfo = new KeyInfoType(); - KeyInfo modelKeyInfo = modelSig.getKeyInfo(); - apiKeyInfo.setId(modelKeyInfo.getXmlID()); - - List modelKeyDataValueList = modelKeyInfo.getKeyDataValue(); - List apiX509KeyInfoList = apiKeyInfo.getContent(); - mapModelKeyDataValue(modelKeyDataValueList, apiX509KeyInfoList); - apiSignature.setKeyInfo(apiKeyInfo); - apiSignatureList.add(apiSignature); - } - } - - private static void mapModelKeyDataValue(List modelKeyDataValueList, List parentKeyDataList) { - for (KeyDataValue modelKeyDataValue : modelKeyDataValueList) { - String tagName = modelKeyDataValue.getKeyDataName(); - String dataType = modelKeyDataValue.getKeyDataType(); - byte[] contentBytes = modelKeyDataValue.getKeyDataValueBytes(); - String contentStr = modelKeyDataValue.getKeyDataValueString(); - Object contents = contentBytes != null ? contentBytes : contentStr; - - if (contents == null) { - List childKeyDataList = new ArrayList(); - if (dataType.equals(X509DataType.class.getSimpleName())) { - X509DataType x509DataType = new X509DataType(); - mapModelKeyDataValue(modelKeyDataValue.getKeyDataValueList(), childKeyDataList); - x509DataType.getX509IssuerSerialOrX509SKIOrX509SubjectName().addAll(childKeyDataList); - JAXBElement dataJAXB = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", tagName), X509DataType.class, x509DataType); - parentKeyDataList.add(dataJAXB); - } else if (dataType.equals(RetrievalMethodType.class.getSimpleName())) { - RetrievalMethodType retrievalMethodType = new RetrievalMethodType(); - TransformsType transformsType = new TransformsType(); - for (KeyDataValue retrievalMethodKDV : modelKeyDataValue.getKeyDataValueList()) { - if (retrievalMethodKDV.getKeyDataName().equals("Transform")) { - TransformType tType = new TransformType(); - tType.setAlgorithm(retrievalMethodKDV.getKeyDataValueString()); - - for (KeyDataValue transformContentKDV : retrievalMethodKDV.getKeyDataValueList()) { - String type = transformContentKDV.getKeyDataType(); - byte[] xformBytes = transformContentKDV.getKeyDataValueBytes(); - Object transformObject = convertDataToTransformContent(type, xformBytes); - tType.getContent().add(transformObject); - } - - transformsType.getTransform().add(tType); - } else if (retrievalMethodKDV.getKeyDataName().equals("Type")) { - retrievalMethodType.setType(retrievalMethodKDV.getKeyDataValueString()); - } else if (retrievalMethodKDV.getKeyDataName().equals("URI")) { - retrievalMethodType.setURI(retrievalMethodKDV.getKeyDataValueString()); - } else { - throw new RuntimeException("Unrecognized key data type: " + retrievalMethodKDV.getKeyDataType()); - } - } - if (transformsType.getTransform() != null && !transformsType.getTransform().isEmpty()) { - retrievalMethodType.setTransforms(transformsType); - } - JAXBElement dataJAXB = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", tagName), RetrievalMethodType.class, retrievalMethodType); - parentKeyDataList.add(dataJAXB); - } else if (dataType.equals(PGPDataType.class.getSimpleName())) { - PGPDataType pgpDataType = new PGPDataType(); - - for (KeyDataValue pgpDataKDV : modelKeyDataValue.getKeyDataValueList()) { - String pgpDataTagName = pgpDataKDV.getKeyDataName(); - Object pgpDataContents = pgpDataKDV.getKeyDataValueBytes() != null ? pgpDataKDV.getKeyDataValueBytes() : pgpDataKDV.getKeyDataValueString(); - Class pgpDataClazz = pgpDataContents.getClass(); - JAXBElement jaxb = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", pgpDataTagName), pgpDataClazz, pgpDataContents); - pgpDataType.getContent().add(jaxb); - } - - JAXBElement dataJAXB = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", tagName), PGPDataType.class, pgpDataType); - parentKeyDataList.add(dataJAXB); - } else if (dataType.equals(SPKIDataType.class.getSimpleName())) { - SPKIDataType spkiDataType = new SPKIDataType(); - - for (KeyDataValue spkiDataKDV : modelKeyDataValue.getKeyDataValueList()) { - String spkiDataTagName = spkiDataKDV.getKeyDataName(); - Object spkiDataContents = spkiDataKDV.getKeyDataValueBytes() != null ? spkiDataKDV.getKeyDataValueBytes() : spkiDataKDV.getKeyDataValueString(); - Class spkiDataClazz = spkiDataContents.getClass(); - JAXBElement jaxb = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", spkiDataTagName), spkiDataClazz, spkiDataContents); - spkiDataType.getSPKISexpAndAny().add(jaxb); - } - - JAXBElement dataJAXB = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", tagName), SPKIDataType.class, spkiDataType); - parentKeyDataList.add(dataJAXB); - } else if (dataType.equals(KeyValueType.class.getSimpleName())) { - KeyValueType keyValueType = new KeyValueType(); - for (KeyDataValue keyValueDataKDV : modelKeyDataValue.getKeyDataValueList()) { - for (KeyDataValue keyValueDataChildKDV : keyValueDataKDV.getKeyDataValueList()) { - String keyDataDataType = keyValueDataChildKDV.getKeyDataType(); - if (keyDataDataType.equals("DSAKeyValueType")) { - DSAKeyValueType dsaKeyValueType = new DSAKeyValueType(); - for (KeyDataValue dsaKDV : keyValueDataChildKDV.getKeyDataValueList()) { - if ("G".equals(dsaKDV.getKeyDataName())) { - dsaKeyValueType.setG(dsaKDV.getKeyDataValueBytes()); - } else if ("P".equals(dsaKDV.getKeyDataName())) { - dsaKeyValueType.setP(dsaKDV.getKeyDataValueBytes()); - } else if ("Q".equals(dsaKDV.getKeyDataName())) { - dsaKeyValueType.setQ(dsaKDV.getKeyDataValueBytes()); - } else if ("Y".equals(dsaKDV.getKeyDataName())) { - dsaKeyValueType.setY(dsaKDV.getKeyDataValueBytes()); - } else if ("J".equals(dsaKDV.getKeyDataName())) { - dsaKeyValueType.setJ(dsaKDV.getKeyDataValueBytes()); - } else if ("Seed".equals(dsaKDV.getKeyDataName())) { - dsaKeyValueType.setSeed(dsaKDV.getKeyDataValueBytes()); - } else if ("PgenCounter".equals(dsaKDV.getKeyDataName())) { - dsaKeyValueType.setPgenCounter(dsaKDV.getKeyDataValueBytes()); - } else { - throw new RuntimeException("Unrecognized dsa type: " + dsaKDV.getKeyDataName()); - } - } - JAXBElement jaxb = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", keyValueDataChildKDV.getKeyDataName()), DSAKeyValueType.class, dsaKeyValueType); - keyValueType.getContent().add(jaxb); - } else if (keyDataDataType.equals("RSAKeyValueType")) { - RSAKeyValueType rsaKeyValueType = new RSAKeyValueType(); - for (KeyDataValue rsaKDV : keyValueDataChildKDV.getKeyDataValueList()) { - if ("Exponent".equals(rsaKDV.getKeyDataName())) { - rsaKeyValueType.setExponent(rsaKDV.getKeyDataValueBytes()); - } else if ("Modulus".equals(rsaKDV.getKeyDataName())) { - rsaKeyValueType.setModulus(rsaKDV.getKeyDataValueBytes()); - } else { - throw new RuntimeException("Unrecognized dsa type: " + rsaKDV.getKeyDataName()); - } - } - JAXBElement jaxb = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", keyValueDataChildKDV.getKeyDataName()), RSAKeyValueType.class, rsaKeyValueType); - keyValueType.getContent().add(jaxb); - } else { - throw new RuntimeException("Unrecognized element: " + keyDataDataType); - } - } - } - JAXBElement dataJAXB = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", tagName), KeyValueType.class, keyValueType); - parentKeyDataList.add(dataJAXB); - } else { - throw new RuntimeException("Unrecognized type: " + dataType); - } - } else { - if (dataType != null && dataType.equals(X509IssuerSerialType.class.getSimpleName())) { - X509IssuerSerialType x509IssuerSerialType = new X509IssuerSerialType(); - x509IssuerSerialType.setX509IssuerName(contentStr); - x509IssuerSerialType.setX509SerialNumber(new BigInteger(contentBytes)); - JAXBElement dataJAXB = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", tagName), X509IssuerSerialType.class, x509IssuerSerialType); - parentKeyDataList.add(dataJAXB); - } else { - JAXBElement dataJAXB = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", tagName), contents.getClass(), contents); - parentKeyDataList.add(dataJAXB); - } - } - } - } - - public static void mapBusinessNames(List modelNameList, - List apiNameList) - throws DispositionReportFaultMessage { - apiNameList.clear(); - - for (org.apache.juddi.model.BusinessName modelName : modelNameList) { - org.uddi.api_v3.Name apiName = new org.uddi.api_v3.Name(); - apiName.setLang(modelName.getLangCode()); - apiName.setValue(modelName.getName()); - apiNameList.add(apiName); - } - } - - public static void mapBusinessDescriptions(List modelDescList, - List apiDescList) - throws DispositionReportFaultMessage { - apiDescList.clear(); - - for (org.apache.juddi.model.BusinessDescr modelDesc : modelDescList) { - org.uddi.api_v3.Description apiDesc = new org.uddi.api_v3.Description(); - apiDesc.setLang(modelDesc.getLangCode()); - apiDesc.setValue(modelDesc.getDescr()); - apiDescList.add(apiDesc); - } - } - - public static void mapDiscoveryUrls(List modelDiscUrlList, - org.uddi.api_v3.DiscoveryURLs apiDiscUrls, - org.uddi.api_v3.BusinessEntity apiBusinessEntity) - throws DispositionReportFaultMessage { - if (modelDiscUrlList == null || modelDiscUrlList.size() == 0) { - return; - } - - if (apiDiscUrls == null) { - apiDiscUrls = new org.uddi.api_v3.DiscoveryURLs(); - } - - List apiDiscUrlList = apiDiscUrls.getDiscoveryURL(); - apiDiscUrlList.clear(); - - for (org.apache.juddi.model.DiscoveryUrl modelDiscUrl : modelDiscUrlList) { - org.uddi.api_v3.DiscoveryURL apiDiscUrl = new org.uddi.api_v3.DiscoveryURL(); - apiDiscUrl.setUseType(modelDiscUrl.getUseType()); - String discoveryURL = modelDiscUrl.getUrl(); - try { - String baseUrl = AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL); - if (baseUrl == null) { - logger.warn("Token '" + Property.JUDDI_BASE_URL + "' not found in the juddiv3.xml, defaulting to '" - + Property.DEFAULT_BASE_URL + "'"); - baseUrl = Property.DEFAULT_BASE_URL; - } - discoveryURL = discoveryURL.replaceAll("\\$\\{" + Property.JUDDI_BASE_URL + "\\}", baseUrl); - - baseUrl = AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE); - if (baseUrl == null) { - logger.warn("Token '" + Property.JUDDI_BASE_URL_SECURE + "' not found in the juddiv3.xml, defaulting to '" - + Property.JUDDI_BASE_URL_SECURE + "'"); - baseUrl = Property.DEFAULT_BASE_URL_SECURE; - } - discoveryURL = discoveryURL.replaceAll("\\$\\{" + Property.JUDDI_BASE_URL_SECURE + "\\}", baseUrl); - - } catch (ConfigurationException e) { - logger.error(e.getMessage(), e); - } - apiDiscUrl.setValue(discoveryURL); - apiDiscUrlList.add(apiDiscUrl); - } - apiBusinessEntity.setDiscoveryURLs(apiDiscUrls); - } - - public static void mapContact(org.apache.juddi.model.Contact modelContact, - org.uddi.api_v3.Contact apiContact) throws DispositionReportFaultMessage { - if (apiContact == null) { - apiContact = new org.uddi.api_v3.Contact(); - } - apiContact.setUseType(modelContact.getUseType()); - - mapPersonNames(modelContact.getPersonNames(), apiContact.getPersonName()); - mapContactDescriptions(modelContact.getContactDescrs(), apiContact.getDescription()); - mapContactEmails(modelContact.getEmails(), apiContact.getEmail()); - mapContactPhones(modelContact.getPhones(), apiContact.getPhone()); - mapContactAddresses(modelContact.getAddresses(), apiContact.getAddress()); - - } - - public static void mapContacts(List modelContactList, - org.uddi.api_v3.Contacts apiContacts, - org.uddi.api_v3.BusinessEntity apiBusinessEntity) - throws DispositionReportFaultMessage { - if (modelContactList == null || modelContactList.size() == 0) { - return; - } - - if (apiContacts == null) { - apiContacts = new org.uddi.api_v3.Contacts(); - } - - List apiContactList = apiContacts.getContact(); - apiContactList.clear(); - - for (org.apache.juddi.model.Contact modelContact : modelContactList) { - org.uddi.api_v3.Contact apiContact = new org.uddi.api_v3.Contact(); - - mapContact(modelContact,apiContact); - - apiContactList.add(apiContact); - } - apiBusinessEntity.setContacts(apiContacts); - } - - public static void mapContactDescriptions(List modelDescList, - List apiDescList) - throws DispositionReportFaultMessage { - apiDescList.clear(); - - for (org.apache.juddi.model.ContactDescr modelDesc : modelDescList) { - org.uddi.api_v3.Description apiDesc = new org.uddi.api_v3.Description(); - apiDesc.setLang(modelDesc.getLangCode()); - apiDesc.setValue(modelDesc.getDescr()); - apiDescList.add(apiDesc); - } - } - - public static void mapPersonNames(List modelPersonNameList, - List apiPersonNameList) - throws DispositionReportFaultMessage { - apiPersonNameList.clear(); - - for (org.apache.juddi.model.PersonName personName : modelPersonNameList) { - org.uddi.api_v3.PersonName apiPersonName = new org.uddi.api_v3.PersonName(); - apiPersonName.setLang(personName.getLangCode()); - apiPersonName.setValue(personName.getName()); - apiPersonNameList.add(apiPersonName); - } - } - - public static void mapContactEmails(List modelEmailList, - List apiEmailList) - throws DispositionReportFaultMessage { - apiEmailList.clear(); - - for (org.apache.juddi.model.Email modelEmail : modelEmailList) { - org.uddi.api_v3.Email apiEmail = new org.uddi.api_v3.Email(); - apiEmail.setUseType(modelEmail.getUseType()); - apiEmail.setValue(modelEmail.getEmailAddress()); - apiEmailList.add(apiEmail); - } - } - - public static void mapContactPhones(List modelPhoneList, - List apiPhoneList) - throws DispositionReportFaultMessage { - apiPhoneList.clear(); - - for (org.apache.juddi.model.Phone modelPhone : modelPhoneList) { - org.uddi.api_v3.Phone apiPhone = new org.uddi.api_v3.Phone(); - apiPhone.setUseType(modelPhone.getUseType()); - apiPhone.setValue(modelPhone.getPhoneNumber()); - apiPhoneList.add(apiPhone); - } - } - - public static void mapContactAddresses(List modelAddressList, - List apiAddressList) - throws DispositionReportFaultMessage { - apiAddressList.clear(); - - for (org.apache.juddi.model.Address modelAddress : modelAddressList) { - org.uddi.api_v3.Address apiAddress = new org.uddi.api_v3.Address(); - apiAddress.setUseType(modelAddress.getUseType()); - apiAddress.setLang(""); - apiAddress.setSortCode(modelAddress.getSortCode()); - apiAddress.setTModelKey(modelAddress.getTmodelKey()); - - mapAddressLines(modelAddress.getAddressLines(), apiAddress.getAddressLine()); - - apiAddressList.add(apiAddress); - } - } - - public static void mapAddressLines(List modelAddressLineList, - List apiAddressLineList) - throws DispositionReportFaultMessage { - apiAddressLineList.clear(); - - for (org.apache.juddi.model.AddressLine modelAddressLine : modelAddressLineList) { - org.uddi.api_v3.AddressLine apiAddressLine = new org.uddi.api_v3.AddressLine(); - apiAddressLine.setKeyName(modelAddressLine.getKeyName()); - apiAddressLine.setKeyValue(modelAddressLine.getKeyValue()); - apiAddressLine.setValue(modelAddressLine.getLine()); - apiAddressLineList.add(apiAddressLine); - } - } - - public static void mapBusinessIdentifiers(List modelIdentifierList, - org.uddi.api_v3.IdentifierBag apiIdentifierBag, - org.uddi.api_v3.BusinessEntity apiBusinessEntity) - throws DispositionReportFaultMessage { - if (modelIdentifierList == null || modelIdentifierList.size() == 0) { - return; - } - - if (apiIdentifierBag == null) { - apiIdentifierBag = new org.uddi.api_v3.IdentifierBag(); - } - - List apiKeyedRefList = apiIdentifierBag.getKeyedReference(); - apiKeyedRefList.clear(); - - for (org.apache.juddi.model.BusinessIdentifier modelIdentifier : modelIdentifierList) { - org.uddi.api_v3.KeyedReference apiKeyedRef = new org.uddi.api_v3.KeyedReference(); - apiKeyedRef.setTModelKey(modelIdentifier.getTmodelKeyRef()); - apiKeyedRef.setKeyName(modelIdentifier.getKeyName()); - apiKeyedRef.setKeyValue(modelIdentifier.getKeyValue()); - apiKeyedRefList.add(apiKeyedRef); - } - apiBusinessEntity.setIdentifierBag(apiIdentifierBag); - } - - public static void mapBusinessServices(List modelBusinessServiceList, - List modelServiceProjectionList, - org.uddi.api_v3.BusinessServices apiBusinessServices, - org.uddi.api_v3.BusinessEntity apiBusinessEntity) - throws DispositionReportFaultMessage { - - if (apiBusinessServices == null) { - apiBusinessServices = new org.uddi.api_v3.BusinessServices(); - } - - List apiBusinessServiceList = apiBusinessServices.getBusinessService(); - apiBusinessServiceList.clear(); - - if (modelBusinessServiceList != null && modelBusinessServiceList.size() > 0) { - for (org.apache.juddi.model.BusinessService modelBusinessService : modelBusinessServiceList) { - org.uddi.api_v3.BusinessService apiBusinessService = new org.uddi.api_v3.BusinessService(); - mapBusinessService(modelBusinessService, apiBusinessService); - apiBusinessServiceList.add(apiBusinessService); - } - } - - if (modelServiceProjectionList != null && modelServiceProjectionList.size() > 0) { - for (org.apache.juddi.model.ServiceProjection modelServiceProjection : modelServiceProjectionList) { - org.uddi.api_v3.BusinessService apiBusinessService = new org.uddi.api_v3.BusinessService(); - mapBusinessService(modelServiceProjection.getBusinessService(), apiBusinessService); - apiBusinessServiceList.add(apiBusinessService); - } - } - - if (apiBusinessServiceList.size() > 0) { - apiBusinessEntity.setBusinessServices(apiBusinessServices); - } - } - - public static void mapBusinessService(org.apache.juddi.model.BusinessService modelBusinessService, - org.uddi.api_v3.BusinessService apiBusinessService) - throws DispositionReportFaultMessage { - - apiBusinessService.setBusinessKey(modelBusinessService.getBusinessEntity().getEntityKey()); - apiBusinessService.setServiceKey(modelBusinessService.getEntityKey()); - - mapServiceNames(modelBusinessService.getServiceNames(), apiBusinessService.getName()); - mapServiceDescriptions(modelBusinessService.getServiceDescrs(), apiBusinessService.getDescription()); - mapBindingTemplates(modelBusinessService.getBindingTemplates(), apiBusinessService.getBindingTemplates(), apiBusinessService); - apiBusinessService.setCategoryBag(mapCategoryBag(modelBusinessService.getCategoryBag(), apiBusinessService.getCategoryBag())); - - mapSignature(modelBusinessService.getSignatures(), apiBusinessService.getSignature()); - } - - public static void mapServiceNames(List modelNameList, - List apiNameList) - throws DispositionReportFaultMessage { - apiNameList.clear(); - - for (org.apache.juddi.model.ServiceName modelName : modelNameList) { - org.uddi.api_v3.Name apiName = new org.uddi.api_v3.Name(); - apiName.setLang(modelName.getLangCode()); - apiName.setValue(modelName.getName()); - apiNameList.add(apiName); - } - } - - public static void mapServiceDescriptions(List modelDescList, - List apiDescList) - throws DispositionReportFaultMessage { - apiDescList.clear(); - - for (org.apache.juddi.model.ServiceDescr modelDesc : modelDescList) { - org.uddi.api_v3.Description apiDesc = new org.uddi.api_v3.Description(); - apiDesc.setLang(modelDesc.getLangCode()); - apiDesc.setValue(modelDesc.getDescr()); - apiDescList.add(apiDesc); - } - } - - public static void mapBindingTemplates(List modelBindingTemplateList, - org.uddi.api_v3.BindingTemplates apiBindingTemplates, - org.uddi.api_v3.BusinessService apiBusinessService) - throws DispositionReportFaultMessage { - if (modelBindingTemplateList == null || modelBindingTemplateList.size() == 0) { - return; - } - - if (apiBindingTemplates == null) { - apiBindingTemplates = new org.uddi.api_v3.BindingTemplates(); - } - - List apiBindingTemplateList = apiBindingTemplates.getBindingTemplate(); - apiBindingTemplateList.clear(); - - for (org.apache.juddi.model.BindingTemplate modelBindingTemplate : modelBindingTemplateList) { - org.uddi.api_v3.BindingTemplate apiBindingTemplate = new org.uddi.api_v3.BindingTemplate(); - mapBindingTemplate(modelBindingTemplate, apiBindingTemplate); - apiBindingTemplateList.add(apiBindingTemplate); - } - apiBusinessService.setBindingTemplates(apiBindingTemplates); - } - - public static void mapBindingTemplate(org.apache.juddi.model.BindingTemplate modelBindingTemplate, - org.uddi.api_v3.BindingTemplate apiBindingTemplate) - throws DispositionReportFaultMessage { - - apiBindingTemplate.setServiceKey(modelBindingTemplate.getBusinessService().getEntityKey()); - apiBindingTemplate.setBindingKey(modelBindingTemplate.getEntityKey()); - org.uddi.api_v3.AccessPoint apiAccessPoint = new org.uddi.api_v3.AccessPoint(); - apiAccessPoint.setUseType(modelBindingTemplate.getAccessPointType()); - String accessPointValue = modelBindingTemplate.getAccessPointUrl(); - if (accessPointValue != null) { - try { - String baseUrl = AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL); - if (baseUrl == null) { - logger.warn("Token '" + Property.JUDDI_BASE_URL + "' not found in the juddiv3.xml, defaulting to '" - + Property.DEFAULT_BASE_URL + "'"); - baseUrl = Property.DEFAULT_BASE_URL; - } - accessPointValue = accessPointValue.replaceAll("\\$\\{" + Property.JUDDI_BASE_URL + "\\}", baseUrl); - - baseUrl = AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE); - if (baseUrl == null) { - logger.warn("Token '" + Property.JUDDI_BASE_URL_SECURE + "' not found in the juddiv3.xml, defaulting to '" - + Property.JUDDI_BASE_URL_SECURE + "'"); - baseUrl = Property.DEFAULT_BASE_URL_SECURE; - } - accessPointValue = accessPointValue.replaceAll("\\$\\{" + Property.JUDDI_BASE_URL_SECURE + "\\}", baseUrl); - } catch (ConfigurationException e) { - logger.error(e.getMessage(), e); - } - } - apiAccessPoint.setValue(accessPointValue); - apiBindingTemplate.setAccessPoint(apiAccessPoint); - if (modelBindingTemplate.getHostingRedirector() != null) { - org.uddi.api_v3.HostingRedirector apiHost = new org.uddi.api_v3.HostingRedirector(); - apiHost.setBindingKey(modelBindingTemplate.getHostingRedirector()); - apiBindingTemplate.setHostingRedirector(apiHost); - } - mapTModelInstanceDetails(modelBindingTemplate.getTmodelInstanceInfos(), apiBindingTemplate.getTModelInstanceDetails(), apiBindingTemplate); - mapBindingDescriptions(modelBindingTemplate.getBindingDescrs(), apiBindingTemplate.getDescription()); - - apiBindingTemplate.setCategoryBag(mapCategoryBag(modelBindingTemplate.getCategoryBag(), apiBindingTemplate.getCategoryBag())); - mapSignature(modelBindingTemplate.getSignatures(), apiBindingTemplate.getSignature()); - } - - public static void mapBindingDescriptions(List modelDescList, - List apiDescList) - throws DispositionReportFaultMessage { - apiDescList.clear(); - - for (org.apache.juddi.model.BindingDescr modelDesc : modelDescList) { - org.uddi.api_v3.Description apiDesc = new org.uddi.api_v3.Description(); - apiDesc.setLang(modelDesc.getLangCode()); - apiDesc.setValue(modelDesc.getDescr()); - apiDescList.add(apiDesc); - } - } - - public static org.uddi.api_v3.CategoryBag mapCategoryBag(org.apache.juddi.model.CategoryBag modelCategoryBag, - org.uddi.api_v3.CategoryBag apiCategoryBag) - throws DispositionReportFaultMessage { - - if (modelCategoryBag != null) { - if (apiCategoryBag == null) { - apiCategoryBag = new org.uddi.api_v3.CategoryBag(); - } - - for (org.apache.juddi.model.KeyedReference modelKeyedReference : modelCategoryBag.getKeyedReferences()) { - org.uddi.api_v3.KeyedReference apiKeyedReference = new org.uddi.api_v3.KeyedReference(); - apiKeyedReference.setTModelKey(modelKeyedReference.getTmodelKeyRef()); - apiKeyedReference.setKeyName(modelKeyedReference.getKeyName()); - apiKeyedReference.setKeyValue(modelKeyedReference.getKeyValue()); - apiCategoryBag.getKeyedReference().add(apiKeyedReference); - } - for (org.apache.juddi.model.KeyedReferenceGroup modelKeyedReferenceGroup : modelCategoryBag.getKeyedReferenceGroups()) { - org.uddi.api_v3.KeyedReferenceGroup apiKeyedReferenceGroup = new org.uddi.api_v3.KeyedReferenceGroup(); - - mapKeyedReferenceGroup(modelKeyedReferenceGroup, apiKeyedReferenceGroup); - - apiCategoryBag.getKeyedReferenceGroup().add(apiKeyedReferenceGroup); - } - } - return apiCategoryBag; - } - - public static void mapKeyedReferenceGroup(org.apache.juddi.model.KeyedReferenceGroup modelKeyedReferenceGroup, - org.uddi.api_v3.KeyedReferenceGroup apiKeyedReferenceGroup) - throws DispositionReportFaultMessage { - - apiKeyedReferenceGroup.setTModelKey(modelKeyedReferenceGroup.getTmodelKey()); - - for (org.apache.juddi.model.KeyedReference modelKeyedReference : modelKeyedReferenceGroup.getKeyedReferences()) { - org.uddi.api_v3.KeyedReference apiKeyedReference = new org.uddi.api_v3.KeyedReference(); - apiKeyedReference.setTModelKey(modelKeyedReference.getTmodelKeyRef()); - apiKeyedReference.setKeyName(modelKeyedReference.getKeyName()); - apiKeyedReference.setKeyValue(modelKeyedReference.getKeyValue()); - apiKeyedReferenceGroup.getKeyedReference().add(apiKeyedReference); - } - - } - - public static void mapTModelInstanceDetails(List modelTModelInstInfoList, - org.uddi.api_v3.TModelInstanceDetails apiTModelInstDetails, - org.uddi.api_v3.BindingTemplate apiBindingTemplate) - throws DispositionReportFaultMessage { - if (modelTModelInstInfoList == null || modelTModelInstInfoList.size() == 0) { - return; - } - - if (apiTModelInstDetails == null) { - apiTModelInstDetails = new org.uddi.api_v3.TModelInstanceDetails(); - } - - List apiTModelInstInfoList = apiTModelInstDetails.getTModelInstanceInfo(); - apiTModelInstInfoList.clear(); - - for (org.apache.juddi.model.TmodelInstanceInfo modelTModelInstInfo : modelTModelInstInfoList) { - org.uddi.api_v3.TModelInstanceInfo apiTModelInstInfo = new org.uddi.api_v3.TModelInstanceInfo(); - apiTModelInstInfo.setTModelKey(modelTModelInstInfo.getTmodelKey()); - mapTModelInstanceInfoDescriptions(modelTModelInstInfo.getTmodelInstanceInfoDescrs(), apiTModelInstInfo.getDescription()); - mapInstanceDetails(modelTModelInstInfo, apiTModelInstInfo.getInstanceDetails(), apiTModelInstInfo); - - apiTModelInstInfoList.add(apiTModelInstInfo); - } - apiBindingTemplate.setTModelInstanceDetails(apiTModelInstDetails); - } - - public static void mapTModelInstanceInfoDescriptions(List modelDescList, - List apiDescList) - throws DispositionReportFaultMessage { - apiDescList.clear(); - - for (org.apache.juddi.model.TmodelInstanceInfoDescr modelDesc : modelDescList) { - org.uddi.api_v3.Description apiDesc = new org.uddi.api_v3.Description(); - apiDesc.setLang(modelDesc.getLangCode()); - apiDesc.setValue(modelDesc.getDescr()); - apiDescList.add(apiDesc); - } - } - - public static void mapInstanceDetails(org.apache.juddi.model.TmodelInstanceInfo modelTModelInstInfo, - org.uddi.api_v3.InstanceDetails apiInstanceDetails, - org.uddi.api_v3.TModelInstanceInfo apiTModelInstInfo) - throws DispositionReportFaultMessage { - if (modelTModelInstInfo == null - || (modelTModelInstInfo.getInstanceParms() == null && modelTModelInstInfo.getOverviewDocs().size() == 0)) { - return; - } - - if (apiInstanceDetails == null) { - apiInstanceDetails = new org.uddi.api_v3.InstanceDetails(); - } - - //InstanceParms - apiInstanceDetails.setInstanceParms(modelTModelInstInfo.getInstanceParms()); - //Descriptions - List modelInstDetailsDescrList = modelTModelInstInfo.getInstanceDetailsDescrs(); - for (org.apache.juddi.model.InstanceDetailsDescr modelInstDetailDescr : modelInstDetailsDescrList) { - org.uddi.api_v3.Description apiDesc = new org.uddi.api_v3.Description(); - apiDesc.setLang(modelInstDetailDescr.getLangCode()); - apiDesc.setValue(modelInstDetailDescr.getDescr()); - apiInstanceDetails.getDescription().add(apiDesc); - } - //OverviewDoc - mapOverviewDocs(modelTModelInstInfo.getOverviewDocs(), apiInstanceDetails, null); - - apiTModelInstInfo.setInstanceDetails(apiInstanceDetails); - } - - public static void mapOverviewDocs(List modelOverviewDocs, - org.uddi.api_v3.InstanceDetails apiInstanceDetails, - org.uddi.api_v3.TModel apiTModel) { - for (OverviewDoc modelOverviewDoc : modelOverviewDocs) { - org.uddi.api_v3.OverviewDoc apiOverviewDoc = new org.uddi.api_v3.OverviewDoc(); - - //Descriptions - List overviewDocDescrList = modelOverviewDoc.getOverviewDocDescrs(); - for (org.apache.juddi.model.OverviewDocDescr overviewDocDescr : overviewDocDescrList) { - org.uddi.api_v3.Description apiDesc = new org.uddi.api_v3.Description(); - apiDesc.setLang(overviewDocDescr.getLangCode()); - apiDesc.setValue(overviewDocDescr.getDescr()); - apiOverviewDoc.getDescription().add(apiDesc); - } - //OverviewURL - org.uddi.api_v3.OverviewURL apiOverviewURL = new org.uddi.api_v3.OverviewURL(); - apiOverviewURL.setUseType(modelOverviewDoc.getOverviewUrlUseType()); - apiOverviewURL.setValue(modelOverviewDoc.getOverviewUrl()); - apiOverviewDoc.setOverviewURL(apiOverviewURL); - //Set the entity on the apiOverviewDoc - if (apiInstanceDetails != null) { - apiInstanceDetails.getOverviewDoc().add(apiOverviewDoc); - } else { - apiTModel.getOverviewDoc().add(apiOverviewDoc); - } - } - } - - public static void mapTModel(org.apache.juddi.model.Tmodel modelTModel, - org.uddi.api_v3.TModel apiTModel) - throws DispositionReportFaultMessage { - - apiTModel.setTModelKey(modelTModel.getEntityKey()); - org.uddi.api_v3.Name apiName = new org.uddi.api_v3.Name(); - apiName.setValue(modelTModel.getName()); - apiName.setLang(modelTModel.getLangCode()); - apiTModel.setName(apiName); - apiTModel.setDeleted(modelTModel.getDeleted()); - - mapTModelDescriptions(modelTModel.getTmodelDescrs(), apiTModel.getDescription()); - - mapTModelIdentifiers(modelTModel.getTmodelIdentifiers(), apiTModel.getIdentifierBag(), apiTModel); - apiTModel.setCategoryBag(mapCategoryBag(modelTModel.getCategoryBag(), apiTModel.getCategoryBag())); - - mapOverviewDocs(modelTModel.getOverviewDocs(), null, apiTModel); - mapSignature(modelTModel.getSignatures(), apiTModel.getSignature()); - } - - public static void mapTModelDescriptions(List modelDescList, - List apiDescList) - throws DispositionReportFaultMessage { - apiDescList.clear(); - - for (org.apache.juddi.model.TmodelDescr modelDesc : modelDescList) { - org.uddi.api_v3.Description apiDesc = new org.uddi.api_v3.Description(); - apiDesc.setLang(modelDesc.getLangCode()); - apiDesc.setValue(modelDesc.getDescr()); - apiDescList.add(apiDesc); - } - } - - public static void mapTModelIdentifiers(List modelIdentifierList, - org.uddi.api_v3.IdentifierBag apiIdentifierBag, - org.uddi.api_v3.TModel apiTModel) - throws DispositionReportFaultMessage { - if (modelIdentifierList == null || modelIdentifierList.size() == 0) { - return; - } - - if (apiIdentifierBag == null) { - apiIdentifierBag = new org.uddi.api_v3.IdentifierBag(); - } - - List apiKeyedRefList = apiIdentifierBag.getKeyedReference(); - apiKeyedRefList.clear(); - - for (org.apache.juddi.model.TmodelIdentifier modelIdentifier : modelIdentifierList) { - org.uddi.api_v3.KeyedReference apiKeyedRef = new org.uddi.api_v3.KeyedReference(); - apiKeyedRef.setTModelKey(modelIdentifier.getTmodelKeyRef()); - apiKeyedRef.setKeyName(modelIdentifier.getKeyName()); - apiKeyedRef.setKeyValue(modelIdentifier.getKeyValue()); - apiKeyedRefList.add(apiKeyedRef); - } - apiTModel.setIdentifierBag(apiIdentifierBag); - } - - public static void mapBusinessInfo(org.apache.juddi.model.BusinessEntity modelBusinessEntity, - org.uddi.api_v3.BusinessInfo apiBusinessInfo) - throws DispositionReportFaultMessage { - - apiBusinessInfo.setBusinessKey(modelBusinessEntity.getEntityKey()); - - mapBusinessNames(modelBusinessEntity.getBusinessNames(), apiBusinessInfo.getName()); - mapBusinessDescriptions(modelBusinessEntity.getBusinessDescrs(), apiBusinessInfo.getDescription()); - - mapServiceInfos(modelBusinessEntity.getBusinessServices(), apiBusinessInfo.getServiceInfos(), apiBusinessInfo); - - } - - public static void mapServiceInfos(List modelBusinessServiceList, - org.uddi.api_v3.ServiceInfos apiServiceInfos, - org.uddi.api_v3.BusinessInfo apiBusinessInfo) - throws DispositionReportFaultMessage { - if (modelBusinessServiceList.size() == 0) { - return; - } - if (apiServiceInfos == null) { - apiServiceInfos = new org.uddi.api_v3.ServiceInfos(); - } - - List apiServiceInfoList = apiServiceInfos.getServiceInfo(); - apiServiceInfoList.clear(); - - for (org.apache.juddi.model.BusinessService modelBusinessService : modelBusinessServiceList) { - org.uddi.api_v3.ServiceInfo apiServiceInfo = new org.uddi.api_v3.ServiceInfo(); - - mapServiceInfo(modelBusinessService, apiServiceInfo); - - apiServiceInfos.getServiceInfo().add(apiServiceInfo); - } - apiBusinessInfo.setServiceInfos(apiServiceInfos); - } - - public static void mapServiceInfo(org.apache.juddi.model.BusinessService modelBusinessService, - org.uddi.api_v3.ServiceInfo apiServiceInfo) - throws DispositionReportFaultMessage { - - apiServiceInfo.setBusinessKey(modelBusinessService.getBusinessEntity().getEntityKey()); - apiServiceInfo.setServiceKey(modelBusinessService.getEntityKey()); - - mapServiceNames(modelBusinessService.getServiceNames(), apiServiceInfo.getName()); - } - - public static void mapTModelInfo(org.apache.juddi.model.Tmodel modelTModel, - org.uddi.api_v3.TModelInfo apiTModelInfo) - throws DispositionReportFaultMessage { - - apiTModelInfo.setTModelKey(modelTModel.getEntityKey()); - org.uddi.api_v3.Name apiName = new org.uddi.api_v3.Name(); - apiName.setValue(modelTModel.getName()); - apiName.setLang(modelTModel.getLangCode()); - apiTModelInfo.setName(apiName); - - mapTModelDescriptions(modelTModel.getTmodelDescrs(), apiTModelInfo.getDescription()); - - } - - public static void mapAuthToken(org.apache.juddi.model.AuthToken modelAuthToken, - org.uddi.api_v3.AuthToken apiAuthToken) - throws DispositionReportFaultMessage { - apiAuthToken.setAuthInfo(modelAuthToken.getAuthToken()); - - } - - public static void mapPublisherAssertion(org.apache.juddi.model.PublisherAssertion modelPublisherAssertion, - org.uddi.api_v3.PublisherAssertion apiPublisherAssertion) - throws DispositionReportFaultMessage { - - apiPublisherAssertion.setFromKey(modelPublisherAssertion.getId().getFromKey()); - apiPublisherAssertion.setToKey(modelPublisherAssertion.getId().getToKey()); - - org.uddi.api_v3.KeyedReference keyedRef = new org.uddi.api_v3.KeyedReference(); - keyedRef.setTModelKey(modelPublisherAssertion.getTmodelKey()); - keyedRef.setKeyName(modelPublisherAssertion.getKeyName()); - keyedRef.setKeyValue(modelPublisherAssertion.getKeyValue()); - - if (modelPublisherAssertion.getSignatures()!=null && - !modelPublisherAssertion.getSignatures().isEmpty()) - { - mapSignature(modelPublisherAssertion.getSignatures(), apiPublisherAssertion.getSignature()); - } - apiPublisherAssertion.setKeyedReference(keyedRef); - - } - - public static void mapAssertionStatusItem(org.apache.juddi.model.PublisherAssertion modelPublisherAssertion, - org.uddi.api_v3.AssertionStatusItem apiAssertionStatusItem, - List businessKeys) - throws DispositionReportFaultMessage { - - apiAssertionStatusItem.setFromKey(modelPublisherAssertion.getId().getFromKey()); - apiAssertionStatusItem.setToKey(modelPublisherAssertion.getId().getToKey()); - - org.uddi.api_v3.KeyedReference keyedRef = new org.uddi.api_v3.KeyedReference(); - keyedRef.setTModelKey(modelPublisherAssertion.getTmodelKey()); - keyedRef.setKeyName(modelPublisherAssertion.getKeyName()); - keyedRef.setKeyValue(modelPublisherAssertion.getKeyValue()); - - apiAssertionStatusItem.setKeyedReference(keyedRef); - - if ("true".equalsIgnoreCase(modelPublisherAssertion.getFromCheck()) - && "true".equalsIgnoreCase(modelPublisherAssertion.getToCheck())) { - apiAssertionStatusItem.setCompletionStatus(CompletionStatus.STATUS_COMPLETE); - } else if (!"true".equalsIgnoreCase(modelPublisherAssertion.getFromCheck()) - && "true".equalsIgnoreCase(modelPublisherAssertion.getToCheck())) { - apiAssertionStatusItem.setCompletionStatus(CompletionStatus.STATUS_FROM_KEY_INCOMPLETE); - } else if ("true".equalsIgnoreCase(modelPublisherAssertion.getFromCheck()) - && !"true".equalsIgnoreCase(modelPublisherAssertion.getToCheck())) { - apiAssertionStatusItem.setCompletionStatus(CompletionStatus.STATUS_TO_KEY_INCOMPLETE); - } else if (!"true".equalsIgnoreCase(modelPublisherAssertion.getFromCheck()) - && !"true".equalsIgnoreCase(modelPublisherAssertion.getToCheck())) { - apiAssertionStatusItem.setCompletionStatus(CompletionStatus.STATUS_BOTH_INCOMPLETE); - } - - org.uddi.api_v3.KeysOwned keysOwned = new org.uddi.api_v3.KeysOwned(); - - //converting resultList to simple List - List businessKeyList = new ArrayList(); - for (Object businessKey : businessKeys) { - businessKeyList.add(String.valueOf(businessKey)); - } - Collections.sort(businessKeyList); - if (Collections.binarySearch(businessKeyList, modelPublisherAssertion.getBusinessEntityByFromKey().getEntityKey()) >= 0) { - keysOwned.setFromKey(modelPublisherAssertion.getBusinessEntityByFromKey().getEntityKey()); - } - - if (Collections.binarySearch(businessKeyList, modelPublisherAssertion.getBusinessEntityByToKey().getEntityKey()) >= 0) { - keysOwned.setToKey(modelPublisherAssertion.getBusinessEntityByToKey().getEntityKey()); - } - if (keysOwned.getFromKey() == null && keysOwned.getToKey() == null) { - throw new FatalErrorException(new ErrorMessage("errors.invalidKey.KeysOwned")); - } - apiAssertionStatusItem.setKeysOwned(keysOwned); - } - - public static void mapRelatedBusinessInfo(org.apache.juddi.model.PublisherAssertion modelPublisherAssertion, - org.apache.juddi.model.BusinessEntity modelRelatedBusiness, - org.uddi.api_v3.Direction direction, - org.uddi.api_v3.RelatedBusinessInfo apiRelatedBusinessInfo) - throws DispositionReportFaultMessage { - - apiRelatedBusinessInfo.setBusinessKey(modelRelatedBusiness.getEntityKey()); - - mapBusinessNames(modelRelatedBusiness.getBusinessNames(), apiRelatedBusinessInfo.getName()); - mapBusinessDescriptions(modelRelatedBusiness.getBusinessDescrs(), apiRelatedBusinessInfo.getDescription()); - - org.uddi.api_v3.SharedRelationships sharedRelationships = new org.uddi.api_v3.SharedRelationships(); - sharedRelationships.setDirection(direction); - - org.uddi.api_v3.KeyedReference keyedRef = new org.uddi.api_v3.KeyedReference(); - keyedRef.setTModelKey(modelPublisherAssertion.getTmodelKey()); - keyedRef.setKeyName(modelPublisherAssertion.getKeyName()); - keyedRef.setKeyValue(modelPublisherAssertion.getKeyValue()); - sharedRelationships.getKeyedReference().add(keyedRef); - - apiRelatedBusinessInfo.getSharedRelationships().add(sharedRelationships); - } - - public static void mapOperationalInfo(UddiEntity modelUddiEntity, - OperationalInfo apiOperationalInfo) - throws DispositionReportFaultMessage { - - apiOperationalInfo.setCreated(TypeConvertor.convertDateToXMLGregorianCalendar(modelUddiEntity.getCreated())); - apiOperationalInfo.setModified(TypeConvertor.convertDateToXMLGregorianCalendar(modelUddiEntity.getModified())); - apiOperationalInfo.setModifiedIncludingChildren(TypeConvertor.convertDateToXMLGregorianCalendar(modelUddiEntity.getModifiedIncludingChildren())); - apiOperationalInfo.setNodeID(modelUddiEntity.getNodeId()); - apiOperationalInfo.setAuthorizedName(modelUddiEntity.getAuthorizedName()); - apiOperationalInfo.setEntityKey(modelUddiEntity.getEntityKey()); - } - - public static void mapSubscription(org.apache.juddi.model.Subscription modelSubscription, - org.uddi.sub_v3.Subscription apiSubscription) - throws DispositionReportFaultMessage { - - apiSubscription.setSubscriptionKey(modelSubscription.getSubscriptionKey()); - apiSubscription.setBrief(modelSubscription.isBrief()); - apiSubscription.setExpiresAfter(TypeConvertor.convertDateToXMLGregorianCalendar(modelSubscription.getExpiresAfter())); - apiSubscription.setBindingKey(modelSubscription.getBindingKey()); - apiSubscription.setMaxEntities(modelSubscription.getMaxEntities()); - apiSubscription.setNotificationInterval(TypeConvertor.convertStringToDuration(modelSubscription.getNotificationInterval())); - - try { - SubscriptionFilter existingFilter = (SubscriptionFilter) JAXBMarshaller.unmarshallFromString(modelSubscription.getSubscriptionFilter(), JAXBMarshaller.PACKAGE_SUBSCRIPTION); - apiSubscription.setSubscriptionFilter(existingFilter); - } catch (JAXBException e) { - logger.error("JAXB Exception while marshalling subscription filter", e); - throw new FatalErrorException(new ErrorMessage("errors.Unspecified")); - } - } - - public static void mapClientSubscriptionInfo(org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo, - org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo, EntityManager em) - throws DispositionReportFaultMessage { - - apiClientSubscriptionInfo.setSubscriptionKey(modelClientSubscriptionInfo.getSubscriptionKey()); - GregorianCalendar gcal = new GregorianCalendar(); - gcal.setTimeInMillis(modelClientSubscriptionInfo.getLastNotified().getTime()); - try { - apiClientSubscriptionInfo.setLastModified(DatatypeFactory.newInstance().newXMLGregorianCalendar(gcal)); - } catch (DatatypeConfigurationException ex) { - logger.warn("unable to create DatatypeFactory", ex); - } - - if (modelClientSubscriptionInfo.getFromClerk() != null) { - org.apache.juddi.api_v3.Clerk apiFromClerk = new org.apache.juddi.api_v3.Clerk(); - mapClerk(modelClientSubscriptionInfo.getFromClerk(), apiFromClerk,em); - apiClientSubscriptionInfo.setFromClerk(apiFromClerk); - } - if (modelClientSubscriptionInfo.getToClerk() != null) { - org.apache.juddi.api_v3.Clerk apiToClerk = new org.apache.juddi.api_v3.Clerk(); - mapClerk(modelClientSubscriptionInfo.getToClerk(), apiToClerk,em); - apiClientSubscriptionInfo.setToClerk(apiToClerk); - } - } - - public static void mapClerk(org.apache.juddi.model.Clerk modelClerk, - org.apache.juddi.api_v3.Clerk apiClerk,EntityManager em) - throws DispositionReportFaultMessage { - - apiClerk.setName(modelClerk.getClerkName()); - apiClerk.setPassword(modelClerk.getCred()); - apiClerk.setPublisher(modelClerk.getPublisherId()); - if (modelClerk.getNode() != null) { - org.apache.juddi.api_v3.Node apiNode = new org.apache.juddi.api_v3.Node(); - mapNode( - em.find(org.apache.juddi.model.Node.class, modelClerk.getNode()) - , apiNode); - apiClerk.setNode(apiNode); - } - } - - public static void mapNode(org.apache.juddi.model.Node modelNode, - org.apache.juddi.api_v3.Node apiNode) - throws DispositionReportFaultMessage { - - apiNode.setCustodyTransferUrl(modelNode.getCustodyTransferUrl()); - apiNode.setFactoryInitial(modelNode.getFactoryInitial()); - apiNode.setFactoryNamingProvider(modelNode.getFactoryNamingProvider()); - apiNode.setFactoryURLPkgs(modelNode.getFactoryURLPkgs()); - apiNode.setInquiryUrl(modelNode.getInquiryUrl()); - apiNode.setJuddiApiUrl(modelNode.getJuddiApiUrl()); - apiNode.setName(modelNode.getName()); - apiNode.setClientName(modelNode.getClientName()); - apiNode.setProxyTransport(modelNode.getProxyTransport()); - apiNode.setPublishUrl(modelNode.getPublishUrl()); - apiNode.setSecurityUrl(modelNode.getSecurityUrl()); - apiNode.setSubscriptionUrl(modelNode.getSubscriptionUrl()); - apiNode.setSubscriptionListenerUrl(modelNode.getSubscriptionListenerUrl()); - apiNode.setReplicationUrl(modelNode.getReplicationUrl()); - } - - private static Object convertDataToTransformContent(String type, byte[] xformBytes) throws RuntimeException { - Object transformObject; - if (type.equals(String.class.getSimpleName())) { - try { - transformObject = new String(xformBytes, "UTF-8"); - } catch (Exception e) { - throw new RuntimeException("Error decoding string due to: " + e.getMessage(), e); - } - } else if (type.equals(byte[].class.getSimpleName())) { - transformObject = xformBytes; - } else if (type.equals(Element.class.getCanonicalName())) { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - try { - dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); - dbf.setNamespaceAware(true); - dbf.setXIncludeAware(true); - - DocumentBuilder db = dbf.newDocumentBuilder(); - Document doc = db.parse(new ByteArrayInputStream(xformBytes)); - transformObject = doc.getDocumentElement(); - } catch (Exception e) { - throw new RuntimeException("Failed to parse element due to: " + e.getMessage(), e); - } - } else { - throw new RuntimeException("Unrecognized type: " + type); - } - return transformObject; - } - - public static void mapReplicationConfiguration(ReplicationConfiguration find, org.uddi.repl_v3.ReplicationConfiguration item) throws DispositionReportFaultMessage { - item.setMaximumTimeToGetChanges(find.getMaximumTimeToGetChanges()); - item.setMaximumTimeToSyncRegistry(find.getMaximumTimeToSyncRegistry()); - item.setSerialNumber(find.getSerialNumber()); - - List sigs = new ArrayList(); - mapSignature(find.getSignatures(), sigs); - item.getSignature().addAll(sigs); - mapOperator(find.getOperator(), item.getOperator()); - - List modelContactList = new ArrayList(); - org.uddi.api_v3.Contacts cs = new Contacts(); - - mapContacts(modelContactList, cs, new BusinessEntity()); - item.setRegistryContact(new org.uddi.repl_v3.ReplicationConfiguration.RegistryContact()); - if (!cs.getContact().isEmpty()) { - - item.getRegistryContact().setContact(cs.getContact().get(0)); - } - else - { - item.getRegistryContact().setContact(new Contact()); - item.getRegistryContact().getContact().getPersonName().add(new PersonName("unknown", null)); - } - item.setTimeOfConfigurationUpdate(find.getTimeOfConfigurationUpdate()); - CommunicationGraph xcom = new CommunicationGraph(); - - mapCommunicationGraph(find, xcom); - item.setCommunicationGraph(xcom); - //(List modelContactList, - //org.uddi.api_v3.Contacts apiContacts, - //org.uddi.api_v3.BusinessEntity apiBusinessEntity) - } - - private static void mapOperator(List model, List api) throws DispositionReportFaultMessage { - for (int i = 0; i < model.size(); i++) { - Operator op = new Operator(); - op.setOperatorNodeID(model.get(i).getOperatorNodeID()); - op.setSoapReplicationURL(model.get(i).getSoapReplicationURL()); - switch (model.get(i).getOperatorStatus()) { - case NEW: - op.setOperatorStatus(OperatorStatusType.NEW); - break; - case NORMAL: - op.setOperatorStatus(OperatorStatusType.NORMAL); - break; - case RESIGNED: - op.setOperatorStatus(OperatorStatusType.RESIGNED); - break; - } - Contacts c = new Contacts(); - mapContacts(model.get(i).getContact(), c, new BusinessEntity()); - op.getContact().addAll(c.getContact()); - - if (model.get(i).getKeyInfo() != null) { - for (int x = 0; x < model.get(i).getKeyInfo().size(); x++) { - KeyInfoType apiKeyInfo = new KeyInfoType(); - KeyInfo modelKeyInfo = model.get(i).getKeyInfo().get(x); - apiKeyInfo.setId(modelKeyInfo.getXmlID()); - List modelKeyDataValueList = modelKeyInfo.getKeyDataValue(); - List apiX509KeyInfoList = apiKeyInfo.getContent(); - mapModelKeyDataValue(modelKeyDataValueList, apiX509KeyInfoList); - op.getKeyInfo().add(apiKeyInfo); - } - } - api.add(op); - } - - } - - private static void mapCommunicationGraph(org.apache.juddi.model.ReplicationConfiguration model, - CommunicationGraph api) { - - mapEdge(model.getEdge(), api.getEdge()); - mapControlMessages(model.getControlMessage(), api.getControlledMessage()); - mapEdgeNodes(model.getNode(), api.getNode()); - - } - - private static void mapEdge(List model, List api) { - Iterator it = model.iterator(); - while (it.hasNext()) { - Edge modelEdge = it.next(); - - CommunicationGraph.Edge apiEdge = new CommunicationGraph.Edge(); - apiEdge.setMessageReceiver(modelEdge.getMessageReceiver()); - apiEdge.setMessageSender(modelEdge.getMessageSender()); - - Iterator it2 = modelEdge.getMessages().iterator(); - while (it2.hasNext()) { - apiEdge.getMessage().add(it2.next().getMessage()); - } - Iterator it3 = modelEdge.getMessageReceiverAlternate().iterator(); - while (it3.hasNext()) { - apiEdge.getMessageReceiverAlternate().add(it3.next().getReceiverAlternate()); - } - - api.add(apiEdge); - - } - } - - private static void mapControlMessages(List model, List api) { - Iterator it = model.iterator(); - while (it.hasNext()) { - api.add(it.next().getMessage()); - } - } - - private static void mapEdgeNodes(List model, List api) { - Iterator it = model.iterator(); - while (it.hasNext()) { - api.add(it.next().getNodeName()); - } - } - - public static ChangeRecord mapChangeRecord(org.apache.juddi.model.ChangeRecord cr) { - if (cr == null) { - return null; - } - ChangeRecord ret = null; - - StringReader sr = null; - try { - sr = new StringReader(new String(cr.getContents(), "UTF8")); - } catch (UnsupportedEncodingException ex) { - Logger.getLogger(MappingModelToApi.class.getName()).log(Level.SEVERE, null, ex); - } - ret = (ChangeRecord) XmlUtils.unmarshal(sr, ChangeRecord.class); - //secret sauce here, if this is -1, that means that the record originated at this node and needs to be populated with the databases record id - if (cr.getOriginatingUSN() == null || cr.getOriginatingUSN() == -1L) { - ret.setChangeID(new ChangeRecordIDType(cr.getNodeID(), cr.getId())); - } else { - ret.setChangeID(new ChangeRecordIDType(cr.getNodeID(), cr.getOriginatingUSN())); - } - return ret; - - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.mapping; + +import java.math.BigInteger; +import java.util.GregorianCalendar; +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import org.w3._2000._09.xmldsig_.X509IssuerSerialType; +import java.io.ByteArrayInputStream; +import java.io.StringReader; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.persistence.EntityManager; +import javax.xml.bind.JAXB; +import javax.xml.bind.JAXBElement; + +import javax.xml.bind.JAXBException; +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.Property; +import org.apache.juddi.jaxb.JAXBMarshaller; +import org.apache.juddi.model.CanonicalizationMethod; +import org.apache.juddi.model.ControlMessage; +import org.apache.juddi.model.Edge; +import org.apache.juddi.model.EdgeReceiverAlternate; +import org.apache.juddi.model.KeyInfo; +import org.apache.juddi.model.OverviewDoc; +import org.apache.juddi.model.Reference; +import org.apache.juddi.model.SignatureTransform; +import org.apache.juddi.model.SignatureValue; +import org.apache.juddi.model.SignedInfo; +import org.apache.juddi.model.UddiEntity; +import org.apache.juddi.model.KeyDataValue; +import org.apache.juddi.model.Node; +import org.apache.juddi.model.ReplicationConfiguration; +import org.apache.juddi.model.ReplicationConfigurationNode; +import org.apache.juddi.model.Signature; +import org.apache.juddi.model.SignatureTransformDataValue; +import org.apache.juddi.subscription.TypeConvertor; +import org.apache.juddi.v3.client.cryptor.XmlUtils; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.FatalErrorException; +import org.uddi.api_v3.BusinessEntity; +import org.uddi.api_v3.CompletionStatus; +import org.uddi.api_v3.Contact; +import org.uddi.api_v3.Contacts; +import org.uddi.api_v3.OperationalInfo; +import org.uddi.api_v3.PersonName; +import org.uddi.repl_v3.ChangeRecord; +import org.uddi.repl_v3.ChangeRecordIDType; +import org.uddi.repl_v3.CommunicationGraph; +import org.uddi.repl_v3.Operator; +import org.uddi.repl_v3.OperatorStatusType; +import org.uddi.sub_v3.SubscriptionFilter; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.w3._2000._09.xmldsig_.CanonicalizationMethodType; +import org.w3._2000._09.xmldsig_.DSAKeyValueType; +import org.w3._2000._09.xmldsig_.DigestMethodType; +import org.w3._2000._09.xmldsig_.KeyInfoType; +import org.w3._2000._09.xmldsig_.KeyValueType; +import org.w3._2000._09.xmldsig_.PGPDataType; +import org.w3._2000._09.xmldsig_.RSAKeyValueType; +import org.w3._2000._09.xmldsig_.ReferenceType; +import org.w3._2000._09.xmldsig_.RetrievalMethodType; +import org.w3._2000._09.xmldsig_.SPKIDataType; +import org.w3._2000._09.xmldsig_.SignatureMethodType; +import org.w3._2000._09.xmldsig_.SignatureType; +import org.w3._2000._09.xmldsig_.SignatureValueType; +import org.w3._2000._09.xmldsig_.SignedInfoType; +import org.w3._2000._09.xmldsig_.TransformType; +import org.w3._2000._09.xmldsig_.TransformsType; +import org.w3._2000._09.xmldsig_.X509DataType; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * @author Jeff Faath + * @author Kurt T Stam + */ +public class MappingModelToApi { + + private static Log logger = LogFactory.getLog(MappingModelToApi.class); + + public static void mapPublisher(org.apache.juddi.model.Publisher modelPublisher, + org.apache.juddi.api_v3.Publisher apiPublisher) + throws DispositionReportFaultMessage { + + apiPublisher.setAuthorizedName(modelPublisher.getAuthorizedName()); + apiPublisher.setPublisherName(modelPublisher.getPublisherName()); + apiPublisher.setEmailAddress(modelPublisher.getEmailAddress()); + apiPublisher.setIsAdmin(modelPublisher.getIsAdmin()); + apiPublisher.setIsEnabled(modelPublisher.getIsEnabled()); + apiPublisher.setMaxBindingsPerService(modelPublisher.getMaxBindingsPerService()); + apiPublisher.setMaxBusinesses(modelPublisher.getMaxBusinesses()); + apiPublisher.setMaxServicePerBusiness(modelPublisher.getMaxServicesPerBusiness()); + apiPublisher.setMaxTModels(modelPublisher.getMaxTmodels()); + mapSignature(modelPublisher.getSignatures(), apiPublisher.getSignature()); + } + + public static void mapBusinessEntity(org.apache.juddi.model.BusinessEntity modelBusinessEntity, + org.uddi.api_v3.BusinessEntity apiBusinessEntity) + throws DispositionReportFaultMessage { + + apiBusinessEntity.setBusinessKey(modelBusinessEntity.getEntityKey()); + + mapBusinessNames(modelBusinessEntity.getBusinessNames(), apiBusinessEntity.getName()); + mapBusinessDescriptions(modelBusinessEntity.getBusinessDescrs(), apiBusinessEntity.getDescription()); + + mapDiscoveryUrls(modelBusinessEntity.getDiscoveryUrls(), apiBusinessEntity.getDiscoveryURLs(), apiBusinessEntity); + mapContacts(modelBusinessEntity.getContacts(), apiBusinessEntity.getContacts(), apiBusinessEntity); + mapBusinessIdentifiers(modelBusinessEntity.getBusinessIdentifiers(), apiBusinessEntity.getIdentifierBag(), apiBusinessEntity); + apiBusinessEntity.setCategoryBag(mapCategoryBag(modelBusinessEntity.getCategoryBag(), apiBusinessEntity.getCategoryBag())); + + mapBusinessServices(modelBusinessEntity.getBusinessServices(), modelBusinessEntity.getServiceProjections(), apiBusinessEntity.getBusinessServices(), apiBusinessEntity); + + mapSignature(modelBusinessEntity.getSignatures(), apiBusinessEntity.getSignature()); + } + + public static void mapSignature(List signatureList, + List apiSignatureList) + throws DispositionReportFaultMessage { + apiSignatureList.clear(); + for (org.apache.juddi.model.Signature modelSig : signatureList) { + SignatureType apiSignature = new SignatureType(); + apiSignature.setId(modelSig.getXmlID()); + + SignedInfo modelSignedInfo = modelSig.getSignedInfo(); + SignedInfoType apiSignedInfoType = new SignedInfoType(); + apiSignature.setSignedInfo(apiSignedInfoType); + // Canonicalization method + CanonicalizationMethod modelCanonMethod = modelSignedInfo.getCanonicalizationMethod(); + CanonicalizationMethodType apiCanonMethod = new CanonicalizationMethodType(); + apiCanonMethod.setAlgorithm(modelCanonMethod.getAlgorithm()); + apiSignedInfoType.setCanonicalizationMethod(apiCanonMethod); + + // Signature Method + String sigAlg = modelSignedInfo.getSignatureMethod().getAlgorithm(); + SignatureMethodType apiSigMethod = new SignatureMethodType(); + apiSigMethod.setAlgorithm(sigAlg); + apiSignedInfoType.setSignatureMethod(apiSigMethod); + + // References + List modelReferenceList = modelSignedInfo.getReference(); + List apiReferenceList = apiSignedInfoType.getReference(); + for (Reference modelRef : modelReferenceList) { + ReferenceType apiRef = new ReferenceType(); + String refUri = modelRef.getUri(); + if (refUri == null) { + refUri = ""; + } + apiRef.setURI(refUri); + + List modelSigTransformList = modelRef.getTransforms(); + TransformsType apiTransformsType = apiRef.getTransforms(); + if (apiTransformsType == null) { + apiTransformsType = new TransformsType(); + apiRef.setTransforms(apiTransformsType); + } + List apiTransformList = apiTransformsType.getTransform(); + for (SignatureTransform modelSigTransform : modelSigTransformList) { + String modelTransformAlgStr = modelSigTransform.getTransform(); + TransformType apiTransform = new TransformType(); + apiTransform.setAlgorithm(modelTransformAlgStr); + + List sigTransformSDVList = modelSigTransform.getSignatureTransformDataValue(); + for (SignatureTransformDataValue sigTransformSDV : sigTransformSDVList) { + String type = sigTransformSDV.getContentType(); + byte[] xformBytes = sigTransformSDV.getContentBytes(); + Object transformObject = convertDataToTransformContent(type, xformBytes); + apiTransform.getContent().add(transformObject); + } + + apiTransformList.add(apiTransform); + } + + String digestMethodStr = modelRef.getDigestMethod(); + byte[] digestValBytes = modelRef.getDigestValue(); + + DigestMethodType apiDigestMethod = new DigestMethodType(); + apiDigestMethod.setAlgorithm(digestMethodStr); + apiRef.setDigestMethod(apiDigestMethod); + apiRef.setDigestValue(digestValBytes); + + apiReferenceList.add(apiRef); + } + + // Signature Value + SignatureValueType apiSignatureValue = new SignatureValueType(); + SignatureValue modelSigValue = modelSig.getSignatureValue(); + apiSignatureValue.setId(modelSigValue.getXmlID()); + apiSignatureValue.setValue(modelSigValue.getValue()); + + apiSignature.setSignatureValue(apiSignatureValue); + + KeyInfoType apiKeyInfo = new KeyInfoType(); + KeyInfo modelKeyInfo = modelSig.getKeyInfo(); + apiKeyInfo.setId(modelKeyInfo.getXmlID()); + + List modelKeyDataValueList = modelKeyInfo.getKeyDataValue(); + List apiX509KeyInfoList = apiKeyInfo.getContent(); + mapModelKeyDataValue(modelKeyDataValueList, apiX509KeyInfoList); + apiSignature.setKeyInfo(apiKeyInfo); + apiSignatureList.add(apiSignature); + } + } + + private static void mapModelKeyDataValue(List modelKeyDataValueList, List parentKeyDataList) { + for (KeyDataValue modelKeyDataValue : modelKeyDataValueList) { + String tagName = modelKeyDataValue.getKeyDataName(); + String dataType = modelKeyDataValue.getKeyDataType(); + byte[] contentBytes = modelKeyDataValue.getKeyDataValueBytes(); + String contentStr = modelKeyDataValue.getKeyDataValueString(); + Object contents = contentBytes != null ? contentBytes : contentStr; + + if (contents == null) { + List childKeyDataList = new ArrayList(); + if (dataType.equals(X509DataType.class.getSimpleName())) { + X509DataType x509DataType = new X509DataType(); + mapModelKeyDataValue(modelKeyDataValue.getKeyDataValueList(), childKeyDataList); + x509DataType.getX509IssuerSerialOrX509SKIOrX509SubjectName().addAll(childKeyDataList); + JAXBElement dataJAXB = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", tagName), X509DataType.class, x509DataType); + parentKeyDataList.add(dataJAXB); + } else if (dataType.equals(RetrievalMethodType.class.getSimpleName())) { + RetrievalMethodType retrievalMethodType = new RetrievalMethodType(); + TransformsType transformsType = new TransformsType(); + for (KeyDataValue retrievalMethodKDV : modelKeyDataValue.getKeyDataValueList()) { + if (retrievalMethodKDV.getKeyDataName().equals("Transform")) { + TransformType tType = new TransformType(); + tType.setAlgorithm(retrievalMethodKDV.getKeyDataValueString()); + + for (KeyDataValue transformContentKDV : retrievalMethodKDV.getKeyDataValueList()) { + String type = transformContentKDV.getKeyDataType(); + byte[] xformBytes = transformContentKDV.getKeyDataValueBytes(); + Object transformObject = convertDataToTransformContent(type, xformBytes); + tType.getContent().add(transformObject); + } + + transformsType.getTransform().add(tType); + } else if (retrievalMethodKDV.getKeyDataName().equals("Type")) { + retrievalMethodType.setType(retrievalMethodKDV.getKeyDataValueString()); + } else if (retrievalMethodKDV.getKeyDataName().equals("URI")) { + retrievalMethodType.setURI(retrievalMethodKDV.getKeyDataValueString()); + } else { + throw new RuntimeException("Unrecognized key data type: " + retrievalMethodKDV.getKeyDataType()); + } + } + if (transformsType.getTransform() != null && !transformsType.getTransform().isEmpty()) { + retrievalMethodType.setTransforms(transformsType); + } + JAXBElement dataJAXB = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", tagName), RetrievalMethodType.class, retrievalMethodType); + parentKeyDataList.add(dataJAXB); + } else if (dataType.equals(PGPDataType.class.getSimpleName())) { + PGPDataType pgpDataType = new PGPDataType(); + + for (KeyDataValue pgpDataKDV : modelKeyDataValue.getKeyDataValueList()) { + String pgpDataTagName = pgpDataKDV.getKeyDataName(); + Object pgpDataContents = pgpDataKDV.getKeyDataValueBytes() != null ? pgpDataKDV.getKeyDataValueBytes() : pgpDataKDV.getKeyDataValueString(); + Class pgpDataClazz = pgpDataContents.getClass(); + JAXBElement jaxb = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", pgpDataTagName), pgpDataClazz, pgpDataContents); + pgpDataType.getContent().add(jaxb); + } + + JAXBElement dataJAXB = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", tagName), PGPDataType.class, pgpDataType); + parentKeyDataList.add(dataJAXB); + } else if (dataType.equals(SPKIDataType.class.getSimpleName())) { + SPKIDataType spkiDataType = new SPKIDataType(); + + for (KeyDataValue spkiDataKDV : modelKeyDataValue.getKeyDataValueList()) { + String spkiDataTagName = spkiDataKDV.getKeyDataName(); + Object spkiDataContents = spkiDataKDV.getKeyDataValueBytes() != null ? spkiDataKDV.getKeyDataValueBytes() : spkiDataKDV.getKeyDataValueString(); + Class spkiDataClazz = spkiDataContents.getClass(); + JAXBElement jaxb = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", spkiDataTagName), spkiDataClazz, spkiDataContents); + spkiDataType.getSPKISexpAndAny().add(jaxb); + } + + JAXBElement dataJAXB = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", tagName), SPKIDataType.class, spkiDataType); + parentKeyDataList.add(dataJAXB); + } else if (dataType.equals(KeyValueType.class.getSimpleName())) { + KeyValueType keyValueType = new KeyValueType(); + for (KeyDataValue keyValueDataKDV : modelKeyDataValue.getKeyDataValueList()) { + for (KeyDataValue keyValueDataChildKDV : keyValueDataKDV.getKeyDataValueList()) { + String keyDataDataType = keyValueDataChildKDV.getKeyDataType(); + if (keyDataDataType.equals("DSAKeyValueType")) { + DSAKeyValueType dsaKeyValueType = new DSAKeyValueType(); + for (KeyDataValue dsaKDV : keyValueDataChildKDV.getKeyDataValueList()) { + if ("G".equals(dsaKDV.getKeyDataName())) { + dsaKeyValueType.setG(dsaKDV.getKeyDataValueBytes()); + } else if ("P".equals(dsaKDV.getKeyDataName())) { + dsaKeyValueType.setP(dsaKDV.getKeyDataValueBytes()); + } else if ("Q".equals(dsaKDV.getKeyDataName())) { + dsaKeyValueType.setQ(dsaKDV.getKeyDataValueBytes()); + } else if ("Y".equals(dsaKDV.getKeyDataName())) { + dsaKeyValueType.setY(dsaKDV.getKeyDataValueBytes()); + } else if ("J".equals(dsaKDV.getKeyDataName())) { + dsaKeyValueType.setJ(dsaKDV.getKeyDataValueBytes()); + } else if ("Seed".equals(dsaKDV.getKeyDataName())) { + dsaKeyValueType.setSeed(dsaKDV.getKeyDataValueBytes()); + } else if ("PgenCounter".equals(dsaKDV.getKeyDataName())) { + dsaKeyValueType.setPgenCounter(dsaKDV.getKeyDataValueBytes()); + } else { + throw new RuntimeException("Unrecognized dsa type: " + dsaKDV.getKeyDataName()); + } + } + JAXBElement jaxb = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", keyValueDataChildKDV.getKeyDataName()), DSAKeyValueType.class, dsaKeyValueType); + keyValueType.getContent().add(jaxb); + } else if (keyDataDataType.equals("RSAKeyValueType")) { + RSAKeyValueType rsaKeyValueType = new RSAKeyValueType(); + for (KeyDataValue rsaKDV : keyValueDataChildKDV.getKeyDataValueList()) { + if ("Exponent".equals(rsaKDV.getKeyDataName())) { + rsaKeyValueType.setExponent(rsaKDV.getKeyDataValueBytes()); + } else if ("Modulus".equals(rsaKDV.getKeyDataName())) { + rsaKeyValueType.setModulus(rsaKDV.getKeyDataValueBytes()); + } else { + throw new RuntimeException("Unrecognized dsa type: " + rsaKDV.getKeyDataName()); + } + } + JAXBElement jaxb = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", keyValueDataChildKDV.getKeyDataName()), RSAKeyValueType.class, rsaKeyValueType); + keyValueType.getContent().add(jaxb); + } else { + throw new RuntimeException("Unrecognized element: " + keyDataDataType); + } + } + } + JAXBElement dataJAXB = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", tagName), KeyValueType.class, keyValueType); + parentKeyDataList.add(dataJAXB); + } else { + throw new RuntimeException("Unrecognized type: " + dataType); + } + } else { + if (dataType != null && dataType.equals(X509IssuerSerialType.class.getSimpleName())) { + X509IssuerSerialType x509IssuerSerialType = new X509IssuerSerialType(); + x509IssuerSerialType.setX509IssuerName(contentStr); + x509IssuerSerialType.setX509SerialNumber(new BigInteger(contentBytes)); + JAXBElement dataJAXB = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", tagName), X509IssuerSerialType.class, x509IssuerSerialType); + parentKeyDataList.add(dataJAXB); + } else { + JAXBElement dataJAXB = new JAXBElement(new QName("http://www.w3.org/2000/09/xmldsig#", tagName), contents.getClass(), contents); + parentKeyDataList.add(dataJAXB); + } + } + } + } + + public static void mapBusinessNames(List modelNameList, + List apiNameList) + throws DispositionReportFaultMessage { + apiNameList.clear(); + + for (org.apache.juddi.model.BusinessName modelName : modelNameList) { + org.uddi.api_v3.Name apiName = new org.uddi.api_v3.Name(); + apiName.setLang(modelName.getLangCode()); + apiName.setValue(modelName.getName()); + apiNameList.add(apiName); + } + } + + public static void mapBusinessDescriptions(List modelDescList, + List apiDescList) + throws DispositionReportFaultMessage { + apiDescList.clear(); + + for (org.apache.juddi.model.BusinessDescr modelDesc : modelDescList) { + org.uddi.api_v3.Description apiDesc = new org.uddi.api_v3.Description(); + apiDesc.setLang(modelDesc.getLangCode()); + apiDesc.setValue(modelDesc.getDescr()); + apiDescList.add(apiDesc); + } + } + + public static void mapDiscoveryUrls(List modelDiscUrlList, + org.uddi.api_v3.DiscoveryURLs apiDiscUrls, + org.uddi.api_v3.BusinessEntity apiBusinessEntity) + throws DispositionReportFaultMessage { + if (modelDiscUrlList == null || modelDiscUrlList.size() == 0) { + return; + } + + if (apiDiscUrls == null) { + apiDiscUrls = new org.uddi.api_v3.DiscoveryURLs(); + } + + List apiDiscUrlList = apiDiscUrls.getDiscoveryURL(); + apiDiscUrlList.clear(); + + for (org.apache.juddi.model.DiscoveryUrl modelDiscUrl : modelDiscUrlList) { + org.uddi.api_v3.DiscoveryURL apiDiscUrl = new org.uddi.api_v3.DiscoveryURL(); + apiDiscUrl.setUseType(modelDiscUrl.getUseType()); + String discoveryURL = modelDiscUrl.getUrl(); + try { + String baseUrl = AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL); + if (baseUrl == null) { + logger.warn("Token '" + Property.JUDDI_BASE_URL + "' not found in the juddiv3.xml, defaulting to '" + + Property.DEFAULT_BASE_URL + "'"); + baseUrl = Property.DEFAULT_BASE_URL; + } + discoveryURL = discoveryURL.replaceAll("\\$\\{" + Property.JUDDI_BASE_URL + "\\}", baseUrl); + + baseUrl = AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE); + if (baseUrl == null) { + logger.warn("Token '" + Property.JUDDI_BASE_URL_SECURE + "' not found in the juddiv3.xml, defaulting to '" + + Property.JUDDI_BASE_URL_SECURE + "'"); + baseUrl = Property.DEFAULT_BASE_URL_SECURE; + } + discoveryURL = discoveryURL.replaceAll("\\$\\{" + Property.JUDDI_BASE_URL_SECURE + "\\}", baseUrl); + + } catch (ConfigurationException e) { + logger.error(e.getMessage(), e); + } + apiDiscUrl.setValue(discoveryURL); + apiDiscUrlList.add(apiDiscUrl); + } + apiBusinessEntity.setDiscoveryURLs(apiDiscUrls); + } + + public static void mapContact(org.apache.juddi.model.Contact modelContact, + org.uddi.api_v3.Contact apiContact) throws DispositionReportFaultMessage { + if (apiContact == null) { + apiContact = new org.uddi.api_v3.Contact(); + } + apiContact.setUseType(modelContact.getUseType()); + + mapPersonNames(modelContact.getPersonNames(), apiContact.getPersonName()); + mapContactDescriptions(modelContact.getContactDescrs(), apiContact.getDescription()); + mapContactEmails(modelContact.getEmails(), apiContact.getEmail()); + mapContactPhones(modelContact.getPhones(), apiContact.getPhone()); + mapContactAddresses(modelContact.getAddresses(), apiContact.getAddress()); + + } + + public static void mapContacts(List modelContactList, + org.uddi.api_v3.Contacts apiContacts, + org.uddi.api_v3.BusinessEntity apiBusinessEntity) + throws DispositionReportFaultMessage { + if (modelContactList == null || modelContactList.size() == 0) { + return; + } + + if (apiContacts == null) { + apiContacts = new org.uddi.api_v3.Contacts(); + } + + List apiContactList = apiContacts.getContact(); + apiContactList.clear(); + + for (org.apache.juddi.model.Contact modelContact : modelContactList) { + org.uddi.api_v3.Contact apiContact = new org.uddi.api_v3.Contact(); + + mapContact(modelContact,apiContact); + + apiContactList.add(apiContact); + } + apiBusinessEntity.setContacts(apiContacts); + } + + public static void mapContactDescriptions(List modelDescList, + List apiDescList) + throws DispositionReportFaultMessage { + apiDescList.clear(); + + for (org.apache.juddi.model.ContactDescr modelDesc : modelDescList) { + org.uddi.api_v3.Description apiDesc = new org.uddi.api_v3.Description(); + apiDesc.setLang(modelDesc.getLangCode()); + apiDesc.setValue(modelDesc.getDescr()); + apiDescList.add(apiDesc); + } + } + + public static void mapPersonNames(List modelPersonNameList, + List apiPersonNameList) + throws DispositionReportFaultMessage { + apiPersonNameList.clear(); + + for (org.apache.juddi.model.PersonName personName : modelPersonNameList) { + org.uddi.api_v3.PersonName apiPersonName = new org.uddi.api_v3.PersonName(); + apiPersonName.setLang(personName.getLangCode()); + apiPersonName.setValue(personName.getName()); + apiPersonNameList.add(apiPersonName); + } + } + + public static void mapContactEmails(List modelEmailList, + List apiEmailList) + throws DispositionReportFaultMessage { + apiEmailList.clear(); + + for (org.apache.juddi.model.Email modelEmail : modelEmailList) { + org.uddi.api_v3.Email apiEmail = new org.uddi.api_v3.Email(); + apiEmail.setUseType(modelEmail.getUseType()); + apiEmail.setValue(modelEmail.getEmailAddress()); + apiEmailList.add(apiEmail); + } + } + + public static void mapContactPhones(List modelPhoneList, + List apiPhoneList) + throws DispositionReportFaultMessage { + apiPhoneList.clear(); + + for (org.apache.juddi.model.Phone modelPhone : modelPhoneList) { + org.uddi.api_v3.Phone apiPhone = new org.uddi.api_v3.Phone(); + apiPhone.setUseType(modelPhone.getUseType()); + apiPhone.setValue(modelPhone.getPhoneNumber()); + apiPhoneList.add(apiPhone); + } + } + + public static void mapContactAddresses(List modelAddressList, + List apiAddressList) + throws DispositionReportFaultMessage { + apiAddressList.clear(); + + for (org.apache.juddi.model.Address modelAddress : modelAddressList) { + org.uddi.api_v3.Address apiAddress = new org.uddi.api_v3.Address(); + apiAddress.setUseType(modelAddress.getUseType()); + apiAddress.setLang(""); + apiAddress.setSortCode(modelAddress.getSortCode()); + apiAddress.setTModelKey(modelAddress.getTmodelKey()); + + mapAddressLines(modelAddress.getAddressLines(), apiAddress.getAddressLine()); + + apiAddressList.add(apiAddress); + } + } + + public static void mapAddressLines(List modelAddressLineList, + List apiAddressLineList) + throws DispositionReportFaultMessage { + apiAddressLineList.clear(); + + for (org.apache.juddi.model.AddressLine modelAddressLine : modelAddressLineList) { + org.uddi.api_v3.AddressLine apiAddressLine = new org.uddi.api_v3.AddressLine(); + apiAddressLine.setKeyName(modelAddressLine.getKeyName()); + apiAddressLine.setKeyValue(modelAddressLine.getKeyValue()); + apiAddressLine.setValue(modelAddressLine.getLine()); + apiAddressLineList.add(apiAddressLine); + } + } + + public static void mapBusinessIdentifiers(List modelIdentifierList, + org.uddi.api_v3.IdentifierBag apiIdentifierBag, + org.uddi.api_v3.BusinessEntity apiBusinessEntity) + throws DispositionReportFaultMessage { + if (modelIdentifierList == null || modelIdentifierList.size() == 0) { + return; + } + + if (apiIdentifierBag == null) { + apiIdentifierBag = new org.uddi.api_v3.IdentifierBag(); + } + + List apiKeyedRefList = apiIdentifierBag.getKeyedReference(); + apiKeyedRefList.clear(); + + for (org.apache.juddi.model.BusinessIdentifier modelIdentifier : modelIdentifierList) { + org.uddi.api_v3.KeyedReference apiKeyedRef = new org.uddi.api_v3.KeyedReference(); + apiKeyedRef.setTModelKey(modelIdentifier.getTmodelKeyRef()); + apiKeyedRef.setKeyName(modelIdentifier.getKeyName()); + apiKeyedRef.setKeyValue(modelIdentifier.getKeyValue()); + apiKeyedRefList.add(apiKeyedRef); + } + apiBusinessEntity.setIdentifierBag(apiIdentifierBag); + } + + public static void mapBusinessServices(List modelBusinessServiceList, + List modelServiceProjectionList, + org.uddi.api_v3.BusinessServices apiBusinessServices, + org.uddi.api_v3.BusinessEntity apiBusinessEntity) + throws DispositionReportFaultMessage { + + if (apiBusinessServices == null) { + apiBusinessServices = new org.uddi.api_v3.BusinessServices(); + } + + List apiBusinessServiceList = apiBusinessServices.getBusinessService(); + apiBusinessServiceList.clear(); + + if (modelBusinessServiceList != null && modelBusinessServiceList.size() > 0) { + for (org.apache.juddi.model.BusinessService modelBusinessService : modelBusinessServiceList) { + org.uddi.api_v3.BusinessService apiBusinessService = new org.uddi.api_v3.BusinessService(); + mapBusinessService(modelBusinessService, apiBusinessService); + apiBusinessServiceList.add(apiBusinessService); + } + } + + if (modelServiceProjectionList != null && modelServiceProjectionList.size() > 0) { + for (org.apache.juddi.model.ServiceProjection modelServiceProjection : modelServiceProjectionList) { + org.uddi.api_v3.BusinessService apiBusinessService = new org.uddi.api_v3.BusinessService(); + mapBusinessService(modelServiceProjection.getBusinessService(), apiBusinessService); + apiBusinessServiceList.add(apiBusinessService); + } + } + + if (apiBusinessServiceList.size() > 0) { + apiBusinessEntity.setBusinessServices(apiBusinessServices); + } + } + + public static void mapBusinessService(org.apache.juddi.model.BusinessService modelBusinessService, + org.uddi.api_v3.BusinessService apiBusinessService) + throws DispositionReportFaultMessage { + + apiBusinessService.setBusinessKey(modelBusinessService.getBusinessEntity().getEntityKey()); + apiBusinessService.setServiceKey(modelBusinessService.getEntityKey()); + + mapServiceNames(modelBusinessService.getServiceNames(), apiBusinessService.getName()); + mapServiceDescriptions(modelBusinessService.getServiceDescrs(), apiBusinessService.getDescription()); + mapBindingTemplates(modelBusinessService.getBindingTemplates(), apiBusinessService.getBindingTemplates(), apiBusinessService); + apiBusinessService.setCategoryBag(mapCategoryBag(modelBusinessService.getCategoryBag(), apiBusinessService.getCategoryBag())); + + mapSignature(modelBusinessService.getSignatures(), apiBusinessService.getSignature()); + } + + public static void mapServiceNames(List modelNameList, + List apiNameList) + throws DispositionReportFaultMessage { + apiNameList.clear(); + + for (org.apache.juddi.model.ServiceName modelName : modelNameList) { + org.uddi.api_v3.Name apiName = new org.uddi.api_v3.Name(); + apiName.setLang(modelName.getLangCode()); + apiName.setValue(modelName.getName()); + apiNameList.add(apiName); + } + } + + public static void mapServiceDescriptions(List modelDescList, + List apiDescList) + throws DispositionReportFaultMessage { + apiDescList.clear(); + + for (org.apache.juddi.model.ServiceDescr modelDesc : modelDescList) { + org.uddi.api_v3.Description apiDesc = new org.uddi.api_v3.Description(); + apiDesc.setLang(modelDesc.getLangCode()); + apiDesc.setValue(modelDesc.getDescr()); + apiDescList.add(apiDesc); + } + } + + public static void mapBindingTemplates(List modelBindingTemplateList, + org.uddi.api_v3.BindingTemplates apiBindingTemplates, + org.uddi.api_v3.BusinessService apiBusinessService) + throws DispositionReportFaultMessage { + if (modelBindingTemplateList == null || modelBindingTemplateList.size() == 0) { + return; + } + + if (apiBindingTemplates == null) { + apiBindingTemplates = new org.uddi.api_v3.BindingTemplates(); + } + + List apiBindingTemplateList = apiBindingTemplates.getBindingTemplate(); + apiBindingTemplateList.clear(); + + for (org.apache.juddi.model.BindingTemplate modelBindingTemplate : modelBindingTemplateList) { + org.uddi.api_v3.BindingTemplate apiBindingTemplate = new org.uddi.api_v3.BindingTemplate(); + mapBindingTemplate(modelBindingTemplate, apiBindingTemplate); + apiBindingTemplateList.add(apiBindingTemplate); + } + apiBusinessService.setBindingTemplates(apiBindingTemplates); + } + + public static void mapBindingTemplate(org.apache.juddi.model.BindingTemplate modelBindingTemplate, + org.uddi.api_v3.BindingTemplate apiBindingTemplate) + throws DispositionReportFaultMessage { + + apiBindingTemplate.setServiceKey(modelBindingTemplate.getBusinessService().getEntityKey()); + apiBindingTemplate.setBindingKey(modelBindingTemplate.getEntityKey()); + org.uddi.api_v3.AccessPoint apiAccessPoint = new org.uddi.api_v3.AccessPoint(); + apiAccessPoint.setUseType(modelBindingTemplate.getAccessPointType()); + String accessPointValue = modelBindingTemplate.getAccessPointUrl(); + if (accessPointValue != null) { + try { + String baseUrl = AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL); + if (baseUrl == null) { + logger.warn("Token '" + Property.JUDDI_BASE_URL + "' not found in the juddiv3.xml, defaulting to '" + + Property.DEFAULT_BASE_URL + "'"); + baseUrl = Property.DEFAULT_BASE_URL; + } + accessPointValue = accessPointValue.replaceAll("\\$\\{" + Property.JUDDI_BASE_URL + "\\}", baseUrl); + + baseUrl = AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE); + if (baseUrl == null) { + logger.warn("Token '" + Property.JUDDI_BASE_URL_SECURE + "' not found in the juddiv3.xml, defaulting to '" + + Property.JUDDI_BASE_URL_SECURE + "'"); + baseUrl = Property.DEFAULT_BASE_URL_SECURE; + } + accessPointValue = accessPointValue.replaceAll("\\$\\{" + Property.JUDDI_BASE_URL_SECURE + "\\}", baseUrl); + } catch (ConfigurationException e) { + logger.error(e.getMessage(), e); + } + } + apiAccessPoint.setValue(accessPointValue); + apiBindingTemplate.setAccessPoint(apiAccessPoint); + if (modelBindingTemplate.getHostingRedirector() != null) { + org.uddi.api_v3.HostingRedirector apiHost = new org.uddi.api_v3.HostingRedirector(); + apiHost.setBindingKey(modelBindingTemplate.getHostingRedirector()); + apiBindingTemplate.setHostingRedirector(apiHost); + } + mapTModelInstanceDetails(modelBindingTemplate.getTmodelInstanceInfos(), apiBindingTemplate.getTModelInstanceDetails(), apiBindingTemplate); + mapBindingDescriptions(modelBindingTemplate.getBindingDescrs(), apiBindingTemplate.getDescription()); + + apiBindingTemplate.setCategoryBag(mapCategoryBag(modelBindingTemplate.getCategoryBag(), apiBindingTemplate.getCategoryBag())); + mapSignature(modelBindingTemplate.getSignatures(), apiBindingTemplate.getSignature()); + } + + public static void mapBindingDescriptions(List modelDescList, + List apiDescList) + throws DispositionReportFaultMessage { + apiDescList.clear(); + + for (org.apache.juddi.model.BindingDescr modelDesc : modelDescList) { + org.uddi.api_v3.Description apiDesc = new org.uddi.api_v3.Description(); + apiDesc.setLang(modelDesc.getLangCode()); + apiDesc.setValue(modelDesc.getDescr()); + apiDescList.add(apiDesc); + } + } + + public static org.uddi.api_v3.CategoryBag mapCategoryBag(org.apache.juddi.model.CategoryBag modelCategoryBag, + org.uddi.api_v3.CategoryBag apiCategoryBag) + throws DispositionReportFaultMessage { + + if (modelCategoryBag != null) { + if (apiCategoryBag == null) { + apiCategoryBag = new org.uddi.api_v3.CategoryBag(); + } + + for (org.apache.juddi.model.KeyedReference modelKeyedReference : modelCategoryBag.getKeyedReferences()) { + org.uddi.api_v3.KeyedReference apiKeyedReference = new org.uddi.api_v3.KeyedReference(); + apiKeyedReference.setTModelKey(modelKeyedReference.getTmodelKeyRef()); + apiKeyedReference.setKeyName(modelKeyedReference.getKeyName()); + apiKeyedReference.setKeyValue(modelKeyedReference.getKeyValue()); + apiCategoryBag.getKeyedReference().add(apiKeyedReference); + } + for (org.apache.juddi.model.KeyedReferenceGroup modelKeyedReferenceGroup : modelCategoryBag.getKeyedReferenceGroups()) { + org.uddi.api_v3.KeyedReferenceGroup apiKeyedReferenceGroup = new org.uddi.api_v3.KeyedReferenceGroup(); + + mapKeyedReferenceGroup(modelKeyedReferenceGroup, apiKeyedReferenceGroup); + + apiCategoryBag.getKeyedReferenceGroup().add(apiKeyedReferenceGroup); + } + } + return apiCategoryBag; + } + + public static void mapKeyedReferenceGroup(org.apache.juddi.model.KeyedReferenceGroup modelKeyedReferenceGroup, + org.uddi.api_v3.KeyedReferenceGroup apiKeyedReferenceGroup) + throws DispositionReportFaultMessage { + + apiKeyedReferenceGroup.setTModelKey(modelKeyedReferenceGroup.getTmodelKey()); + + for (org.apache.juddi.model.KeyedReference modelKeyedReference : modelKeyedReferenceGroup.getKeyedReferences()) { + org.uddi.api_v3.KeyedReference apiKeyedReference = new org.uddi.api_v3.KeyedReference(); + apiKeyedReference.setTModelKey(modelKeyedReference.getTmodelKeyRef()); + apiKeyedReference.setKeyName(modelKeyedReference.getKeyName()); + apiKeyedReference.setKeyValue(modelKeyedReference.getKeyValue()); + apiKeyedReferenceGroup.getKeyedReference().add(apiKeyedReference); + } + + } + + public static void mapTModelInstanceDetails(List modelTModelInstInfoList, + org.uddi.api_v3.TModelInstanceDetails apiTModelInstDetails, + org.uddi.api_v3.BindingTemplate apiBindingTemplate) + throws DispositionReportFaultMessage { + if (modelTModelInstInfoList == null || modelTModelInstInfoList.size() == 0) { + return; + } + + if (apiTModelInstDetails == null) { + apiTModelInstDetails = new org.uddi.api_v3.TModelInstanceDetails(); + } + + List apiTModelInstInfoList = apiTModelInstDetails.getTModelInstanceInfo(); + apiTModelInstInfoList.clear(); + + for (org.apache.juddi.model.TmodelInstanceInfo modelTModelInstInfo : modelTModelInstInfoList) { + org.uddi.api_v3.TModelInstanceInfo apiTModelInstInfo = new org.uddi.api_v3.TModelInstanceInfo(); + apiTModelInstInfo.setTModelKey(modelTModelInstInfo.getTmodelKey()); + mapTModelInstanceInfoDescriptions(modelTModelInstInfo.getTmodelInstanceInfoDescrs(), apiTModelInstInfo.getDescription()); + mapInstanceDetails(modelTModelInstInfo, apiTModelInstInfo.getInstanceDetails(), apiTModelInstInfo); + + apiTModelInstInfoList.add(apiTModelInstInfo); + } + apiBindingTemplate.setTModelInstanceDetails(apiTModelInstDetails); + } + + public static void mapTModelInstanceInfoDescriptions(List modelDescList, + List apiDescList) + throws DispositionReportFaultMessage { + apiDescList.clear(); + + for (org.apache.juddi.model.TmodelInstanceInfoDescr modelDesc : modelDescList) { + org.uddi.api_v3.Description apiDesc = new org.uddi.api_v3.Description(); + apiDesc.setLang(modelDesc.getLangCode()); + apiDesc.setValue(modelDesc.getDescr()); + apiDescList.add(apiDesc); + } + } + + public static void mapInstanceDetails(org.apache.juddi.model.TmodelInstanceInfo modelTModelInstInfo, + org.uddi.api_v3.InstanceDetails apiInstanceDetails, + org.uddi.api_v3.TModelInstanceInfo apiTModelInstInfo) + throws DispositionReportFaultMessage { + if (modelTModelInstInfo == null + || (modelTModelInstInfo.getInstanceParms() == null && modelTModelInstInfo.getOverviewDocs().size() == 0)) { + return; + } + + if (apiInstanceDetails == null) { + apiInstanceDetails = new org.uddi.api_v3.InstanceDetails(); + } + + //InstanceParms + apiInstanceDetails.setInstanceParms(modelTModelInstInfo.getInstanceParms()); + //Descriptions + List modelInstDetailsDescrList = modelTModelInstInfo.getInstanceDetailsDescrs(); + for (org.apache.juddi.model.InstanceDetailsDescr modelInstDetailDescr : modelInstDetailsDescrList) { + org.uddi.api_v3.Description apiDesc = new org.uddi.api_v3.Description(); + apiDesc.setLang(modelInstDetailDescr.getLangCode()); + apiDesc.setValue(modelInstDetailDescr.getDescr()); + apiInstanceDetails.getDescription().add(apiDesc); + } + //OverviewDoc + mapOverviewDocs(modelTModelInstInfo.getOverviewDocs(), apiInstanceDetails, null); + + apiTModelInstInfo.setInstanceDetails(apiInstanceDetails); + } + + public static void mapOverviewDocs(List modelOverviewDocs, + org.uddi.api_v3.InstanceDetails apiInstanceDetails, + org.uddi.api_v3.TModel apiTModel) { + for (OverviewDoc modelOverviewDoc : modelOverviewDocs) { + org.uddi.api_v3.OverviewDoc apiOverviewDoc = new org.uddi.api_v3.OverviewDoc(); + + //Descriptions + List overviewDocDescrList = modelOverviewDoc.getOverviewDocDescrs(); + for (org.apache.juddi.model.OverviewDocDescr overviewDocDescr : overviewDocDescrList) { + org.uddi.api_v3.Description apiDesc = new org.uddi.api_v3.Description(); + apiDesc.setLang(overviewDocDescr.getLangCode()); + apiDesc.setValue(overviewDocDescr.getDescr()); + apiOverviewDoc.getDescription().add(apiDesc); + } + //OverviewURL + org.uddi.api_v3.OverviewURL apiOverviewURL = new org.uddi.api_v3.OverviewURL(); + apiOverviewURL.setUseType(modelOverviewDoc.getOverviewUrlUseType()); + apiOverviewURL.setValue(modelOverviewDoc.getOverviewUrl()); + apiOverviewDoc.setOverviewURL(apiOverviewURL); + //Set the entity on the apiOverviewDoc + if (apiInstanceDetails != null) { + apiInstanceDetails.getOverviewDoc().add(apiOverviewDoc); + } else { + apiTModel.getOverviewDoc().add(apiOverviewDoc); + } + } + } + + public static void mapTModel(org.apache.juddi.model.Tmodel modelTModel, + org.uddi.api_v3.TModel apiTModel) + throws DispositionReportFaultMessage { + + apiTModel.setTModelKey(modelTModel.getEntityKey()); + org.uddi.api_v3.Name apiName = new org.uddi.api_v3.Name(); + apiName.setValue(modelTModel.getName()); + apiName.setLang(modelTModel.getLangCode()); + apiTModel.setName(apiName); + apiTModel.setDeleted(modelTModel.getDeleted()); + + mapTModelDescriptions(modelTModel.getTmodelDescrs(), apiTModel.getDescription()); + + mapTModelIdentifiers(modelTModel.getTmodelIdentifiers(), apiTModel.getIdentifierBag(), apiTModel); + apiTModel.setCategoryBag(mapCategoryBag(modelTModel.getCategoryBag(), apiTModel.getCategoryBag())); + + mapOverviewDocs(modelTModel.getOverviewDocs(), null, apiTModel); + mapSignature(modelTModel.getSignatures(), apiTModel.getSignature()); + } + + public static void mapTModelDescriptions(List modelDescList, + List apiDescList) + throws DispositionReportFaultMessage { + apiDescList.clear(); + + for (org.apache.juddi.model.TmodelDescr modelDesc : modelDescList) { + org.uddi.api_v3.Description apiDesc = new org.uddi.api_v3.Description(); + apiDesc.setLang(modelDesc.getLangCode()); + apiDesc.setValue(modelDesc.getDescr()); + apiDescList.add(apiDesc); + } + } + + public static void mapTModelIdentifiers(List modelIdentifierList, + org.uddi.api_v3.IdentifierBag apiIdentifierBag, + org.uddi.api_v3.TModel apiTModel) + throws DispositionReportFaultMessage { + if (modelIdentifierList == null || modelIdentifierList.size() == 0) { + return; + } + + if (apiIdentifierBag == null) { + apiIdentifierBag = new org.uddi.api_v3.IdentifierBag(); + } + + List apiKeyedRefList = apiIdentifierBag.getKeyedReference(); + apiKeyedRefList.clear(); + + for (org.apache.juddi.model.TmodelIdentifier modelIdentifier : modelIdentifierList) { + org.uddi.api_v3.KeyedReference apiKeyedRef = new org.uddi.api_v3.KeyedReference(); + apiKeyedRef.setTModelKey(modelIdentifier.getTmodelKeyRef()); + apiKeyedRef.setKeyName(modelIdentifier.getKeyName()); + apiKeyedRef.setKeyValue(modelIdentifier.getKeyValue()); + apiKeyedRefList.add(apiKeyedRef); + } + apiTModel.setIdentifierBag(apiIdentifierBag); + } + + public static void mapBusinessInfo(org.apache.juddi.model.BusinessEntity modelBusinessEntity, + org.uddi.api_v3.BusinessInfo apiBusinessInfo) + throws DispositionReportFaultMessage { + + apiBusinessInfo.setBusinessKey(modelBusinessEntity.getEntityKey()); + + mapBusinessNames(modelBusinessEntity.getBusinessNames(), apiBusinessInfo.getName()); + mapBusinessDescriptions(modelBusinessEntity.getBusinessDescrs(), apiBusinessInfo.getDescription()); + + mapServiceInfos(modelBusinessEntity.getBusinessServices(), apiBusinessInfo.getServiceInfos(), apiBusinessInfo); + + } + + public static void mapServiceInfos(List modelBusinessServiceList, + org.uddi.api_v3.ServiceInfos apiServiceInfos, + org.uddi.api_v3.BusinessInfo apiBusinessInfo) + throws DispositionReportFaultMessage { + if (modelBusinessServiceList.size() == 0) { + return; + } + if (apiServiceInfos == null) { + apiServiceInfos = new org.uddi.api_v3.ServiceInfos(); + } + + List apiServiceInfoList = apiServiceInfos.getServiceInfo(); + apiServiceInfoList.clear(); + + for (org.apache.juddi.model.BusinessService modelBusinessService : modelBusinessServiceList) { + org.uddi.api_v3.ServiceInfo apiServiceInfo = new org.uddi.api_v3.ServiceInfo(); + + mapServiceInfo(modelBusinessService, apiServiceInfo); + + apiServiceInfos.getServiceInfo().add(apiServiceInfo); + } + apiBusinessInfo.setServiceInfos(apiServiceInfos); + } + + public static void mapServiceInfo(org.apache.juddi.model.BusinessService modelBusinessService, + org.uddi.api_v3.ServiceInfo apiServiceInfo) + throws DispositionReportFaultMessage { + + apiServiceInfo.setBusinessKey(modelBusinessService.getBusinessEntity().getEntityKey()); + apiServiceInfo.setServiceKey(modelBusinessService.getEntityKey()); + + mapServiceNames(modelBusinessService.getServiceNames(), apiServiceInfo.getName()); + } + + public static void mapTModelInfo(org.apache.juddi.model.Tmodel modelTModel, + org.uddi.api_v3.TModelInfo apiTModelInfo) + throws DispositionReportFaultMessage { + + apiTModelInfo.setTModelKey(modelTModel.getEntityKey()); + org.uddi.api_v3.Name apiName = new org.uddi.api_v3.Name(); + apiName.setValue(modelTModel.getName()); + apiName.setLang(modelTModel.getLangCode()); + apiTModelInfo.setName(apiName); + + mapTModelDescriptions(modelTModel.getTmodelDescrs(), apiTModelInfo.getDescription()); + + } + + public static void mapAuthToken(org.apache.juddi.model.AuthToken modelAuthToken, + org.uddi.api_v3.AuthToken apiAuthToken) + throws DispositionReportFaultMessage { + apiAuthToken.setAuthInfo(modelAuthToken.getAuthToken()); + + } + + public static void mapPublisherAssertion(org.apache.juddi.model.PublisherAssertion modelPublisherAssertion, + org.uddi.api_v3.PublisherAssertion apiPublisherAssertion) + throws DispositionReportFaultMessage { + + apiPublisherAssertion.setFromKey(modelPublisherAssertion.getId().getFromKey()); + apiPublisherAssertion.setToKey(modelPublisherAssertion.getId().getToKey()); + + org.uddi.api_v3.KeyedReference keyedRef = new org.uddi.api_v3.KeyedReference(); + keyedRef.setTModelKey(modelPublisherAssertion.getTmodelKey()); + keyedRef.setKeyName(modelPublisherAssertion.getKeyName()); + keyedRef.setKeyValue(modelPublisherAssertion.getKeyValue()); + + if (modelPublisherAssertion.getSignatures()!=null && + !modelPublisherAssertion.getSignatures().isEmpty()) + { + mapSignature(modelPublisherAssertion.getSignatures(), apiPublisherAssertion.getSignature()); + } + apiPublisherAssertion.setKeyedReference(keyedRef); + + } + + public static void mapAssertionStatusItem(org.apache.juddi.model.PublisherAssertion modelPublisherAssertion, + org.uddi.api_v3.AssertionStatusItem apiAssertionStatusItem, + List businessKeys) + throws DispositionReportFaultMessage { + + apiAssertionStatusItem.setFromKey(modelPublisherAssertion.getId().getFromKey()); + apiAssertionStatusItem.setToKey(modelPublisherAssertion.getId().getToKey()); + + org.uddi.api_v3.KeyedReference keyedRef = new org.uddi.api_v3.KeyedReference(); + keyedRef.setTModelKey(modelPublisherAssertion.getTmodelKey()); + keyedRef.setKeyName(modelPublisherAssertion.getKeyName()); + keyedRef.setKeyValue(modelPublisherAssertion.getKeyValue()); + + apiAssertionStatusItem.setKeyedReference(keyedRef); + + if ("true".equalsIgnoreCase(modelPublisherAssertion.getFromCheck()) + && "true".equalsIgnoreCase(modelPublisherAssertion.getToCheck())) { + apiAssertionStatusItem.setCompletionStatus(CompletionStatus.STATUS_COMPLETE); + } else if (!"true".equalsIgnoreCase(modelPublisherAssertion.getFromCheck()) + && "true".equalsIgnoreCase(modelPublisherAssertion.getToCheck())) { + apiAssertionStatusItem.setCompletionStatus(CompletionStatus.STATUS_FROM_KEY_INCOMPLETE); + } else if ("true".equalsIgnoreCase(modelPublisherAssertion.getFromCheck()) + && !"true".equalsIgnoreCase(modelPublisherAssertion.getToCheck())) { + apiAssertionStatusItem.setCompletionStatus(CompletionStatus.STATUS_TO_KEY_INCOMPLETE); + } else if (!"true".equalsIgnoreCase(modelPublisherAssertion.getFromCheck()) + && !"true".equalsIgnoreCase(modelPublisherAssertion.getToCheck())) { + apiAssertionStatusItem.setCompletionStatus(CompletionStatus.STATUS_BOTH_INCOMPLETE); + } + + org.uddi.api_v3.KeysOwned keysOwned = new org.uddi.api_v3.KeysOwned(); + + //converting resultList to simple List + List businessKeyList = new ArrayList(); + for (Object businessKey : businessKeys) { + businessKeyList.add(String.valueOf(businessKey)); + } + Collections.sort(businessKeyList); + if (Collections.binarySearch(businessKeyList, modelPublisherAssertion.getBusinessEntityByFromKey().getEntityKey()) >= 0) { + keysOwned.setFromKey(modelPublisherAssertion.getBusinessEntityByFromKey().getEntityKey()); + } + + if (Collections.binarySearch(businessKeyList, modelPublisherAssertion.getBusinessEntityByToKey().getEntityKey()) >= 0) { + keysOwned.setToKey(modelPublisherAssertion.getBusinessEntityByToKey().getEntityKey()); + } + if (keysOwned.getFromKey() == null && keysOwned.getToKey() == null) { + throw new FatalErrorException(new ErrorMessage("errors.invalidKey.KeysOwned")); + } + apiAssertionStatusItem.setKeysOwned(keysOwned); + } + + public static void mapRelatedBusinessInfo(org.apache.juddi.model.PublisherAssertion modelPublisherAssertion, + org.apache.juddi.model.BusinessEntity modelRelatedBusiness, + org.uddi.api_v3.Direction direction, + org.uddi.api_v3.RelatedBusinessInfo apiRelatedBusinessInfo) + throws DispositionReportFaultMessage { + + apiRelatedBusinessInfo.setBusinessKey(modelRelatedBusiness.getEntityKey()); + + mapBusinessNames(modelRelatedBusiness.getBusinessNames(), apiRelatedBusinessInfo.getName()); + mapBusinessDescriptions(modelRelatedBusiness.getBusinessDescrs(), apiRelatedBusinessInfo.getDescription()); + + org.uddi.api_v3.SharedRelationships sharedRelationships = new org.uddi.api_v3.SharedRelationships(); + sharedRelationships.setDirection(direction); + + org.uddi.api_v3.KeyedReference keyedRef = new org.uddi.api_v3.KeyedReference(); + keyedRef.setTModelKey(modelPublisherAssertion.getTmodelKey()); + keyedRef.setKeyName(modelPublisherAssertion.getKeyName()); + keyedRef.setKeyValue(modelPublisherAssertion.getKeyValue()); + sharedRelationships.getKeyedReference().add(keyedRef); + + apiRelatedBusinessInfo.getSharedRelationships().add(sharedRelationships); + } + + public static void mapOperationalInfo(UddiEntity modelUddiEntity, + OperationalInfo apiOperationalInfo) + throws DispositionReportFaultMessage { + + apiOperationalInfo.setCreated(TypeConvertor.convertDateToXMLGregorianCalendar(modelUddiEntity.getCreated())); + apiOperationalInfo.setModified(TypeConvertor.convertDateToXMLGregorianCalendar(modelUddiEntity.getModified())); + apiOperationalInfo.setModifiedIncludingChildren(TypeConvertor.convertDateToXMLGregorianCalendar(modelUddiEntity.getModifiedIncludingChildren())); + apiOperationalInfo.setNodeID(modelUddiEntity.getNodeId()); + apiOperationalInfo.setAuthorizedName(modelUddiEntity.getAuthorizedName()); + apiOperationalInfo.setEntityKey(modelUddiEntity.getEntityKey()); + } + + public static void mapSubscription(org.apache.juddi.model.Subscription modelSubscription, + org.uddi.sub_v3.Subscription apiSubscription) + throws DispositionReportFaultMessage { + + apiSubscription.setSubscriptionKey(modelSubscription.getSubscriptionKey()); + apiSubscription.setBrief(modelSubscription.isBrief()); + apiSubscription.setExpiresAfter(TypeConvertor.convertDateToXMLGregorianCalendar(modelSubscription.getExpiresAfter())); + apiSubscription.setBindingKey(modelSubscription.getBindingKey()); + apiSubscription.setMaxEntities(modelSubscription.getMaxEntities()); + apiSubscription.setNotificationInterval(TypeConvertor.convertStringToDuration(modelSubscription.getNotificationInterval())); + + try { + SubscriptionFilter existingFilter = (SubscriptionFilter) JAXBMarshaller.unmarshallFromString(modelSubscription.getSubscriptionFilter(), JAXBMarshaller.PACKAGE_SUBSCRIPTION); + apiSubscription.setSubscriptionFilter(existingFilter); + } catch (JAXBException e) { + logger.error("JAXB Exception while marshalling subscription filter", e); + throw new FatalErrorException(new ErrorMessage("errors.Unspecified")); + } + } + + public static void mapClientSubscriptionInfo(org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo, + org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo, EntityManager em) + throws DispositionReportFaultMessage { + + apiClientSubscriptionInfo.setSubscriptionKey(modelClientSubscriptionInfo.getSubscriptionKey()); + GregorianCalendar gcal = new GregorianCalendar(); + gcal.setTimeInMillis(modelClientSubscriptionInfo.getLastNotified().getTime()); + try { + apiClientSubscriptionInfo.setLastModified(DatatypeFactory.newInstance().newXMLGregorianCalendar(gcal)); + } catch (DatatypeConfigurationException ex) { + logger.warn("unable to create DatatypeFactory", ex); + } + + if (modelClientSubscriptionInfo.getFromClerk() != null) { + org.apache.juddi.api_v3.Clerk apiFromClerk = new org.apache.juddi.api_v3.Clerk(); + mapClerk(modelClientSubscriptionInfo.getFromClerk(), apiFromClerk,em); + apiClientSubscriptionInfo.setFromClerk(apiFromClerk); + } + if (modelClientSubscriptionInfo.getToClerk() != null) { + org.apache.juddi.api_v3.Clerk apiToClerk = new org.apache.juddi.api_v3.Clerk(); + mapClerk(modelClientSubscriptionInfo.getToClerk(), apiToClerk,em); + apiClientSubscriptionInfo.setToClerk(apiToClerk); + } + } + + public static void mapClerk(org.apache.juddi.model.Clerk modelClerk, + org.apache.juddi.api_v3.Clerk apiClerk,EntityManager em) + throws DispositionReportFaultMessage { + + apiClerk.setName(modelClerk.getClerkName()); + apiClerk.setPassword(modelClerk.getCred()); + apiClerk.setPublisher(modelClerk.getPublisherId()); + if (modelClerk.getNode() != null) { + org.apache.juddi.api_v3.Node apiNode = new org.apache.juddi.api_v3.Node(); + mapNode( + em.find(org.apache.juddi.model.Node.class, modelClerk.getNode()) + , apiNode); + apiClerk.setNode(apiNode); + } + } + + public static void mapNode(org.apache.juddi.model.Node modelNode, + org.apache.juddi.api_v3.Node apiNode) + throws DispositionReportFaultMessage { + + apiNode.setCustodyTransferUrl(modelNode.getCustodyTransferUrl()); + apiNode.setFactoryInitial(modelNode.getFactoryInitial()); + apiNode.setFactoryNamingProvider(modelNode.getFactoryNamingProvider()); + apiNode.setFactoryURLPkgs(modelNode.getFactoryURLPkgs()); + apiNode.setInquiryUrl(modelNode.getInquiryUrl()); + apiNode.setJuddiApiUrl(modelNode.getJuddiApiUrl()); + apiNode.setName(modelNode.getName()); + apiNode.setClientName(modelNode.getClientName()); + apiNode.setProxyTransport(modelNode.getProxyTransport()); + apiNode.setPublishUrl(modelNode.getPublishUrl()); + apiNode.setSecurityUrl(modelNode.getSecurityUrl()); + apiNode.setSubscriptionUrl(modelNode.getSubscriptionUrl()); + apiNode.setSubscriptionListenerUrl(modelNode.getSubscriptionListenerUrl()); + apiNode.setReplicationUrl(modelNode.getReplicationUrl()); + } + + private static Object convertDataToTransformContent(String type, byte[] xformBytes) throws RuntimeException { + Object transformObject; + if (type.equals(String.class.getSimpleName())) { + try { + transformObject = new String(xformBytes, "UTF-8"); + } catch (Exception e) { + throw new RuntimeException("Error decoding string due to: " + e.getMessage(), e); + } + } else if (type.equals(byte[].class.getSimpleName())) { + transformObject = xformBytes; + } else if (type.equals(Element.class.getCanonicalName())) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + try { + dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + dbf.setNamespaceAware(true); + dbf.setXIncludeAware(true); + + DocumentBuilder db = dbf.newDocumentBuilder(); + Document doc = db.parse(new ByteArrayInputStream(xformBytes)); + transformObject = doc.getDocumentElement(); + } catch (Exception e) { + throw new RuntimeException("Failed to parse element due to: " + e.getMessage(), e); + } + } else { + throw new RuntimeException("Unrecognized type: " + type); + } + return transformObject; + } + + public static void mapReplicationConfiguration(ReplicationConfiguration find, org.uddi.repl_v3.ReplicationConfiguration item) throws DispositionReportFaultMessage { + item.setMaximumTimeToGetChanges(find.getMaximumTimeToGetChanges()); + item.setMaximumTimeToSyncRegistry(find.getMaximumTimeToSyncRegistry()); + item.setSerialNumber(find.getSerialNumber()); + + List sigs = new ArrayList(); + mapSignature(find.getSignatures(), sigs); + item.getSignature().addAll(sigs); + mapOperator(find.getOperator(), item.getOperator()); + + List modelContactList = new ArrayList(); + org.uddi.api_v3.Contacts cs = new Contacts(); + + mapContacts(modelContactList, cs, new BusinessEntity()); + item.setRegistryContact(new org.uddi.repl_v3.ReplicationConfiguration.RegistryContact()); + if (!cs.getContact().isEmpty()) { + + item.getRegistryContact().setContact(cs.getContact().get(0)); + } + else + { + item.getRegistryContact().setContact(new Contact()); + item.getRegistryContact().getContact().getPersonName().add(new PersonName("unknown", null)); + } + item.setTimeOfConfigurationUpdate(find.getTimeOfConfigurationUpdate()); + CommunicationGraph xcom = new CommunicationGraph(); + + mapCommunicationGraph(find, xcom); + item.setCommunicationGraph(xcom); + //(List modelContactList, + //org.uddi.api_v3.Contacts apiContacts, + //org.uddi.api_v3.BusinessEntity apiBusinessEntity) + } + + private static void mapOperator(List model, List api) throws DispositionReportFaultMessage { + for (int i = 0; i < model.size(); i++) { + Operator op = new Operator(); + op.setOperatorNodeID(model.get(i).getOperatorNodeID()); + op.setSoapReplicationURL(model.get(i).getSoapReplicationURL()); + switch (model.get(i).getOperatorStatus()) { + case NEW: + op.setOperatorStatus(OperatorStatusType.NEW); + break; + case NORMAL: + op.setOperatorStatus(OperatorStatusType.NORMAL); + break; + case RESIGNED: + op.setOperatorStatus(OperatorStatusType.RESIGNED); + break; + } + Contacts c = new Contacts(); + mapContacts(model.get(i).getContact(), c, new BusinessEntity()); + op.getContact().addAll(c.getContact()); + + if (model.get(i).getKeyInfo() != null) { + for (int x = 0; x < model.get(i).getKeyInfo().size(); x++) { + KeyInfoType apiKeyInfo = new KeyInfoType(); + KeyInfo modelKeyInfo = model.get(i).getKeyInfo().get(x); + apiKeyInfo.setId(modelKeyInfo.getXmlID()); + List modelKeyDataValueList = modelKeyInfo.getKeyDataValue(); + List apiX509KeyInfoList = apiKeyInfo.getContent(); + mapModelKeyDataValue(modelKeyDataValueList, apiX509KeyInfoList); + op.getKeyInfo().add(apiKeyInfo); + } + } + api.add(op); + } + + } + + private static void mapCommunicationGraph(org.apache.juddi.model.ReplicationConfiguration model, + CommunicationGraph api) { + + mapEdge(model.getEdge(), api.getEdge()); + mapControlMessages(model.getControlMessage(), api.getControlledMessage()); + mapEdgeNodes(model.getNode(), api.getNode()); + + } + + private static void mapEdge(List model, List api) { + Iterator it = model.iterator(); + while (it.hasNext()) { + Edge modelEdge = it.next(); + + CommunicationGraph.Edge apiEdge = new CommunicationGraph.Edge(); + apiEdge.setMessageReceiver(modelEdge.getMessageReceiver()); + apiEdge.setMessageSender(modelEdge.getMessageSender()); + + Iterator it2 = modelEdge.getMessages().iterator(); + while (it2.hasNext()) { + apiEdge.getMessage().add(it2.next().getMessage()); + } + Iterator it3 = modelEdge.getMessageReceiverAlternate().iterator(); + while (it3.hasNext()) { + apiEdge.getMessageReceiverAlternate().add(it3.next().getReceiverAlternate()); + } + + api.add(apiEdge); + + } + } + + private static void mapControlMessages(List model, List api) { + Iterator it = model.iterator(); + while (it.hasNext()) { + api.add(it.next().getMessage()); + } + } + + private static void mapEdgeNodes(List model, List api) { + Iterator it = model.iterator(); + while (it.hasNext()) { + api.add(it.next().getNodeName()); + } + } + + public static ChangeRecord mapChangeRecord(org.apache.juddi.model.ChangeRecord cr) { + if (cr == null) { + return null; + } + ChangeRecord ret = null; + + StringReader sr = null; + try { + sr = new StringReader(new String(cr.getContents(), "UTF8")); + } catch (UnsupportedEncodingException ex) { + Logger.getLogger(MappingModelToApi.class.getName()).log(Level.SEVERE, null, ex); + } + ret = (ChangeRecord) XmlUtils.unmarshal(sr, ChangeRecord.class); + //secret sauce here, if this is -1, that means that the record originated at this node and needs to be populated with the databases record id + if (cr.getOriginatingUSN() == null || cr.getOriginatingUSN() == -1L) { + ret.setChangeID(new ChangeRecordIDType(cr.getNodeID(), cr.getId())); + } else { + ret.setChangeID(new ChangeRecordIDType(cr.getNodeID(), cr.getOriginatingUSN())); + } + return ret; + + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/mapping/package-info.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/mapping/package-info.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/mapping/package-info.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/mapping/package-info.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/Address.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/Address.java similarity index 99% rename from juddi-core/src/main/java/org/apache/juddi/model/Address.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/Address.java index c0c339a07..49954c7b8 100644 --- a/juddi-core/src/main/java/org/apache/juddi/model/Address.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/Address.java @@ -59,6 +59,7 @@ public Address(Long id, Contact contact, String useType, this.sortCode = sortCode; this.tmodelKey = tmodelKey; this.addressLines = addressLines; + this.id=id; } @Id diff --git a/juddi-core/src/main/java/org/apache/juddi/model/AddressLine.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/AddressLine.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/AddressLine.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/AddressLine.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/AuthToken.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/AuthToken.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/AuthToken.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/AuthToken.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/BindingCategoryBag.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/BindingCategoryBag.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/BindingCategoryBag.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/BindingCategoryBag.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/BindingDescr.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/BindingDescr.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/BindingDescr.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/BindingDescr.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/BindingTemplate.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/BindingTemplate.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/BindingTemplate.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/BindingTemplate.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/BusinessCategoryBag.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/BusinessCategoryBag.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/BusinessCategoryBag.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/BusinessCategoryBag.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/BusinessDescr.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/BusinessDescr.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/BusinessDescr.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/BusinessDescr.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/BusinessEntity.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/BusinessEntity.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/BusinessEntity.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/BusinessEntity.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/BusinessIdentifier.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/BusinessIdentifier.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/BusinessIdentifier.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/BusinessIdentifier.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/BusinessName.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/BusinessName.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/BusinessName.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/BusinessName.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/BusinessService.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/BusinessService.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/BusinessService.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/BusinessService.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/CanonicalizationMethod.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/CanonicalizationMethod.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/CanonicalizationMethod.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/CanonicalizationMethod.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/CategoryBag.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/CategoryBag.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/CategoryBag.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/CategoryBag.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/ChangeRecord.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/ChangeRecord.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/ChangeRecord.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/ChangeRecord.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/Clerk.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/Clerk.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/Clerk.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/Clerk.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/ClientSubscriptionInfo.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/ClientSubscriptionInfo.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/ClientSubscriptionInfo.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/ClientSubscriptionInfo.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/Contact.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/Contact.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/Contact.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/Contact.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/ContactDescr.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/ContactDescr.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/ContactDescr.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/ContactDescr.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/ControlMessage.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/ControlMessage.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/ControlMessage.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/ControlMessage.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/DiscoveryUrl.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/DiscoveryUrl.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/DiscoveryUrl.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/DiscoveryUrl.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/Edge.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/Edge.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/Edge.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/Edge.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/EdgeReceiverAlternate.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/EdgeReceiverAlternate.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/EdgeReceiverAlternate.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/EdgeReceiverAlternate.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/Email.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/Email.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/Email.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/Email.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/InstanceDetailsDescr.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/InstanceDetailsDescr.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/InstanceDetailsDescr.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/InstanceDetailsDescr.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/InstanceDetailsDocDescr.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/InstanceDetailsDocDescr.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/InstanceDetailsDocDescr.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/InstanceDetailsDocDescr.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/KeyDataValue.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/KeyDataValue.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/KeyDataValue.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/KeyDataValue.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/KeyInfo.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/KeyInfo.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/KeyInfo.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/KeyInfo.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/KeyedReference.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/KeyedReference.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/KeyedReference.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/KeyedReference.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/KeyedReferenceGroup.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/KeyedReferenceGroup.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/KeyedReferenceGroup.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/KeyedReferenceGroup.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/Node.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/Node.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/Node.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/Node.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/ObjectType.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/ObjectType.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/ObjectType.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/ObjectType.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/ObjectTypeContent.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/ObjectTypeContent.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/ObjectTypeContent.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/ObjectTypeContent.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/Operator.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/Operator.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/Operator.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/Operator.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/OperatorStatusType.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/OperatorStatusType.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/OperatorStatusType.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/OperatorStatusType.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/OverviewDoc.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/OverviewDoc.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/OverviewDoc.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/OverviewDoc.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/OverviewDocDescr.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/OverviewDocDescr.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/OverviewDocDescr.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/OverviewDocDescr.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/PersonName.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/PersonName.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/PersonName.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/PersonName.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/Phone.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/Phone.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/Phone.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/Phone.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/Publisher.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/Publisher.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/Publisher.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/Publisher.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/PublisherAssertion.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/PublisherAssertion.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/PublisherAssertion.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/PublisherAssertion.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/PublisherAssertionId.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/PublisherAssertionId.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/PublisherAssertionId.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/PublisherAssertionId.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/Reference.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/Reference.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/Reference.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/Reference.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/ReplicationConfiguration.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/ReplicationConfiguration.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/ReplicationConfiguration.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/ReplicationConfiguration.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/ReplicationConfigurationNode.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/ReplicationConfigurationNode.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/ReplicationConfigurationNode.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/ReplicationConfigurationNode.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/ServiceCategoryBag.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/ServiceCategoryBag.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/ServiceCategoryBag.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/ServiceCategoryBag.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/ServiceDescr.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/ServiceDescr.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/ServiceDescr.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/ServiceDescr.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/ServiceName.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/ServiceName.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/ServiceName.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/ServiceName.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/ServiceProjection.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/ServiceProjection.java similarity index 96% rename from juddi-core/src/main/java/org/apache/juddi/model/ServiceProjection.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/ServiceProjection.java index a4a1c3c15..a47b8fc62 100644 --- a/juddi-core/src/main/java/org/apache/juddi/model/ServiceProjection.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/ServiceProjection.java @@ -1,77 +1,77 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.model; - -import javax.persistence.EmbeddedId; -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; - -/** - * @author Jeff Faath - */ -@Entity -@Table(name = "j3_service_projection") -public class ServiceProjection implements java.io.Serializable { - - private static final long serialVersionUID = -8404899558507142913L; - @EmbeddedId - private ServiceProjectionId id = new ServiceProjectionId(); - @ManyToOne - @JoinColumn(name = "business_key", insertable = false, updatable = false) - private BusinessEntity businessEntity; - @ManyToOne - @JoinColumn(name = "service_key", insertable = false, updatable = false) - private BusinessService businessService; - - public ServiceProjection() { - } - - public ServiceProjection(BusinessEntity businessEntity, BusinessService businessService) { - this.businessEntity = businessEntity; - this.businessService = businessService; - - this.id.businessKey = businessEntity.entityKey; - this.id.serviceKey = businessService.entityKey; - - businessEntity.getServiceProjections().add(this); - businessService.getProjectingBusinesses().add(this); - } - - public ServiceProjectionId getId() { - return id; - } - public void setId(ServiceProjectionId id) { - this.id = id; - } - - public BusinessEntity getBusinessEntity() { - return businessEntity; - } - public void setBusinessEntity(BusinessEntity businessEntity) { - this.businessEntity = businessEntity; - } - - public BusinessService getBusinessService() { - return businessService; - } - public void setBusinessService(BusinessService businessService) { - this.businessService = businessService; - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.model; + +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +/** + * @author Jeff Faath + */ +@Entity +@Table(name = "j3_service_projection") +public class ServiceProjection implements java.io.Serializable { + + private static final long serialVersionUID = -8404899558507142913L; + @EmbeddedId + private ServiceProjectionId id = new ServiceProjectionId(); + @ManyToOne + @JoinColumn(name = "business_key", insertable = false, updatable = false) + private BusinessEntity businessEntity; + @ManyToOne + @JoinColumn(name = "service_key", insertable = false, updatable = false) + private BusinessService businessService; + + public ServiceProjection() { + } + + public ServiceProjection(BusinessEntity businessEntity, BusinessService businessService) { + this.businessEntity = businessEntity; + this.businessService = businessService; + + this.id.businessKey = businessEntity.entityKey; + this.id.serviceKey = businessService.entityKey; + + businessEntity.getServiceProjections().add(this); + businessService.getProjectingBusinesses().add(this); + } + + public ServiceProjectionId getId() { + return id; + } + public void setId(ServiceProjectionId id) { + this.id = id; + } + + public BusinessEntity getBusinessEntity() { + return businessEntity; + } + public void setBusinessEntity(BusinessEntity businessEntity) { + this.businessEntity = businessEntity; + } + + public BusinessService getBusinessService() { + return businessService; + } + public void setBusinessService(BusinessService businessService) { + this.businessService = businessService; + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/model/ServiceProjectionId.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/ServiceProjectionId.java similarity index 96% rename from juddi-core/src/main/java/org/apache/juddi/model/ServiceProjectionId.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/ServiceProjectionId.java index 5f0a10d6d..1428ade68 100644 --- a/juddi-core/src/main/java/org/apache/juddi/model/ServiceProjectionId.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/ServiceProjectionId.java @@ -1,73 +1,73 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.model; - -import javax.persistence.Column; -import javax.persistence.Embeddable; - -/** - * @author Jeff Faath - */ - - -@Embeddable -public class ServiceProjectionId implements java.io.Serializable { - - private static final long serialVersionUID = 3146022787279005205L; - @Column(name = "business_key", nullable = false, length = 255) - String businessKey; - @Column(name = "service_key", nullable = false, length = 255) - String serviceKey; - - public ServiceProjectionId() { - } - public ServiceProjectionId(String businessKey, String serviceKey) { - this.businessKey = businessKey; - this.serviceKey = serviceKey; - } - - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((businessKey == null) ? 0 : businessKey.hashCode()); - result = prime * result - + ((serviceKey == null) ? 0 : serviceKey.hashCode()); - return result; - } - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ServiceProjectionId other = (ServiceProjectionId) obj; - if (businessKey == null) { - if (other.businessKey != null) - return false; - } else if (!businessKey.equals(other.businessKey)) - return false; - if (serviceKey == null) { - if (other.serviceKey != null) - return false; - } else if (!serviceKey.equals(other.serviceKey)) - return false; - return true; - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.model; + +import javax.persistence.Column; +import javax.persistence.Embeddable; + +/** + * @author Jeff Faath + */ + + +@Embeddable +public class ServiceProjectionId implements java.io.Serializable { + + private static final long serialVersionUID = 3146022787279005205L; + @Column(name = "business_key", nullable = false, length = 255) + String businessKey; + @Column(name = "service_key", nullable = false, length = 255) + String serviceKey; + + public ServiceProjectionId() { + } + public ServiceProjectionId(String businessKey, String serviceKey) { + this.businessKey = businessKey; + this.serviceKey = serviceKey; + } + + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + + ((businessKey == null) ? 0 : businessKey.hashCode()); + result = prime * result + + ((serviceKey == null) ? 0 : serviceKey.hashCode()); + return result; + } + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ServiceProjectionId other = (ServiceProjectionId) obj; + if (businessKey == null) { + if (other.businessKey != null) + return false; + } else if (!businessKey.equals(other.businessKey)) + return false; + if (serviceKey == null) { + if (other.serviceKey != null) + return false; + } else if (!serviceKey.equals(other.serviceKey)) + return false; + return true; + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/model/Signature.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/Signature.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/Signature.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/Signature.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/SignatureMethod.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/SignatureMethod.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/SignatureMethod.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/SignatureMethod.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/SignatureTransform.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/SignatureTransform.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/SignatureTransform.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/SignatureTransform.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/SignatureTransformDataValue.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/SignatureTransformDataValue.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/SignatureTransformDataValue.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/SignatureTransformDataValue.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/SignatureValue.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/SignatureValue.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/SignatureValue.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/SignatureValue.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/SignedInfo.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/SignedInfo.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/SignedInfo.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/SignedInfo.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/Subscription.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/Subscription.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/Subscription.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/Subscription.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/SubscriptionChunkToken.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/SubscriptionChunkToken.java similarity index 96% rename from juddi-core/src/main/java/org/apache/juddi/model/SubscriptionChunkToken.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/SubscriptionChunkToken.java index 74a214bf9..05a63f561 100644 --- a/juddi-core/src/main/java/org/apache/juddi/model/SubscriptionChunkToken.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/SubscriptionChunkToken.java @@ -1,104 +1,104 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.model; - -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -/** - * @author Jeff Faath - */ -@Entity -@Table(name = "j3_subscription_chunk_token") -public class SubscriptionChunkToken implements java.io.Serializable { - - private static final long serialVersionUID = 3839994259992953856L; - private String chunkToken; - private String subscriptionKey; - private Date startPoint; - private Date endPoint; - private Integer data; - private Date expiresAfter; - - public SubscriptionChunkToken() { - - } - - public SubscriptionChunkToken(String chunkToken) { - this.chunkToken = chunkToken; - } - - @Id - @Column(name = "chunk_token", nullable = false, length = 255) - public String getChunkToken() { - return chunkToken; - } - public void setChunkToken(String chunkToken) { - this.chunkToken = chunkToken; - } - - @Column(name = "subscription_key", nullable = false, length = 255) - public String getSubscriptionKey() { - return subscriptionKey; - } - public void setSubscriptionKey(String subscriptionKey) { - this.subscriptionKey = subscriptionKey; - } - - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "start_point", length = 29) - public Date getStartPoint() { - return startPoint; - } - public void setStartPoint(Date startPoint) { - this.startPoint = startPoint; - } - - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "end_point", length = 29) - public Date getEndPoint() { - return endPoint; - } - public void setEndPoint(Date endPoint) { - this.endPoint = endPoint; - } - - @Column(name = "data", nullable = false) - public Integer getData() { - return data; - } - public void setData(Integer data) { - this.data = data; - } - - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "expires_after", nullable = false, length = 29) - public Date getExpiresAfter() { - return expiresAfter; - } - public void setExpiresAfter(Date expiresAfter) { - this.expiresAfter = expiresAfter; - } - - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.model; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +/** + * @author Jeff Faath + */ +@Entity +@Table(name = "j3_subscription_chunk_token") +public class SubscriptionChunkToken implements java.io.Serializable { + + private static final long serialVersionUID = 3839994259992953856L; + private String chunkToken; + private String subscriptionKey; + private Date startPoint; + private Date endPoint; + private Integer data; + private Date expiresAfter; + + public SubscriptionChunkToken() { + + } + + public SubscriptionChunkToken(String chunkToken) { + this.chunkToken = chunkToken; + } + + @Id + @Column(name = "chunk_token", nullable = false, length = 255) + public String getChunkToken() { + return chunkToken; + } + public void setChunkToken(String chunkToken) { + this.chunkToken = chunkToken; + } + + @Column(name = "subscription_key", nullable = false, length = 255) + public String getSubscriptionKey() { + return subscriptionKey; + } + public void setSubscriptionKey(String subscriptionKey) { + this.subscriptionKey = subscriptionKey; + } + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "start_point", length = 29) + public Date getStartPoint() { + return startPoint; + } + public void setStartPoint(Date startPoint) { + this.startPoint = startPoint; + } + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "end_point", length = 29) + public Date getEndPoint() { + return endPoint; + } + public void setEndPoint(Date endPoint) { + this.endPoint = endPoint; + } + + @Column(name = "data", nullable = false) + public Integer getData() { + return data; + } + public void setData(Integer data) { + this.data = data; + } + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "expires_after", nullable = false, length = 29) + public Date getExpiresAfter() { + return expiresAfter; + } + public void setExpiresAfter(Date expiresAfter) { + this.expiresAfter = expiresAfter; + } + + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/model/SubscriptionMatch.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/SubscriptionMatch.java similarity index 96% rename from juddi-core/src/main/java/org/apache/juddi/model/SubscriptionMatch.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/SubscriptionMatch.java index dcb2a8a7e..ddf756986 100644 --- a/juddi-core/src/main/java/org/apache/juddi/model/SubscriptionMatch.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/SubscriptionMatch.java @@ -1,77 +1,77 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.model; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; - -/** - * @author Jeff Faath - */ -@Entity -@Table(name = "j3_subscription_match") -public class SubscriptionMatch implements java.io.Serializable { - - private static final long serialVersionUID = -7603419240922639070L; - private Long id; - private Subscription subscription; - private String entityKey; - - public SubscriptionMatch() { - } - - public SubscriptionMatch(Subscription subscription, String entityKey) { - this.subscription = subscription; - this.entityKey = entityKey; - } - - @Id - @GeneratedValue(strategy=GenerationType.AUTO) - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "subscription_key", nullable = false) - public Subscription getSubscription() { - return subscription; - } - public void setSubscription(Subscription subscription) { - this.subscription = subscription; - } - - @Column(name = "entity_key", nullable = false) - public String getEntityKey() { - return entityKey; - } - public void setEntityKey(String entityKey) { - this.entityKey = entityKey; - } - - - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +/** + * @author Jeff Faath + */ +@Entity +@Table(name = "j3_subscription_match") +public class SubscriptionMatch implements java.io.Serializable { + + private static final long serialVersionUID = -7603419240922639070L; + private Long id; + private Subscription subscription; + private String entityKey; + + public SubscriptionMatch() { + } + + public SubscriptionMatch(Subscription subscription, String entityKey) { + this.subscription = subscription; + this.entityKey = entityKey; + } + + @Id + @GeneratedValue(strategy=GenerationType.AUTO) + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "subscription_key", nullable = false) + public Subscription getSubscription() { + return subscription; + } + public void setSubscription(Subscription subscription) { + this.subscription = subscription; + } + + @Column(name = "entity_key", nullable = false) + public String getEntityKey() { + return entityKey; + } + public void setEntityKey(String entityKey) { + this.entityKey = entityKey; + } + + + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/model/TempKey.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/TempKey.java similarity index 99% rename from juddi-core/src/main/java/org/apache/juddi/model/TempKey.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/TempKey.java index 398b95761..5788ef105 100644 --- a/juddi-core/src/main/java/org/apache/juddi/model/TempKey.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/TempKey.java @@ -15,7 +15,7 @@ * limitations under the License. */ -import javax.persistence.EmbeddedId; +import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Table; @@ -32,8 +32,8 @@ public class TempKey implements java.io.Serializable { public TempKey(){ } - - @EmbeddedId + + @EmbeddedId public TempKeyPK getPk() { return pk; } diff --git a/juddi-core/src/main/java/org/apache/juddi/model/TempKeyPK.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/TempKeyPK.java similarity index 96% rename from juddi-core/src/main/java/org/apache/juddi/model/TempKeyPK.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/TempKeyPK.java index a97026d4e..777dae848 100644 --- a/juddi-core/src/main/java/org/apache/juddi/model/TempKeyPK.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/TempKeyPK.java @@ -1,79 +1,79 @@ -package org.apache.juddi.model; -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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. - */ - -import javax.persistence.Column; -import javax.persistence.Embeddable; - -import org.apache.commons.lang.builder.HashCodeBuilder; - -/** - * @author Kurt Stam - */ - -@Embeddable -public class TempKeyPK implements java.io.Serializable { - - private static final long serialVersionUID = 790951819871694597L; - private String entityKey; - private String txId; - - public TempKeyPK(){ - } - - @Column(name = "entity_key", nullable = false, length = 255) - public String getEntityKey() { - return entityKey; - } - public void setEntityKey(String entityKey) { - this.entityKey = entityKey; - } - - @Column(name = "tx_id", nullable = false, length = 255) - public String getTxId() { - return txId; - } - public void setTxId(String txId) { - this.txId = txId; - } - - public int compareTo(TempKeyPK o) { - if (o==null || o.getEntityKey()==null || o.getTxId()==null) return 0; - if (o.getEntityKey().equals(getEntityKey()) && o.getTxId().equals(getTxId())) return 1; - else return 0; - } - - @Override - public boolean equals(Object obj) { - if (obj!=null && obj instanceof TempKeyPK) { - int i = compareTo((TempKeyPK) obj); - if (i==1) return true; - else return false; - } else { - return false; - } - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers - append(getTxId()). - append(getEntityKey()). - toHashCode(); - } -} - - +package org.apache.juddi.model; +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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. + */ + +import javax.persistence.Column; +import javax.persistence.Embeddable; + +import org.apache.commons.lang.builder.HashCodeBuilder; + +/** + * @author Kurt Stam + */ + +@Embeddable +public class TempKeyPK implements java.io.Serializable { + + private static final long serialVersionUID = 790951819871694597L; + private String entityKey; + private String txId; + + public TempKeyPK(){ + } + + @Column(name = "entity_key", nullable = false, length = 255) + public String getEntityKey() { + return entityKey; + } + public void setEntityKey(String entityKey) { + this.entityKey = entityKey; + } + + @Column(name = "tx_id", nullable = false, length = 255) + public String getTxId() { + return txId; + } + public void setTxId(String txId) { + this.txId = txId; + } + + public int compareTo(TempKeyPK o) { + if (o==null || o.getEntityKey()==null || o.getTxId()==null) return 0; + if (o.getEntityKey().equals(getEntityKey()) && o.getTxId().equals(getTxId())) return 1; + else return 0; + } + + @Override + public boolean equals(Object obj) { + if (obj!=null && obj instanceof TempKeyPK) { + int i = compareTo((TempKeyPK) obj); + if (i==1) return true; + else return false; + } else { + return false; + } + } + + @Override + public int hashCode() { + return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers + append(getTxId()). + append(getEntityKey()). + toHashCode(); + } +} + + diff --git a/juddi-core/src/main/java/org/apache/juddi/model/Tmodel.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/Tmodel.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/Tmodel.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/Tmodel.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/TmodelCategoryBag.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/TmodelCategoryBag.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/TmodelCategoryBag.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/TmodelCategoryBag.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/TmodelDescr.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/TmodelDescr.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/TmodelDescr.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/TmodelDescr.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/TmodelIdentifier.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/TmodelIdentifier.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/TmodelIdentifier.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/TmodelIdentifier.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/TmodelInstanceInfo.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/TmodelInstanceInfo.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/TmodelInstanceInfo.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/TmodelInstanceInfo.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/TmodelInstanceInfoDescr.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/TmodelInstanceInfoDescr.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/TmodelInstanceInfoDescr.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/TmodelInstanceInfoDescr.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/TransferToken.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/TransferToken.java similarity index 99% rename from juddi-core/src/main/java/org/apache/juddi/model/TransferToken.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/TransferToken.java index 39e6cb722..d737baf2e 100644 --- a/juddi-core/src/main/java/org/apache/juddi/model/TransferToken.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/TransferToken.java @@ -17,7 +17,7 @@ package org.apache.juddi.model; -import javax.persistence.*; +import javax.persistence.*; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -53,7 +53,7 @@ public void setTransferToken(String transferToken) { this.transferToken = transferToken; } - @Temporal(TemporalType.TIMESTAMP) + @Temporal(TemporalType.TIMESTAMP) @Column(name="expiration_date", nullable = false, updatable = false) public Date getExpirationDate() { return expirationDate; diff --git a/juddi-core/src/main/java/org/apache/juddi/model/TransferTokenKey.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/TransferTokenKey.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/TransferTokenKey.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/TransferTokenKey.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/UddiEntity.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/UddiEntity.java similarity index 96% rename from juddi-core/src/main/java/org/apache/juddi/model/UddiEntity.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/UddiEntity.java index a91171d91..ef0d6190e 100644 --- a/juddi-core/src/main/java/org/apache/juddi/model/UddiEntity.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/UddiEntity.java @@ -1,129 +1,129 @@ -package org.apache.juddi.model; -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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. - */ - -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -/** - * @author Jeff Faath - */ -@Entity -@Table(name = "j3_uddi_entity") -@Inheritance(strategy = InheritanceType.JOINED) -public abstract class UddiEntity implements Comparable{ - - protected String entityKey; - protected Date created; - protected Date modified; - protected Date modifiedIncludingChildren; - protected String nodeId; - protected String authorizedName; - protected boolean xfer = false; - - @Id - @Column(name = "entity_key", nullable = false, length = 255) - public String getEntityKey() { - return entityKey; - } - public void setEntityKey(String entityKey) { - this.entityKey = entityKey; - } - - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "created", length = 29) - public Date getCreated() { - if (created!=null) { - return new Date(created.getTime()); - } else { - return null; - } - } - public void setCreated(Date created) { - this.created = created; - } - - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "modified", nullable = false, length = 29) - public Date getModified() { - if (modified!=null) { - return new Date(modified.getTime()); - } else { - return null; - } - } - public void setModified(Date modified) { - this.modified = modified; - } - - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "modified_including_children", length = 29) - public Date getModifiedIncludingChildren() { - if (modifiedIncludingChildren!=null) { - return new Date(modifiedIncludingChildren.getTime()); - } else { - return null; - } - } - public void setModifiedIncludingChildren(Date modifiedIncludingChildren) { - this.modifiedIncludingChildren = modifiedIncludingChildren; - } - - /** - * As of 3.2, node_id is a required field - * @return node id - */ - @Column(name = "node_id", nullable=false,length = 255) - public String getNodeId() { - return nodeId; - } - public void setNodeId(String nodeId) { - this.nodeId = nodeId; - } - - - @Column(name = "authorized_name", nullable=false, length = 255) - public String getAuthorizedName() { - return authorizedName; - } - public void setAuthorizedName(String authorizedName) { - this.authorizedName = authorizedName; - } - - public int compareTo(UddiEntity o) { - if (o==null || o.getEntityKey()==null) return 0; - if (o.getEntityKey().equals(getEntityKey())) return 1; - else return 0; - } - - public void setIsTransferInProgress(boolean b) { - xfer = b; - } - @Column(name="xfer", nullable=false) - public boolean getIsTransferInProgress() - { - return xfer; - } - -} +package org.apache.juddi.model; +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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. + */ + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +/** + * @author Jeff Faath + */ +@Entity +@Table(name = "j3_uddi_entity") +@Inheritance(strategy = InheritanceType.JOINED) +public abstract class UddiEntity implements Comparable{ + + protected String entityKey; + protected Date created; + protected Date modified; + protected Date modifiedIncludingChildren; + protected String nodeId; + protected String authorizedName; + protected boolean xfer = false; + + @Id + @Column(name = "entity_key", nullable = false, length = 255) + public String getEntityKey() { + return entityKey; + } + public void setEntityKey(String entityKey) { + this.entityKey = entityKey; + } + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "created", length = 29) + public Date getCreated() { + if (created!=null) { + return new Date(created.getTime()); + } else { + return null; + } + } + public void setCreated(Date created) { + this.created = created; + } + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "modified", nullable = false, length = 29) + public Date getModified() { + if (modified!=null) { + return new Date(modified.getTime()); + } else { + return null; + } + } + public void setModified(Date modified) { + this.modified = modified; + } + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "modified_including_children", length = 29) + public Date getModifiedIncludingChildren() { + if (modifiedIncludingChildren!=null) { + return new Date(modifiedIncludingChildren.getTime()); + } else { + return null; + } + } + public void setModifiedIncludingChildren(Date modifiedIncludingChildren) { + this.modifiedIncludingChildren = modifiedIncludingChildren; + } + + /** + * As of 3.2, node_id is a required field + * @return node id + */ + @Column(name = "node_id", nullable=false,length = 255) + public String getNodeId() { + return nodeId; + } + public void setNodeId(String nodeId) { + this.nodeId = nodeId; + } + + + @Column(name = "authorized_name", nullable=false, length = 255) + public String getAuthorizedName() { + return authorizedName; + } + public void setAuthorizedName(String authorizedName) { + this.authorizedName = authorizedName; + } + + public int compareTo(UddiEntity o) { + if (o==null || o.getEntityKey()==null) return 0; + if (o.getEntityKey().equals(getEntityKey())) return 1; + else return 0; + } + + public void setIsTransferInProgress(boolean b) { + xfer = b; + } + @Column(name="xfer", nullable=false) + public boolean getIsTransferInProgress() + { + return xfer; + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/model/UddiEntityPublisher.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/UddiEntityPublisher.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/model/UddiEntityPublisher.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/UddiEntityPublisher.java index 20c9aed1f..4c05d9f00 100644 --- a/juddi-core/src/main/java/org/apache/juddi/model/UddiEntityPublisher.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/UddiEntityPublisher.java @@ -1,221 +1,221 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.model; - -import java.util.List; -import java.util.StringTokenizer; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.persistence.Column; -import javax.persistence.EntityManager; -import javax.persistence.Id; -import javax.persistence.MappedSuperclass; -import javax.persistence.Query; -import javax.persistence.Transient; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.Property; - -import org.apache.juddi.keygen.KeyGenerator; -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.validation.ValidateUDDIKey; -import org.uddi.v3_service.DispositionReportFaultMessage; - -/** - * @author Jeff Faath - */ -@MappedSuperclass -public class UddiEntityPublisher { - - private transient static final Logger logger = Logger.getLogger(UddiEntityPublisher.class.getCanonicalName()); - protected String authorizedName; - private List keyGeneratorKeys = null; - - public UddiEntityPublisher() { - } - - public UddiEntityPublisher(String authorizedName) { - this.authorizedName = authorizedName; - } - - @Id - @Column(name = "authorized_name", nullable = false, length = 255) - public String getAuthorizedName() { - return this.authorizedName; - } - public void setAuthorizedName(String authorizedName) { - this.authorizedName = authorizedName; - } - - @Transient - public List getKeyGeneratorKeys() { - return keyGeneratorKeys; - } - public void setKeyGeneratorKeys(List keyGeneratorKeys) { - this.keyGeneratorKeys = keyGeneratorKeys; - } - - @SuppressWarnings("unchecked") - public void populateKeyGeneratorKeys(EntityManager em) { - DynamicQuery getKeysQuery = new DynamicQuery(); - getKeysQuery.append("select t.entityKey from Tmodel t").pad().WHERE().pad(); - - DynamicQuery.Parameter pubParam = new DynamicQuery.Parameter("t.authorizedName", - getAuthorizedName(), - DynamicQuery.PREDICATE_EQUALS); - - DynamicQuery.Parameter keyParam = new DynamicQuery.Parameter("UPPER(t.entityKey)", - (DynamicQuery.WILDCARD + KeyGenerator.KEYGENERATOR_SUFFIX).toUpperCase(), - DynamicQuery.PREDICATE_LIKE); - - - getKeysQuery.appendGroupedAnd(pubParam, keyParam); - Query qry = getKeysQuery.buildJPAQuery(em); - - keyGeneratorKeys = qry.getResultList(); - } - - /** - * Determines if *this publisher owns a specific key - * @param entity - * @return true/false - */ - public boolean isOwner(UddiEntity entity){ - try { - AppConfig instance = AppConfig.getInstance(); - - if (entity != null) { - if (entity.getAuthorizedName().equals(getAuthorizedName()) - && entity.getNodeId().equals((AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID)))) { - return true; - } - } - } catch (Exception ex) { - logger.log(Level.WARNING, "Error caught determining node id! Defaulting to access denied", ex); - } - return false; - } - - - public boolean isValidPublisherKey(EntityManager em, String key) { - if (key == null) - return false; - - if (keyGeneratorKeys == null) - populateKeyGeneratorKeys(em); - - if (! key.contains(KeyGenerator.PARTITION_SEPARATOR)) return true; //v2 style key - String keyPartition = key.substring(0, key.lastIndexOf(KeyGenerator.PARTITION_SEPARATOR)); - - for (String keyGenKey : keyGeneratorKeys) { - String keyGenPartition = keyGenKey.substring(0, keyGenKey.lastIndexOf(KeyGenerator.PARTITION_SEPARATOR)); - if (keyGenPartition.equalsIgnoreCase(keyPartition)) - return true; - } - return false; - } - - /* - * This method will check if the given key generator key is available for this publisher. The idea is to make sure that the key generator - * and all its sub-partitions are not already taken by another publisher. - */ - public boolean isKeyGeneratorAvailable(EntityManager em, String keygenKey) throws DispositionReportFaultMessage { - - // First make sure the key is a valid UDDIv3 key per the specification's rules - ValidateUDDIKey.validateUDDIv3KeyGeneratorKey(keygenKey); - - String partition = keygenKey.toUpperCase().substring(0, keygenKey.lastIndexOf(KeyGenerator.PARTITION_SEPARATOR)); - - StringTokenizer tokenizer = new StringTokenizer(partition, KeyGenerator.PARTITION_SEPARATOR); - int tokenCount = tokenizer.countTokens(); - // Must have 2 or more tokens as the first is the uddi scheme and the second is the domain key. - if (tokenCount < 2) - return false; - - String domainPartition = (String)tokenizer.nextElement() + KeyGenerator.PARTITION_SEPARATOR + (String)tokenizer.nextElement(); - - // If three or more tokens then we need to make sure the current publisher has the parent partitions. For example, you can't register the - // uddi:domain:abc:123 key generator without having the uddi:domain and uddi:domain:abc key generators. This implicitly checks if another - // publisher has any of these partitions since if they do, current publisher won't have them. - if (tokenCount > 2) { - Vector params = new Vector(0); - - DynamicQuery.Parameter pubParam = new DynamicQuery.Parameter("t.authorizedName", - getAuthorizedName(), - DynamicQuery.PREDICATE_EQUALS); - - int requiredCount = 0; - params.add(new DynamicQuery.Parameter("UPPER(t.entityKey)", - (domainPartition + KeyGenerator.PARTITION_SEPARATOR + KeyGenerator.KEYGENERATOR_SUFFIX).toUpperCase(), - DynamicQuery.PREDICATE_EQUALS)); - requiredCount++; - - String subPartition = domainPartition; - while (tokenizer.hasMoreElements()) { - // Don't need to add the last token as it is the proposed key generator. - if (tokenizer.countTokens() == 1) - break; - - String nextToken = (String)tokenizer.nextElement(); - subPartition = subPartition + KeyGenerator.PARTITION_SEPARATOR + nextToken; - DynamicQuery.Parameter param = new DynamicQuery.Parameter("UPPER(t.entityKey)", - (subPartition + KeyGenerator.PARTITION_SEPARATOR + KeyGenerator.KEYGENERATOR_SUFFIX).toUpperCase(), - DynamicQuery.PREDICATE_EQUALS); - params.add(param); - requiredCount++; - } - - DynamicQuery checkParentKeyQry = new DynamicQuery(); - checkParentKeyQry.append("select COUNT(t.entityKey) from Tmodel t").pad(); - - checkParentKeyQry.WHERE().pad().appendGroupedAnd(pubParam); - checkParentKeyQry.AND().pad().appendGroupedOr(params.toArray(new DynamicQuery.Parameter[0])); - - Query qry = checkParentKeyQry.buildJPAQuery(em); - Number resultCount = (Number)qry.getSingleResult(); - if (resultCount.longValue() != requiredCount) - return false; - } - else { - // If only two tokens, then a domain key generator is being checked. A domain key generator can only be registered if no other publishers - // own it. For example, if trying to register the uddi:domain:abc:123 key then uddi:domain cannot be owned by another publisher. - DynamicQuery.Parameter notPubParam = new DynamicQuery.Parameter("t.authorizedName", - getAuthorizedName(), - DynamicQuery.PREDICATE_NOTEQUALS); - - DynamicQuery.Parameter keyParam = new DynamicQuery.Parameter("UPPER(t.entityKey)", - (domainPartition + KeyGenerator.PARTITION_SEPARATOR + KeyGenerator.KEYGENERATOR_SUFFIX).toUpperCase(), - DynamicQuery.PREDICATE_EQUALS); - - DynamicQuery checkDomainKeyQry = new DynamicQuery(); - checkDomainKeyQry.append("select t.entityKey from Tmodel t").pad(); - - checkDomainKeyQry.WHERE().pad().appendGroupedAnd(notPubParam, keyParam); - - Query qry = checkDomainKeyQry.buildJPAQuery(em); - List obj = qry.getResultList(); - // If there are results then another publisher has the domain key and therefore the key generator is unavailable - if (obj != null && obj.size() > 0) - return false; - } - - return true; - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.model; + +import java.util.List; +import java.util.StringTokenizer; +import java.util.Vector; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.persistence.Column; +import javax.persistence.EntityManager; +import javax.persistence.Id; +import javax.persistence.MappedSuperclass; +import javax.persistence.Query; +import javax.persistence.Transient; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.Property; + +import org.apache.juddi.keygen.KeyGenerator; +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.validation.ValidateUDDIKey; +import org.uddi.v3_service.DispositionReportFaultMessage; + +/** + * @author Jeff Faath + */ +@MappedSuperclass +public class UddiEntityPublisher { + + private transient static final Logger logger = Logger.getLogger(UddiEntityPublisher.class.getCanonicalName()); + protected String authorizedName; + private List keyGeneratorKeys = null; + + public UddiEntityPublisher() { + } + + public UddiEntityPublisher(String authorizedName) { + this.authorizedName = authorizedName; + } + + @Id + @Column(name = "authorized_name", nullable = false, length = 255) + public String getAuthorizedName() { + return this.authorizedName; + } + public void setAuthorizedName(String authorizedName) { + this.authorizedName = authorizedName; + } + + @Transient + public List getKeyGeneratorKeys() { + return keyGeneratorKeys; + } + public void setKeyGeneratorKeys(List keyGeneratorKeys) { + this.keyGeneratorKeys = keyGeneratorKeys; + } + + @SuppressWarnings("unchecked") + public void populateKeyGeneratorKeys(EntityManager em) { + DynamicQuery getKeysQuery = new DynamicQuery(); + getKeysQuery.append("select t.entityKey from Tmodel t").pad().WHERE().pad(); + + DynamicQuery.Parameter pubParam = new DynamicQuery.Parameter("t.authorizedName", + getAuthorizedName(), + DynamicQuery.PREDICATE_EQUALS); + + DynamicQuery.Parameter keyParam = new DynamicQuery.Parameter("UPPER(t.entityKey)", + (DynamicQuery.WILDCARD + KeyGenerator.KEYGENERATOR_SUFFIX).toUpperCase(), + DynamicQuery.PREDICATE_LIKE); + + + getKeysQuery.appendGroupedAnd(pubParam, keyParam); + Query qry = getKeysQuery.buildJPAQuery(em); + + keyGeneratorKeys = qry.getResultList(); + } + + /** + * Determines if *this publisher owns a specific key + * @param entity + * @return true/false + */ + public boolean isOwner(UddiEntity entity){ + try { + AppConfig instance = AppConfig.getInstance(); + + if (entity != null) { + if (entity.getAuthorizedName().equals(getAuthorizedName()) + && entity.getNodeId().equals((AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID)))) { + return true; + } + } + } catch (Exception ex) { + logger.log(Level.WARNING, "Error caught determining node id! Defaulting to access denied", ex); + } + return false; + } + + + public boolean isValidPublisherKey(EntityManager em, String key) { + if (key == null) + return false; + + if (keyGeneratorKeys == null) + populateKeyGeneratorKeys(em); + + if (! key.contains(KeyGenerator.PARTITION_SEPARATOR)) return true; //v2 style key + String keyPartition = key.substring(0, key.lastIndexOf(KeyGenerator.PARTITION_SEPARATOR)); + + for (String keyGenKey : keyGeneratorKeys) { + String keyGenPartition = keyGenKey.substring(0, keyGenKey.lastIndexOf(KeyGenerator.PARTITION_SEPARATOR)); + if (keyGenPartition.equalsIgnoreCase(keyPartition)) + return true; + } + return false; + } + + /* + * This method will check if the given key generator key is available for this publisher. The idea is to make sure that the key generator + * and all its sub-partitions are not already taken by another publisher. + */ + public boolean isKeyGeneratorAvailable(EntityManager em, String keygenKey) throws DispositionReportFaultMessage { + + // First make sure the key is a valid UDDIv3 key per the specification's rules + ValidateUDDIKey.validateUDDIv3KeyGeneratorKey(keygenKey); + + String partition = keygenKey.toUpperCase().substring(0, keygenKey.lastIndexOf(KeyGenerator.PARTITION_SEPARATOR)); + + StringTokenizer tokenizer = new StringTokenizer(partition, KeyGenerator.PARTITION_SEPARATOR); + int tokenCount = tokenizer.countTokens(); + // Must have 2 or more tokens as the first is the uddi scheme and the second is the domain key. + if (tokenCount < 2) + return false; + + String domainPartition = (String)tokenizer.nextElement() + KeyGenerator.PARTITION_SEPARATOR + (String)tokenizer.nextElement(); + + // If three or more tokens then we need to make sure the current publisher has the parent partitions. For example, you can't register the + // uddi:domain:abc:123 key generator without having the uddi:domain and uddi:domain:abc key generators. This implicitly checks if another + // publisher has any of these partitions since if they do, current publisher won't have them. + if (tokenCount > 2) { + Vector params = new Vector(0); + + DynamicQuery.Parameter pubParam = new DynamicQuery.Parameter("t.authorizedName", + getAuthorizedName(), + DynamicQuery.PREDICATE_EQUALS); + + int requiredCount = 0; + params.add(new DynamicQuery.Parameter("UPPER(t.entityKey)", + (domainPartition + KeyGenerator.PARTITION_SEPARATOR + KeyGenerator.KEYGENERATOR_SUFFIX).toUpperCase(), + DynamicQuery.PREDICATE_EQUALS)); + requiredCount++; + + String subPartition = domainPartition; + while (tokenizer.hasMoreElements()) { + // Don't need to add the last token as it is the proposed key generator. + if (tokenizer.countTokens() == 1) + break; + + String nextToken = (String)tokenizer.nextElement(); + subPartition = subPartition + KeyGenerator.PARTITION_SEPARATOR + nextToken; + DynamicQuery.Parameter param = new DynamicQuery.Parameter("UPPER(t.entityKey)", + (subPartition + KeyGenerator.PARTITION_SEPARATOR + KeyGenerator.KEYGENERATOR_SUFFIX).toUpperCase(), + DynamicQuery.PREDICATE_EQUALS); + params.add(param); + requiredCount++; + } + + DynamicQuery checkParentKeyQry = new DynamicQuery(); + checkParentKeyQry.append("select COUNT(t.entityKey) from Tmodel t").pad(); + + checkParentKeyQry.WHERE().pad().appendGroupedAnd(pubParam); + checkParentKeyQry.AND().pad().appendGroupedOr(params.toArray(new DynamicQuery.Parameter[0])); + + Query qry = checkParentKeyQry.buildJPAQuery(em); + Number resultCount = (Number)qry.getSingleResult(); + if (resultCount.longValue() != requiredCount) + return false; + } + else { + // If only two tokens, then a domain key generator is being checked. A domain key generator can only be registered if no other publishers + // own it. For example, if trying to register the uddi:domain:abc:123 key then uddi:domain cannot be owned by another publisher. + DynamicQuery.Parameter notPubParam = new DynamicQuery.Parameter("t.authorizedName", + getAuthorizedName(), + DynamicQuery.PREDICATE_NOTEQUALS); + + DynamicQuery.Parameter keyParam = new DynamicQuery.Parameter("UPPER(t.entityKey)", + (domainPartition + KeyGenerator.PARTITION_SEPARATOR + KeyGenerator.KEYGENERATOR_SUFFIX).toUpperCase(), + DynamicQuery.PREDICATE_EQUALS); + + DynamicQuery checkDomainKeyQry = new DynamicQuery(); + checkDomainKeyQry.append("select t.entityKey from Tmodel t").pad(); + + checkDomainKeyQry.WHERE().pad().appendGroupedAnd(notPubParam, keyParam); + + Query qry = checkDomainKeyQry.buildJPAQuery(em); + List obj = qry.getResultList(); + // If there are results then another publisher has the domain key and therefore the key generator is unavailable + if (obj != null && obj.size() > 0) + return false; + } + + return true; + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/model/ValueSetValues.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/ValueSetValues.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/ValueSetValues.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/ValueSetValues.java diff --git a/juddi-core/src/main/java/org/apache/juddi/model/package-info.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/model/package-info.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/model/package-info.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/model/package-info.java diff --git a/juddi-core/src/main/java/org/apache/juddi/query/BindingTemplateQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/BindingTemplateQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/BindingTemplateQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/BindingTemplateQuery.java index e43b32a0b..23c1f0719 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/BindingTemplateQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/BindingTemplateQuery.java @@ -1,46 +1,46 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -/** - * @author Jeff Faath - */ -public class BindingTemplateQuery extends EntityQuery { - - public static final String ENTITY_NAME = "BindingTemplate"; - public static final String ENTITY_ALIAS = "bt"; - public static final String ENTITY_FIELD = "bindingTemplate"; - public static final String KEY_NAME_PARENT = BusinessServiceQuery.ENTITY_FIELD + "." + BusinessServiceQuery.KEY_NAME; - public static final String SIGNATURE_PRESENT = - ENTITY_ALIAS + "." + EntityQuery.SIGNATURE_FIELD + " IS NOT EMPTY OR " + - ENTITY_ALIAS + ".businessService." + EntityQuery.SIGNATURE_FIELD + " IS NOT EMPTY OR " + - ENTITY_ALIAS + ".businessService.businessEntity." + EntityQuery.SIGNATURE_FIELD + " IS NOT EMPTY "; - - protected final static String selectSQL; - - static { - StringBuilder sql = new StringBuilder(200); - sql.append("select distinct "+ ENTITY_ALIAS + "." + KEY_NAME + " from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); - selectSQL = sql.toString(); - } - - public static String getSelectSQL() { - return selectSQL; - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +/** + * @author Jeff Faath + */ +public class BindingTemplateQuery extends EntityQuery { + + public static final String ENTITY_NAME = "BindingTemplate"; + public static final String ENTITY_ALIAS = "bt"; + public static final String ENTITY_FIELD = "bindingTemplate"; + public static final String KEY_NAME_PARENT = BusinessServiceQuery.ENTITY_FIELD + "." + BusinessServiceQuery.KEY_NAME; + public static final String SIGNATURE_PRESENT = + ENTITY_ALIAS + "." + EntityQuery.SIGNATURE_FIELD + " IS NOT EMPTY OR " + + ENTITY_ALIAS + ".businessService." + EntityQuery.SIGNATURE_FIELD + " IS NOT EMPTY OR " + + ENTITY_ALIAS + ".businessService.businessEntity." + EntityQuery.SIGNATURE_FIELD + " IS NOT EMPTY "; + + protected final static String selectSQL; + + static { + StringBuilder sql = new StringBuilder(200); + sql.append("select distinct "+ ENTITY_ALIAS + "." + KEY_NAME + " from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); + selectSQL = sql.toString(); + } + + public static String getSelectSQL() { + return selectSQL; + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/BusinessEntityQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/BusinessEntityQuery.java similarity index 96% rename from juddi-core/src/main/java/org/apache/juddi/query/BusinessEntityQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/BusinessEntityQuery.java index c1326ce06..6a23b135f 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/BusinessEntityQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/BusinessEntityQuery.java @@ -1,43 +1,43 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - - -/** - * @author Jeff Faath - */ -public class BusinessEntityQuery extends EntityQuery { - - public static final String ENTITY_NAME = "BusinessEntity"; - public static final String ENTITY_ALIAS = "be"; - public static final String ENTITY_FIELD = "businessEntity"; - public static final String SIGNATURE_PRESENT = ENTITY_ALIAS + "." + SIGNATURE_FIELD + " IS NOT EMPTY "; - - protected static final String selectSQL; - - static { - StringBuilder sql = new StringBuilder(200); - sql.append("select distinct "+ ENTITY_ALIAS + "." + KEY_NAME + " from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); - selectSQL = sql.toString(); - } - - public static String getSelectSQL() { - return selectSQL; - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + + +/** + * @author Jeff Faath + */ +public class BusinessEntityQuery extends EntityQuery { + + public static final String ENTITY_NAME = "BusinessEntity"; + public static final String ENTITY_ALIAS = "be"; + public static final String ENTITY_FIELD = "businessEntity"; + public static final String SIGNATURE_PRESENT = ENTITY_ALIAS + "." + SIGNATURE_FIELD + " IS NOT EMPTY "; + + protected static final String selectSQL; + + static { + StringBuilder sql = new StringBuilder(200); + sql.append("select distinct "+ ENTITY_ALIAS + "." + KEY_NAME + " from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); + selectSQL = sql.toString(); + } + + public static String getSelectSQL() { + return selectSQL; + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/BusinessServiceQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/BusinessServiceQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/BusinessServiceQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/BusinessServiceQuery.java index 6f3ff2282..e8db18da6 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/BusinessServiceQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/BusinessServiceQuery.java @@ -1,45 +1,45 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -/** - * @author Jeff Faath - */ -public class BusinessServiceQuery extends EntityQuery { - - public static final String ENTITY_NAME = "BusinessService"; - public static final String ENTITY_ALIAS = "bs"; - public static final String ENTITY_FIELD = "businessService"; - public static final String KEY_NAME_PARENT = BusinessEntityQuery.ENTITY_FIELD + "." + BusinessEntityQuery.KEY_NAME; - public static final String SIGNATURE_PRESENT = - ENTITY_ALIAS + "." + EntityQuery.SIGNATURE_FIELD + " IS NOT EMPTY OR " + - ENTITY_ALIAS + ".businessEntity." + EntityQuery.SIGNATURE_FIELD + " IS NOT EMPTY "; - - protected static final String selectSQL; - - static { - StringBuilder sql = new StringBuilder(200); - sql.append("select distinct "+ ENTITY_ALIAS + "." + KEY_NAME + " from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); - selectSQL = sql.toString(); - } - - public static String getSelectSQL() { - return selectSQL; - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +/** + * @author Jeff Faath + */ +public class BusinessServiceQuery extends EntityQuery { + + public static final String ENTITY_NAME = "BusinessService"; + public static final String ENTITY_ALIAS = "bs"; + public static final String ENTITY_FIELD = "businessService"; + public static final String KEY_NAME_PARENT = BusinessEntityQuery.ENTITY_FIELD + "." + BusinessEntityQuery.KEY_NAME; + public static final String SIGNATURE_PRESENT = + ENTITY_ALIAS + "." + EntityQuery.SIGNATURE_FIELD + " IS NOT EMPTY OR " + + ENTITY_ALIAS + ".businessEntity." + EntityQuery.SIGNATURE_FIELD + " IS NOT EMPTY "; + + protected static final String selectSQL; + + static { + StringBuilder sql = new StringBuilder(200); + sql.append("select distinct "+ ENTITY_ALIAS + "." + KEY_NAME + " from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); + selectSQL = sql.toString(); + } + + public static String getSelectSQL() { + return selectSQL; + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/DeletePublisherAssertionByBusinessQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/DeletePublisherAssertionByBusinessQuery.java similarity index 96% rename from juddi-core/src/main/java/org/apache/juddi/query/DeletePublisherAssertionByBusinessQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/DeletePublisherAssertionByBusinessQuery.java index 2423ab72d..60a07ba25 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/DeletePublisherAssertionByBusinessQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/DeletePublisherAssertionByBusinessQuery.java @@ -1,69 +1,69 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; -import javax.persistence.EntityManager; -import javax.persistence.Query; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.query.util.DynamicQuery; - -/** - * - * Returns the list of PublisherAssertions that contain the input businessKeys as their from or to key - * * - * @author Jeff Faath - */ -public class DeletePublisherAssertionByBusinessQuery extends PublisherAssertionQuery { - - private static final Log log = LogFactory.getLog(DeletePublisherAssertionByBusinessQuery.class); - - public static int delete(EntityManager em, List businessKeys) { - if ((businessKeys == null) || (businessKeys.size() == 0)) - return 0; - - DynamicQuery dynamicQry = new DynamicQuery(deleteSQL); - appendConditions(dynamicQry, businessKeys); - - log.debug(dynamicQry); - - Query qry = dynamicQry.buildJPAQuery(em); - int result = qry.executeUpdate(); - - return result; - } - - /* - * Appends the conditions to the query based on the businessKey list. The keys can either be in the fromKey or toKey of the publisher assertion. - */ - public static void appendConditions(DynamicQuery qry, List businessKeys) { - - qry.WHERE().pad().openParen().pad(); - - qry.appendInList(ENTITY_ALIAS + "." + FROM_KEY_NAME, businessKeys); - qry.pad().OR().pad(); - qry.appendInList(ENTITY_ALIAS + "." + TO_KEY_NAME, businessKeys); - qry.closeParen().pad(); - - - } - - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; +import javax.persistence.EntityManager; +import javax.persistence.Query; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.query.util.DynamicQuery; + +/** + * + * Returns the list of PublisherAssertions that contain the input businessKeys as their from or to key + * * + * @author Jeff Faath + */ +public class DeletePublisherAssertionByBusinessQuery extends PublisherAssertionQuery { + + private static final Log log = LogFactory.getLog(DeletePublisherAssertionByBusinessQuery.class); + + public static int delete(EntityManager em, List businessKeys) { + if ((businessKeys == null) || (businessKeys.size() == 0)) + return 0; + + DynamicQuery dynamicQry = new DynamicQuery(deleteSQL); + appendConditions(dynamicQry, businessKeys); + + log.debug(dynamicQry); + + Query qry = dynamicQry.buildJPAQuery(em); + int result = qry.executeUpdate(); + + return result; + } + + /* + * Appends the conditions to the query based on the businessKey list. The keys can either be in the fromKey or toKey of the publisher assertion. + */ + public static void appendConditions(DynamicQuery qry, List businessKeys) { + + qry.WHERE().pad().openParen().pad(); + + qry.appendInList(ENTITY_ALIAS + "." + FROM_KEY_NAME, businessKeys); + qry.pad().OR().pad(); + qry.appendInList(ENTITY_ALIAS + "." + TO_KEY_NAME, businessKeys); + qry.closeParen().pad(); + + + } + + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/EntityQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/EntityQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/EntityQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/EntityQuery.java index b8558aa86..edc95ca3b 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/EntityQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/EntityQuery.java @@ -1,186 +1,186 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; -import java.util.ArrayList; -import java.util.Collections; - -import javax.persistence.EntityManager; -import javax.persistence.Query; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.uddi.api_v3.ListDescription; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.Property; -import org.apache.juddi.model.TempKey; -import org.apache.juddi.query.util.DynamicQuery; - -/** - * @author Jeff Faath - */ -public abstract class EntityQuery { - private static Log log = LogFactory.getLog(EntityQuery.class); - - public static final String KEY_NAME = "entityKey"; - public static final String TEMP_ENTITY_NAME = "TempKey"; - public static final String TEMP_ENTITY_ALIAS = "tk"; - public static final String TEMP_ENTITY_PK_TXID_NAME = TEMP_ENTITY_ALIAS + ".pk.txId"; - public static final String TEMP_ENTITY_PK_KEY_NAME = TEMP_ENTITY_ALIAS + ".pk.entityKey"; - public static final String SIGNATURE_FIELD = "signatures"; - - public static final int DEFAULT_MAXROWS = 1000; - public static final int DEFAULT_MAXINCLAUSE = 1000; - - // TODO: make this alias creator a little more unique - public static String buildAlias(String entityName) { - if (entityName == null || entityName.length() == 0) - return "x"; - - return entityName.substring(0, entityName.length() - 3) + "_"; - } - - /* - * Used to retrieve the final results of find operations. Handles paging as specified by user. - * - * TODO: This query will use an IN clause, however, it is not restricted per the global parameter. This is so the query can - * take advantage of sorting through SQL. The fix would be to apply the parameter, but only if the IN list is greater than the - * parameter. In this case, sorting would have to be done in java. - * - */ - public static List getPagedResult(EntityManager em, DynamicQuery dynamicQry, Integer maxRowsUser, Integer listHead, ListDescription listDesc) { - - int maxRows = DEFAULT_MAXROWS; - try { - maxRows = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_ROWS, DEFAULT_MAXROWS); - } - catch(ConfigurationException ce) { - log.error("Configuration exception occurred retrieving: " + Property.JUDDI_MAX_ROWS); - } - - if (maxRowsUser != null && maxRowsUser > 0) { - if (maxRowsUser < maxRows) - maxRows = maxRowsUser; - } - - if (listHead == null || listHead <= 0) - listHead = 1; - - - Query qry = dynamicQry.buildJPAQuery(em); - List result = new ArrayList(); - //Filter out non-unique results - for (Object object : qry.getResultList()) { - if (!result.contains(object)) { - result.add(object); - } - } - - int resultSize = result.size(); - - if (listDesc != null) { - listDesc.setActualCount(resultSize); - listDesc.setListHead(listHead); - } - - int startIndex = listHead - 1; - if (startIndex >= resultSize) { - if (listDesc != null) - listDesc.setIncludeCount(0); - - return Collections.emptyList(); - } - else { - int endIndex = Math.min(startIndex + maxRows, resultSize); - if (listDesc != null) - listDesc.setIncludeCount(endIndex - startIndex); - - List subList = new ArrayList(endIndex); - for (int i=startIndex; i< endIndex; i++) { - subList.add(result.get(i)); - } - return subList; - } - } - - /* - * Used for all the find operation sub-queries. Restricts size of the IN clause based on global parameter - */ - @SuppressWarnings("unchecked") - public static List getQueryResult(EntityManager em, DynamicQuery dynamicQry, List keysIn, String inListTerm) { - - List result = new ArrayList(0); - // If keysIn is null, then no IN list is applied to the query - we simply need to run the query. Otherwise, the IN list is chunked based on - // the application property. - if (keysIn == null) { - if (log.isDebugEnabled()) log.debug(dynamicQry); - Query qry = dynamicQry.buildJPAQuery(em); - result = qry.getResultList(); - } - else { - int maxInClause = DEFAULT_MAXINCLAUSE; - try { - maxInClause = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_IN_CLAUSE, DEFAULT_MAXINCLAUSE); - } - catch(ConfigurationException ce) { - log.error("Configuration exception occurred retrieving: " + Property.JUDDI_MAX_IN_CLAUSE); - } - if (keysIn.isEmpty()) { - Query qry = dynamicQry.buildJPAQuery(em); - List resultChunk = qry.getResultList(); - result.addAll(resultChunk); - } else { - int inParamsLeft = keysIn.size(); - int startIndex = 0; - while(inParamsLeft > 0) { - int endIndex = startIndex + Math.min(inParamsLeft, maxInClause); - - List subKeysIn = new ArrayList(endIndex); - for (int i=startIndex; i< endIndex; i++) { - subKeysIn.add(keysIn.get(i)); - } - dynamicQry.appendInListWithAnd(inListTerm, subKeysIn); - log.debug(dynamicQry); - - Query qry = dynamicQry.buildJPAQuery(em); - List resultChunk = qry.getResultList(); - result.addAll(resultChunk); - - inParamsLeft = inParamsLeft - (endIndex - startIndex); - startIndex = endIndex; - } - } - } - - return result; - - - } - - public static void storeIntermediateKeySetResults (EntityManager em, String txId, List keysIn) { - - for (Object key : keysIn) { - TempKey tempKey = new TempKey(); - tempKey.setPk(txId,key.toString()); - em.persist(tempKey); - } - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; +import java.util.ArrayList; +import java.util.Collections; + +import javax.persistence.EntityManager; +import javax.persistence.Query; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.uddi.api_v3.ListDescription; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.Property; +import org.apache.juddi.model.TempKey; +import org.apache.juddi.query.util.DynamicQuery; + +/** + * @author Jeff Faath + */ +public abstract class EntityQuery { + private static Log log = LogFactory.getLog(EntityQuery.class); + + public static final String KEY_NAME = "entityKey"; + public static final String TEMP_ENTITY_NAME = "TempKey"; + public static final String TEMP_ENTITY_ALIAS = "tk"; + public static final String TEMP_ENTITY_PK_TXID_NAME = TEMP_ENTITY_ALIAS + ".pk.txId"; + public static final String TEMP_ENTITY_PK_KEY_NAME = TEMP_ENTITY_ALIAS + ".pk.entityKey"; + public static final String SIGNATURE_FIELD = "signatures"; + + public static final int DEFAULT_MAXROWS = 1000; + public static final int DEFAULT_MAXINCLAUSE = 1000; + + // TODO: make this alias creator a little more unique + public static String buildAlias(String entityName) { + if (entityName == null || entityName.length() == 0) + return "x"; + + return entityName.substring(0, entityName.length() - 3) + "_"; + } + + /* + * Used to retrieve the final results of find operations. Handles paging as specified by user. + * + * TODO: This query will use an IN clause, however, it is not restricted per the global parameter. This is so the query can + * take advantage of sorting through SQL. The fix would be to apply the parameter, but only if the IN list is greater than the + * parameter. In this case, sorting would have to be done in java. + * + */ + public static List getPagedResult(EntityManager em, DynamicQuery dynamicQry, Integer maxRowsUser, Integer listHead, ListDescription listDesc) { + + int maxRows = DEFAULT_MAXROWS; + try { + maxRows = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_ROWS, DEFAULT_MAXROWS); + } + catch(ConfigurationException ce) { + log.error("Configuration exception occurred retrieving: " + Property.JUDDI_MAX_ROWS); + } + + if (maxRowsUser != null && maxRowsUser > 0) { + if (maxRowsUser < maxRows) + maxRows = maxRowsUser; + } + + if (listHead == null || listHead <= 0) + listHead = 1; + + + Query qry = dynamicQry.buildJPAQuery(em); + List result = new ArrayList(); + //Filter out non-unique results + for (Object object : qry.getResultList()) { + if (!result.contains(object)) { + result.add(object); + } + } + + int resultSize = result.size(); + + if (listDesc != null) { + listDesc.setActualCount(resultSize); + listDesc.setListHead(listHead); + } + + int startIndex = listHead - 1; + if (startIndex >= resultSize) { + if (listDesc != null) + listDesc.setIncludeCount(0); + + return Collections.emptyList(); + } + else { + int endIndex = Math.min(startIndex + maxRows, resultSize); + if (listDesc != null) + listDesc.setIncludeCount(endIndex - startIndex); + + List subList = new ArrayList(endIndex); + for (int i=startIndex; i< endIndex; i++) { + subList.add(result.get(i)); + } + return subList; + } + } + + /* + * Used for all the find operation sub-queries. Restricts size of the IN clause based on global parameter + */ + @SuppressWarnings("unchecked") + public static List getQueryResult(EntityManager em, DynamicQuery dynamicQry, List keysIn, String inListTerm) { + + List result = new ArrayList(0); + // If keysIn is null, then no IN list is applied to the query - we simply need to run the query. Otherwise, the IN list is chunked based on + // the application property. + if (keysIn == null) { + if (log.isDebugEnabled()) log.debug(dynamicQry); + Query qry = dynamicQry.buildJPAQuery(em); + result = qry.getResultList(); + } + else { + int maxInClause = DEFAULT_MAXINCLAUSE; + try { + maxInClause = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_IN_CLAUSE, DEFAULT_MAXINCLAUSE); + } + catch(ConfigurationException ce) { + log.error("Configuration exception occurred retrieving: " + Property.JUDDI_MAX_IN_CLAUSE); + } + if (keysIn.isEmpty()) { + Query qry = dynamicQry.buildJPAQuery(em); + List resultChunk = qry.getResultList(); + result.addAll(resultChunk); + } else { + int inParamsLeft = keysIn.size(); + int startIndex = 0; + while(inParamsLeft > 0) { + int endIndex = startIndex + Math.min(inParamsLeft, maxInClause); + + List subKeysIn = new ArrayList(endIndex); + for (int i=startIndex; i< endIndex; i++) { + subKeysIn.add(keysIn.get(i)); + } + dynamicQry.appendInListWithAnd(inListTerm, subKeysIn); + log.debug(dynamicQry); + + Query qry = dynamicQry.buildJPAQuery(em); + List resultChunk = qry.getResultList(); + result.addAll(resultChunk); + + inParamsLeft = inParamsLeft - (endIndex - startIndex); + startIndex = endIndex; + } + } + } + + return result; + + + } + + public static void storeIntermediateKeySetResults (EntityManager em, String txId, List keysIn) { + + for (Object key : keysIn) { + TempKey tempKey = new TempKey(); + tempKey.setPk(txId,key.toString()); + em.persist(tempKey); + } + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FetchBindingTemplatesQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FetchBindingTemplatesQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FetchBindingTemplatesQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FetchBindingTemplatesQuery.java index aeb41db2d..f3fba255f 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FetchBindingTemplatesQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FetchBindingTemplatesQuery.java @@ -1,125 +1,125 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.Collections; -import java.util.List; -import java.util.UUID; - -import javax.persistence.EntityManager; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.Property; -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.api_v3.ListDescription; - -/** - * The "select" method retrieves all the entities for the input key list and sorts according to the user settings. Paging is taken into account when retrieving - * the results. The result is a list of the entity objects containing all top level elements (restricted to the given page). - * - * NOTE: Results usually need multiple one-to-many collections to be fetched. Although this could be done in one query with eager fetching, this strategy is not - * recommended as it will lead to a potentially large Cartesian product. Therefore, the collections are initialized in separate queries during the mapping - * stage. If the returned results are small (maxRows parameters is set appropriately), a single query is likely faster, but probably not by enough to consider - * the optimization under these conditions. - * - * @author Jeff Faath - */ -public class FetchBindingTemplatesQuery extends BindingTemplateQuery { - - private static final Log log = LogFactory.getLog(FetchBindingTemplatesQuery.class); - - protected static final String selectSQL; - - static { - StringBuilder sql = new StringBuilder(200); - sql.append("select " + ENTITY_ALIAS + " from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); - selectSQL = sql.toString(); - } - - public static List select(EntityManager em, FindQualifiers fq, List keysIn, Integer maxRowsUser, Integer listHead, ListDescription listDesc, DynamicQuery.Parameter... restrictions) throws DispositionReportFaultMessage { - - // If keysIn is null or empty, then nothing to fetch. - if ((keysIn == null) || (keysIn.size() == 0)) - return Collections.emptyList(); - int maxRows = DEFAULT_MAXROWS; - try { - maxRows = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_ROWS, DEFAULT_MAXROWS); - } - catch(ConfigurationException ce) { - log.error("Configuration exception occurred retrieving: " + Property.JUDDI_MAX_ROWS); - } - DynamicQuery dynamicQry = new DynamicQuery(selectSQL); - if (keysIn.size() > maxRows) { - UUID uuid = UUID.randomUUID(); - storeIntermediateKeySetResults(em, uuid.toString(), keysIn); - appendTempTable(dynamicQry); - appendSortTables(dynamicQry); - appendTempJoin(dynamicQry, uuid.toString()); - } - else { - appendSortTables(dynamicQry); - dynamicQry.appendInListWithAnd(ENTITY_ALIAS + "." + KEY_NAME, keysIn); - } - if (restrictions != null && restrictions.length > 0) - dynamicQry.AND().pad().appendGroupedAnd(restrictions); - - appendSortCriteria(dynamicQry, fq); - - log.debug(dynamicQry); - - return getPagedResult(em, dynamicQry, maxRowsUser, listHead, listDesc); - } - - private static void appendTempTable(DynamicQuery qry) { - qry.comma().append(TEMP_ENTITY_NAME + " " + TEMP_ENTITY_ALIAS ); - } - - private static void appendTempJoin(DynamicQuery qry, String uuid) { - qry.pad().AND().pad().append(TEMP_ENTITY_PK_KEY_NAME).append(DynamicQuery.PREDICATE_EQUALS); - qry.pad().append(ENTITY_ALIAS + "." + KEY_NAME); - qry.pad().AND().pad().append(TEMP_ENTITY_PK_TXID_NAME).append(DynamicQuery.PREDICATE_EQUALS); - qry.append("'" + uuid + "'").pad(); - } - - private static void appendSortTables(DynamicQuery qry) { - // BindingTemplates can only be sorted by date. - qry.WHERE().pad().append("1=1").pad(); - } - - /* - * BindingTemplates can only be sorted by date. - */ - private static void appendSortCriteria(DynamicQuery qry, FindQualifiers fq) { - - qry.ORDERBY().pad(); - - if (fq.isSortByDateAsc()) - qry.append(ENTITY_ALIAS + ".modified").pad().append(DynamicQuery.SORT_ASC); - else - qry.append(ENTITY_ALIAS + ".modified").pad().append(DynamicQuery.SORT_DESC); - - qry.pad(); - - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.Collections; +import java.util.List; +import java.util.UUID; + +import javax.persistence.EntityManager; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.Property; +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.api_v3.ListDescription; + +/** + * The "select" method retrieves all the entities for the input key list and sorts according to the user settings. Paging is taken into account when retrieving + * the results. The result is a list of the entity objects containing all top level elements (restricted to the given page). + * + * NOTE: Results usually need multiple one-to-many collections to be fetched. Although this could be done in one query with eager fetching, this strategy is not + * recommended as it will lead to a potentially large Cartesian product. Therefore, the collections are initialized in separate queries during the mapping + * stage. If the returned results are small (maxRows parameters is set appropriately), a single query is likely faster, but probably not by enough to consider + * the optimization under these conditions. + * + * @author Jeff Faath + */ +public class FetchBindingTemplatesQuery extends BindingTemplateQuery { + + private static final Log log = LogFactory.getLog(FetchBindingTemplatesQuery.class); + + protected static final String selectSQL; + + static { + StringBuilder sql = new StringBuilder(200); + sql.append("select " + ENTITY_ALIAS + " from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); + selectSQL = sql.toString(); + } + + public static List select(EntityManager em, FindQualifiers fq, List keysIn, Integer maxRowsUser, Integer listHead, ListDescription listDesc, DynamicQuery.Parameter... restrictions) throws DispositionReportFaultMessage { + + // If keysIn is null or empty, then nothing to fetch. + if ((keysIn == null) || (keysIn.size() == 0)) + return Collections.emptyList(); + int maxRows = DEFAULT_MAXROWS; + try { + maxRows = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_ROWS, DEFAULT_MAXROWS); + } + catch(ConfigurationException ce) { + log.error("Configuration exception occurred retrieving: " + Property.JUDDI_MAX_ROWS); + } + DynamicQuery dynamicQry = new DynamicQuery(selectSQL); + if (keysIn.size() > maxRows) { + UUID uuid = UUID.randomUUID(); + storeIntermediateKeySetResults(em, uuid.toString(), keysIn); + appendTempTable(dynamicQry); + appendSortTables(dynamicQry); + appendTempJoin(dynamicQry, uuid.toString()); + } + else { + appendSortTables(dynamicQry); + dynamicQry.appendInListWithAnd(ENTITY_ALIAS + "." + KEY_NAME, keysIn); + } + if (restrictions != null && restrictions.length > 0) + dynamicQry.AND().pad().appendGroupedAnd(restrictions); + + appendSortCriteria(dynamicQry, fq); + + log.debug(dynamicQry); + + return getPagedResult(em, dynamicQry, maxRowsUser, listHead, listDesc); + } + + private static void appendTempTable(DynamicQuery qry) { + qry.comma().append(TEMP_ENTITY_NAME + " " + TEMP_ENTITY_ALIAS ); + } + + private static void appendTempJoin(DynamicQuery qry, String uuid) { + qry.pad().AND().pad().append(TEMP_ENTITY_PK_KEY_NAME).append(DynamicQuery.PREDICATE_EQUALS); + qry.pad().append(ENTITY_ALIAS + "." + KEY_NAME); + qry.pad().AND().pad().append(TEMP_ENTITY_PK_TXID_NAME).append(DynamicQuery.PREDICATE_EQUALS); + qry.append("'" + uuid + "'").pad(); + } + + private static void appendSortTables(DynamicQuery qry) { + // BindingTemplates can only be sorted by date. + qry.WHERE().pad().append("1=1").pad(); + } + + /* + * BindingTemplates can only be sorted by date. + */ + private static void appendSortCriteria(DynamicQuery qry, FindQualifiers fq) { + + qry.ORDERBY().pad(); + + if (fq.isSortByDateAsc()) + qry.append(ENTITY_ALIAS + ".modified").pad().append(DynamicQuery.SORT_ASC); + else + qry.append(ENTITY_ALIAS + ".modified").pad().append(DynamicQuery.SORT_DESC); + + qry.pad(); + + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FetchBusinessEntitiesQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FetchBusinessEntitiesQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FetchBusinessEntitiesQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FetchBusinessEntitiesQuery.java index 7f2ffee29..340e7ac4a 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FetchBusinessEntitiesQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FetchBusinessEntitiesQuery.java @@ -1,150 +1,150 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.Collections; -import java.util.List; -import java.util.UUID; - -import javax.persistence.EntityManager; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.Property; -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.api_v3.ListDescription; - -/** - * The "select" method retrieves all the entities for the input key list and sorts according to the user settings. Paging is taken into account when retrieving - * the results. The result is a list of the entity objects containing all top level elements (restricted to the given page). - * - * NOTE: Results usually need multiple one-to-many collections to be fetched. Although this could be done in one query with eager fetching, this strategy is not - * recommended as it will lead to a potentially large Cartesian product. Therefore, the collections are initialized in separate queries during the mapping - * stage. If the returned results are small (maxRows parameters is set appropriately), a single query is likely faster, but probably not by enough to consider - * the optimization under these conditions. - * - * @author Jeff Faath - */ -public class FetchBusinessEntitiesQuery extends BusinessEntityQuery { - - private static final Log log = LogFactory.getLog(FetchBusinessEntitiesQuery.class); - - protected static final String selectSQL; - - static { - StringBuilder sql = new StringBuilder(200); - sql.append("select " + ENTITY_ALIAS + " from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); - selectSQL = sql.toString(); - } - - public static List select(EntityManager em, FindQualifiers fq, List keysIn, Integer maxRowsUser, Integer listHead, ListDescription listDesc, DynamicQuery.Parameter... restrictions) throws DispositionReportFaultMessage { - - // If keysIn is null or empty, then nothing to fetch. - if ((keysIn == null) || (keysIn.size() == 0)) - return Collections.emptyList(); - - int maxRows = DEFAULT_MAXROWS; - try { - maxRows = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_ROWS, DEFAULT_MAXROWS); - } - catch(ConfigurationException ce) { - log.error("Configuration exception occurred retrieving: " + Property.JUDDI_MAX_ROWS); - } - DynamicQuery dynamicQry = new DynamicQuery(selectSQL); - if (keysIn.size() > maxRows) { - UUID uuid = UUID.randomUUID(); - storeIntermediateKeySetResults(em, uuid.toString(), keysIn); - appendTempTable(dynamicQry); - appendSortTables(dynamicQry); - appendTempJoin(dynamicQry, uuid.toString()); - } - else { - appendSortTables(dynamicQry); - dynamicQry.appendInListWithAnd(ENTITY_ALIAS + "." + KEY_NAME, keysIn); - } - if (restrictions != null && restrictions.length > 0) - dynamicQry.AND().pad().appendGroupedAnd(restrictions); - - appendSortCriteria(dynamicQry, fq); - - log.debug(dynamicQry); - return getPagedResult(em, dynamicQry, maxRowsUser, listHead, listDesc); - } - - private static void appendTempTable(DynamicQuery qry) { - qry.comma().append(TEMP_ENTITY_NAME + " " + TEMP_ENTITY_ALIAS ); - } - - private static void appendTempJoin(DynamicQuery qry, String uuid) { - qry.pad().AND().pad().append(TEMP_ENTITY_PK_KEY_NAME).append(DynamicQuery.PREDICATE_EQUALS); - qry.pad().append(ENTITY_ALIAS + "." + KEY_NAME); - qry.pad().AND().pad().append(TEMP_ENTITY_PK_TXID_NAME).append(DynamicQuery.PREDICATE_EQUALS); - qry.append("'" + uuid + "'").pad(); - } - - private static void appendSortTables(DynamicQuery qry) { - qry.pad().comma().pad().append(FindBusinessByNameQuery.ENTITY_NAME_CHILD).pad().append(buildAlias(FindBusinessByNameQuery.ENTITY_NAME_CHILD)).pad(); - qry.WHERE().pad().append(ENTITY_ALIAS + "." + KEY_NAME).pad(); - qry.append(DynamicQuery.PREDICATE_EQUALS).pad(); - qry.append(buildAlias(FindBusinessByNameQuery.ENTITY_NAME_CHILD) + "." + ENTITY_FIELD + "." + KEY_NAME).pad(); - } - - /* - * Default ordering is name ascending and date descending. If a name item is set, then it will always go first. If only a date item is set, then date will - * go first, and the name sort will occur second in ascending order. - */ - private static void appendSortCriteria(DynamicQuery qry, FindQualifiers fq) { - - String nameTerm = buildAlias(FindBusinessByNameQuery.ENTITY_NAME_CHILD) + ".name"; - - if (fq.isCaseInsensitiveSort()) { - // See JUDDI-785 - log.info("jUDDI does not support caseInsensitive sort, as JPA does not support sortBy " - + "with UPPER or LOWER, see https://issues.apache.org/jira/browse/OPENJPA-1817. " - + "A work around is to do a caseInsentive Match."); - //nameTerm = "upper(" + nameTerm + ")"; - } - - String dateTerm = ENTITY_ALIAS + ".modified"; - - String orderClause = nameTerm + " " + DynamicQuery.SORT_ASC + ", " + dateTerm + " " + DynamicQuery.SORT_DESC; - if (fq.isSortByNameAsc()) { - if (fq.isSortByDateAsc()) - orderClause = nameTerm + " " + DynamicQuery.SORT_ASC + ", " + dateTerm + " " + DynamicQuery.SORT_ASC; - } - else if (fq.isSortByNameDesc()) { - if (fq.isSortByDateAsc()) - orderClause = nameTerm + " " + DynamicQuery.SORT_DESC + ", " + dateTerm + " " + DynamicQuery.SORT_ASC; - else - orderClause = nameTerm + " " + DynamicQuery.SORT_DESC + ", " + dateTerm + " " + DynamicQuery.SORT_DESC; - } - else if (fq.isSortByDateAsc()) - orderClause = dateTerm + " " + DynamicQuery.SORT_ASC + ", " + nameTerm + " " + DynamicQuery.SORT_ASC; - else if (fq.isSortByDateDesc()) - orderClause = dateTerm + " " + DynamicQuery.SORT_DESC + ", " + nameTerm + " " + DynamicQuery.SORT_ASC; - - qry.ORDERBY().pad(); - qry.append(orderClause); - qry.pad(); - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.Collections; +import java.util.List; +import java.util.UUID; + +import javax.persistence.EntityManager; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.Property; +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.api_v3.ListDescription; + +/** + * The "select" method retrieves all the entities for the input key list and sorts according to the user settings. Paging is taken into account when retrieving + * the results. The result is a list of the entity objects containing all top level elements (restricted to the given page). + * + * NOTE: Results usually need multiple one-to-many collections to be fetched. Although this could be done in one query with eager fetching, this strategy is not + * recommended as it will lead to a potentially large Cartesian product. Therefore, the collections are initialized in separate queries during the mapping + * stage. If the returned results are small (maxRows parameters is set appropriately), a single query is likely faster, but probably not by enough to consider + * the optimization under these conditions. + * + * @author Jeff Faath + */ +public class FetchBusinessEntitiesQuery extends BusinessEntityQuery { + + private static final Log log = LogFactory.getLog(FetchBusinessEntitiesQuery.class); + + protected static final String selectSQL; + + static { + StringBuilder sql = new StringBuilder(200); + sql.append("select " + ENTITY_ALIAS + " from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); + selectSQL = sql.toString(); + } + + public static List select(EntityManager em, FindQualifiers fq, List keysIn, Integer maxRowsUser, Integer listHead, ListDescription listDesc, DynamicQuery.Parameter... restrictions) throws DispositionReportFaultMessage { + + // If keysIn is null or empty, then nothing to fetch. + if ((keysIn == null) || (keysIn.size() == 0)) + return Collections.emptyList(); + + int maxRows = DEFAULT_MAXROWS; + try { + maxRows = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_ROWS, DEFAULT_MAXROWS); + } + catch(ConfigurationException ce) { + log.error("Configuration exception occurred retrieving: " + Property.JUDDI_MAX_ROWS); + } + DynamicQuery dynamicQry = new DynamicQuery(selectSQL); + if (keysIn.size() > maxRows) { + UUID uuid = UUID.randomUUID(); + storeIntermediateKeySetResults(em, uuid.toString(), keysIn); + appendTempTable(dynamicQry); + appendSortTables(dynamicQry); + appendTempJoin(dynamicQry, uuid.toString()); + } + else { + appendSortTables(dynamicQry); + dynamicQry.appendInListWithAnd(ENTITY_ALIAS + "." + KEY_NAME, keysIn); + } + if (restrictions != null && restrictions.length > 0) + dynamicQry.AND().pad().appendGroupedAnd(restrictions); + + appendSortCriteria(dynamicQry, fq); + + log.debug(dynamicQry); + return getPagedResult(em, dynamicQry, maxRowsUser, listHead, listDesc); + } + + private static void appendTempTable(DynamicQuery qry) { + qry.comma().append(TEMP_ENTITY_NAME + " " + TEMP_ENTITY_ALIAS ); + } + + private static void appendTempJoin(DynamicQuery qry, String uuid) { + qry.pad().AND().pad().append(TEMP_ENTITY_PK_KEY_NAME).append(DynamicQuery.PREDICATE_EQUALS); + qry.pad().append(ENTITY_ALIAS + "." + KEY_NAME); + qry.pad().AND().pad().append(TEMP_ENTITY_PK_TXID_NAME).append(DynamicQuery.PREDICATE_EQUALS); + qry.append("'" + uuid + "'").pad(); + } + + private static void appendSortTables(DynamicQuery qry) { + qry.pad().comma().pad().append(FindBusinessByNameQuery.ENTITY_NAME_CHILD).pad().append(buildAlias(FindBusinessByNameQuery.ENTITY_NAME_CHILD)).pad(); + qry.WHERE().pad().append(ENTITY_ALIAS + "." + KEY_NAME).pad(); + qry.append(DynamicQuery.PREDICATE_EQUALS).pad(); + qry.append(buildAlias(FindBusinessByNameQuery.ENTITY_NAME_CHILD) + "." + ENTITY_FIELD + "." + KEY_NAME).pad(); + } + + /* + * Default ordering is name ascending and date descending. If a name item is set, then it will always go first. If only a date item is set, then date will + * go first, and the name sort will occur second in ascending order. + */ + private static void appendSortCriteria(DynamicQuery qry, FindQualifiers fq) { + + String nameTerm = buildAlias(FindBusinessByNameQuery.ENTITY_NAME_CHILD) + ".name"; + + if (fq.isCaseInsensitiveSort()) { + // See JUDDI-785 + log.info("jUDDI does not support caseInsensitive sort, as JPA does not support sortBy " + + "with UPPER or LOWER, see https://issues.apache.org/jira/browse/OPENJPA-1817. " + + "A work around is to do a caseInsentive Match."); + //nameTerm = "upper(" + nameTerm + ")"; + } + + String dateTerm = ENTITY_ALIAS + ".modified"; + + String orderClause = nameTerm + " " + DynamicQuery.SORT_ASC + ", " + dateTerm + " " + DynamicQuery.SORT_DESC; + if (fq.isSortByNameAsc()) { + if (fq.isSortByDateAsc()) + orderClause = nameTerm + " " + DynamicQuery.SORT_ASC + ", " + dateTerm + " " + DynamicQuery.SORT_ASC; + } + else if (fq.isSortByNameDesc()) { + if (fq.isSortByDateAsc()) + orderClause = nameTerm + " " + DynamicQuery.SORT_DESC + ", " + dateTerm + " " + DynamicQuery.SORT_ASC; + else + orderClause = nameTerm + " " + DynamicQuery.SORT_DESC + ", " + dateTerm + " " + DynamicQuery.SORT_DESC; + } + else if (fq.isSortByDateAsc()) + orderClause = dateTerm + " " + DynamicQuery.SORT_ASC + ", " + nameTerm + " " + DynamicQuery.SORT_ASC; + else if (fq.isSortByDateDesc()) + orderClause = dateTerm + " " + DynamicQuery.SORT_DESC + ", " + nameTerm + " " + DynamicQuery.SORT_ASC; + + qry.ORDERBY().pad(); + qry.append(orderClause); + qry.pad(); + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FetchBusinessServicesQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FetchBusinessServicesQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FetchBusinessServicesQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FetchBusinessServicesQuery.java index f9ec7b89b..235f1bb1a 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FetchBusinessServicesQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FetchBusinessServicesQuery.java @@ -1,148 +1,148 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.Collections; -import java.util.List; -import java.util.UUID; - -import javax.persistence.EntityManager; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.Property; -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.api_v3.ListDescription; - -/** - * The "select" method retrieves all the entities for the input key list and sorts according to the user settings. Paging is taken into account when retrieving - * the results. The result is a list of the entity objects containing all top level elements (restricted to the given page). - * - * NOTE: Results usually need multiple one-to-many collections to be fetched. Although this could be done in one query with eager fetching, this strategy is not - * recommended as it will lead to a potentially large Cartesian product. Therefore, the collections are initialized in separate queries during the mapping - * stage. If the returned results are small (maxRows parameters is set appropriately), a single query is likely faster, but probably not by enough to consider - * the optimization under these conditions. - * - * @author Jeff Faath - */ -public class FetchBusinessServicesQuery extends BusinessServiceQuery { - - private static final Log log = LogFactory.getLog(FetchBusinessServicesQuery.class); - - protected static final String selectSQL; - - static { - StringBuilder sql = new StringBuilder(200); - sql.append("select " + ENTITY_ALIAS + " from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); - selectSQL = sql.toString(); - } - - public static List select(EntityManager em, FindQualifiers fq, List keysIn, Integer maxRowsUser, Integer listHead, ListDescription listDesc, DynamicQuery.Parameter... restrictions) throws DispositionReportFaultMessage { - - // If keysIn is null or empty, then nothing to fetch. - if ((keysIn == null) || (keysIn.size() == 0)) - return Collections.emptyList(); - - int maxRows = DEFAULT_MAXROWS; - try { - maxRows = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_ROWS, DEFAULT_MAXROWS); - } - catch(ConfigurationException ce) { - log.error("Configuration exception occurred retrieving: " + Property.JUDDI_MAX_ROWS); - } - DynamicQuery dynamicQry = new DynamicQuery(selectSQL); - if (keysIn.size() > maxRows) { - UUID uuid = UUID.randomUUID(); - storeIntermediateKeySetResults(em, uuid.toString(), keysIn); - appendTempTable(dynamicQry); - appendSortTables(dynamicQry); - appendTempJoin(dynamicQry, uuid.toString()); - } - else { - appendSortTables(dynamicQry); - dynamicQry.appendInListWithAnd(ENTITY_ALIAS + "." + KEY_NAME, keysIn); - } - if (restrictions != null && restrictions.length > 0) - dynamicQry.AND().pad().appendGroupedAnd(restrictions); - - appendSortCriteria(dynamicQry, fq); - - log.debug(dynamicQry); - return getPagedResult(em, dynamicQry, maxRowsUser, listHead, listDesc); - } - - private static void appendTempTable(DynamicQuery qry) { - qry.comma().append(TEMP_ENTITY_NAME + " " + TEMP_ENTITY_ALIAS ); - } - - private static void appendTempJoin(DynamicQuery qry, String uuid) { - qry.pad().AND().pad().append(TEMP_ENTITY_PK_KEY_NAME).append(DynamicQuery.PREDICATE_EQUALS); - qry.append(ENTITY_ALIAS + "." + KEY_NAME); - qry.pad().AND().pad().append(TEMP_ENTITY_PK_TXID_NAME).append(DynamicQuery.PREDICATE_EQUALS); - qry.append("'" + uuid + "'").pad(); - } - - private static void appendSortTables(DynamicQuery qry) { - qry.pad().comma().pad().append(FindServiceByNameQuery.ENTITY_NAME_CHILD).pad().append(buildAlias(FindServiceByNameQuery.ENTITY_NAME_CHILD)).pad(); - qry.WHERE().pad().append(ENTITY_ALIAS + "." + KEY_NAME).pad(); - qry.append(DynamicQuery.PREDICATE_EQUALS).pad(); - qry.append(buildAlias(FindServiceByNameQuery.ENTITY_NAME_CHILD) + "." + ENTITY_FIELD + "." + KEY_NAME).pad(); - } - - /* - * Default ordering is name ascending and date descending. If a name item is set, then it will always go first. If only a date item is set, then date will - * go first, and the name sort will occur second in ascending order. - */ - private static void appendSortCriteria(DynamicQuery qry, FindQualifiers fq) { - - String nameTerm = buildAlias(FindServiceByNameQuery.ENTITY_NAME_CHILD) + ".name"; - if (fq.isCaseInsensitiveSort()) { - // See JUDDI-785 - log.info("jUDDI does not support caseInsensitive sort, as JPA does not support sortBy " - + "with UPPER or LOWER, see https://issues.apache.org/jira/browse/OPENJPA-1817. " - + "A work around is to do a caseInsentive Match."); - //nameTerm = "upper(" + nameTerm + ")"; - } - String dateTerm = ENTITY_ALIAS + ".modified"; - - String orderClause = nameTerm + " " + DynamicQuery.SORT_ASC + ", " + dateTerm + " " + DynamicQuery.SORT_DESC; - if (fq.isSortByNameAsc()) { - if (fq.isSortByDateAsc()) - orderClause = nameTerm + " " + DynamicQuery.SORT_ASC + ", " + dateTerm + " " + DynamicQuery.SORT_ASC; - } - else if (fq.isSortByNameDesc()) { - if (fq.isSortByDateAsc()) - orderClause = nameTerm + " " + DynamicQuery.SORT_DESC + ", " + dateTerm + " " + DynamicQuery.SORT_ASC; - else - orderClause = nameTerm + " " + DynamicQuery.SORT_DESC + ", " + dateTerm + " " + DynamicQuery.SORT_DESC; - } - else if (fq.isSortByDateAsc()) - orderClause = dateTerm + " " + DynamicQuery.SORT_ASC + ", " + nameTerm + " " + DynamicQuery.SORT_ASC; - else if (fq.isSortByDateDesc()) - orderClause = dateTerm + " " + DynamicQuery.SORT_DESC + ", " + nameTerm + " " + DynamicQuery.SORT_ASC; - - qry.ORDERBY().pad(); - qry.append(orderClause); - qry.pad(); - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.Collections; +import java.util.List; +import java.util.UUID; + +import javax.persistence.EntityManager; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.Property; +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.api_v3.ListDescription; + +/** + * The "select" method retrieves all the entities for the input key list and sorts according to the user settings. Paging is taken into account when retrieving + * the results. The result is a list of the entity objects containing all top level elements (restricted to the given page). + * + * NOTE: Results usually need multiple one-to-many collections to be fetched. Although this could be done in one query with eager fetching, this strategy is not + * recommended as it will lead to a potentially large Cartesian product. Therefore, the collections are initialized in separate queries during the mapping + * stage. If the returned results are small (maxRows parameters is set appropriately), a single query is likely faster, but probably not by enough to consider + * the optimization under these conditions. + * + * @author Jeff Faath + */ +public class FetchBusinessServicesQuery extends BusinessServiceQuery { + + private static final Log log = LogFactory.getLog(FetchBusinessServicesQuery.class); + + protected static final String selectSQL; + + static { + StringBuilder sql = new StringBuilder(200); + sql.append("select " + ENTITY_ALIAS + " from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); + selectSQL = sql.toString(); + } + + public static List select(EntityManager em, FindQualifiers fq, List keysIn, Integer maxRowsUser, Integer listHead, ListDescription listDesc, DynamicQuery.Parameter... restrictions) throws DispositionReportFaultMessage { + + // If keysIn is null or empty, then nothing to fetch. + if ((keysIn == null) || (keysIn.size() == 0)) + return Collections.emptyList(); + + int maxRows = DEFAULT_MAXROWS; + try { + maxRows = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_ROWS, DEFAULT_MAXROWS); + } + catch(ConfigurationException ce) { + log.error("Configuration exception occurred retrieving: " + Property.JUDDI_MAX_ROWS); + } + DynamicQuery dynamicQry = new DynamicQuery(selectSQL); + if (keysIn.size() > maxRows) { + UUID uuid = UUID.randomUUID(); + storeIntermediateKeySetResults(em, uuid.toString(), keysIn); + appendTempTable(dynamicQry); + appendSortTables(dynamicQry); + appendTempJoin(dynamicQry, uuid.toString()); + } + else { + appendSortTables(dynamicQry); + dynamicQry.appendInListWithAnd(ENTITY_ALIAS + "." + KEY_NAME, keysIn); + } + if (restrictions != null && restrictions.length > 0) + dynamicQry.AND().pad().appendGroupedAnd(restrictions); + + appendSortCriteria(dynamicQry, fq); + + log.debug(dynamicQry); + return getPagedResult(em, dynamicQry, maxRowsUser, listHead, listDesc); + } + + private static void appendTempTable(DynamicQuery qry) { + qry.comma().append(TEMP_ENTITY_NAME + " " + TEMP_ENTITY_ALIAS ); + } + + private static void appendTempJoin(DynamicQuery qry, String uuid) { + qry.pad().AND().pad().append(TEMP_ENTITY_PK_KEY_NAME).append(DynamicQuery.PREDICATE_EQUALS); + qry.append(ENTITY_ALIAS + "." + KEY_NAME); + qry.pad().AND().pad().append(TEMP_ENTITY_PK_TXID_NAME).append(DynamicQuery.PREDICATE_EQUALS); + qry.append("'" + uuid + "'").pad(); + } + + private static void appendSortTables(DynamicQuery qry) { + qry.pad().comma().pad().append(FindServiceByNameQuery.ENTITY_NAME_CHILD).pad().append(buildAlias(FindServiceByNameQuery.ENTITY_NAME_CHILD)).pad(); + qry.WHERE().pad().append(ENTITY_ALIAS + "." + KEY_NAME).pad(); + qry.append(DynamicQuery.PREDICATE_EQUALS).pad(); + qry.append(buildAlias(FindServiceByNameQuery.ENTITY_NAME_CHILD) + "." + ENTITY_FIELD + "." + KEY_NAME).pad(); + } + + /* + * Default ordering is name ascending and date descending. If a name item is set, then it will always go first. If only a date item is set, then date will + * go first, and the name sort will occur second in ascending order. + */ + private static void appendSortCriteria(DynamicQuery qry, FindQualifiers fq) { + + String nameTerm = buildAlias(FindServiceByNameQuery.ENTITY_NAME_CHILD) + ".name"; + if (fq.isCaseInsensitiveSort()) { + // See JUDDI-785 + log.info("jUDDI does not support caseInsensitive sort, as JPA does not support sortBy " + + "with UPPER or LOWER, see https://issues.apache.org/jira/browse/OPENJPA-1817. " + + "A work around is to do a caseInsentive Match."); + //nameTerm = "upper(" + nameTerm + ")"; + } + String dateTerm = ENTITY_ALIAS + ".modified"; + + String orderClause = nameTerm + " " + DynamicQuery.SORT_ASC + ", " + dateTerm + " " + DynamicQuery.SORT_DESC; + if (fq.isSortByNameAsc()) { + if (fq.isSortByDateAsc()) + orderClause = nameTerm + " " + DynamicQuery.SORT_ASC + ", " + dateTerm + " " + DynamicQuery.SORT_ASC; + } + else if (fq.isSortByNameDesc()) { + if (fq.isSortByDateAsc()) + orderClause = nameTerm + " " + DynamicQuery.SORT_DESC + ", " + dateTerm + " " + DynamicQuery.SORT_ASC; + else + orderClause = nameTerm + " " + DynamicQuery.SORT_DESC + ", " + dateTerm + " " + DynamicQuery.SORT_DESC; + } + else if (fq.isSortByDateAsc()) + orderClause = dateTerm + " " + DynamicQuery.SORT_ASC + ", " + nameTerm + " " + DynamicQuery.SORT_ASC; + else if (fq.isSortByDateDesc()) + orderClause = dateTerm + " " + DynamicQuery.SORT_DESC + ", " + nameTerm + " " + DynamicQuery.SORT_ASC; + + qry.ORDERBY().pad(); + qry.append(orderClause); + qry.pad(); + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FetchTModelsQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FetchTModelsQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FetchTModelsQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FetchTModelsQuery.java index d0460145c..ca9a17db4 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FetchTModelsQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FetchTModelsQuery.java @@ -1,146 +1,146 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.Collections; -import java.util.List; -import java.util.UUID; - -import javax.persistence.EntityManager; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.Property; -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.api_v3.ListDescription; - -/** - * The "select" method retrieves all the entities for the input key list and sorts according to the user settings. Paging is taken into account when retrieving - * the results. The result is a list of the entity objects containing all top level elements (restricted to the given page). - * - * NOTE: Results usually need multiple one-to-many collections to be fetched. Although this could be done in one query with eager fetching, this strategy is not - * recommended as it will lead to a potentially large Cartesian product. Therefore, the collections are initialized in separate queries during the mapping - * stage. If the returned results are small (maxRows parameters is set appropriately), a single query is likely faster, but probably not by enough to consider - * the optimization under these conditions. - * - * @author Jeff Faath - */ -public class FetchTModelsQuery extends TModelQuery { - - private static final Log log = LogFactory.getLog(FetchTModelsQuery.class); - - protected static final String selectSQL; - - static { - StringBuilder sql = new StringBuilder(200); - sql.append("select " + ENTITY_ALIAS + " from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); - selectSQL = sql.toString(); - } - - public static List select(EntityManager em, FindQualifiers fq, List keysIn, Integer maxRowsUser, Integer listHead, ListDescription listDesc, DynamicQuery.Parameter... restrictions) throws DispositionReportFaultMessage { - - // If keysIn is null or empty, then nothing to fetch. - if ((keysIn == null) || (keysIn.size() == 0)) - return Collections.emptyList(); - int maxRows = DEFAULT_MAXROWS; - try { - maxRows = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_ROWS, DEFAULT_MAXROWS); - } - catch(ConfigurationException ce) { - log.error("Configuration exception occurred retrieving: " + Property.JUDDI_MAX_ROWS); - } - DynamicQuery dynamicQry = new DynamicQuery(selectSQL); - if (keysIn.size() > maxRows) { - UUID uuid = UUID.randomUUID(); - storeIntermediateKeySetResults(em, uuid.toString(), keysIn); - appendTempTable(dynamicQry); - appendSortTables(dynamicQry); - appendTempJoin(dynamicQry, uuid.toString()); - } - else { - appendSortTables(dynamicQry); - dynamicQry.appendInListWithAnd(ENTITY_ALIAS + "." + KEY_NAME, keysIn); - } - if (restrictions != null && restrictions.length > 0) - dynamicQry.AND().pad().appendGroupedAnd(restrictions); - - appendSortCriteria(dynamicQry, fq); - - log.debug(dynamicQry); - - return getPagedResult(em, dynamicQry, maxRowsUser, listHead, listDesc); - } - - private static void appendTempTable(DynamicQuery qry) { - qry.comma().append(TEMP_ENTITY_NAME + " " + TEMP_ENTITY_ALIAS ); - } - - private static void appendTempJoin(DynamicQuery qry, String uuid) { - qry.pad().AND().pad().append(TEMP_ENTITY_PK_KEY_NAME).append(DynamicQuery.PREDICATE_EQUALS); - qry.append(ENTITY_ALIAS + "." + KEY_NAME); - qry.pad().AND().pad().append(TEMP_ENTITY_PK_TXID_NAME).append(DynamicQuery.PREDICATE_EQUALS); - qry.append("'" + uuid + "'").pad(); - } - - private static void appendSortTables(DynamicQuery qry) { - // TModels don't need the join table, the single name is in the main table. - qry.WHERE().pad().append("1=1").pad(); - } - - /* - * Default ordering is name ascending and date descending. If a name item is set, then it will always go first. If only a date item is set, then date will - * go first, and the name sort will occur second in ascending order. - */ - private static void appendSortCriteria(DynamicQuery qry, FindQualifiers fq) { - - String nameTerm = ENTITY_ALIAS + ".name"; - if (fq.isCaseInsensitiveSort()) { - // See JUDDI-785 - log.info("jUDDI does not support caseInsensitive sort, as JPA does not support sortBy " - + "with UPPER or LOWER, see https://issues.apache.org/jira/browse/OPENJPA-1817. " - + "A work around is to do a caseInsentive Match."); - //nameTerm = "upper(" + nameTerm + ")"; - } - String dateTerm = ENTITY_ALIAS + ".modified"; - - String orderClause = nameTerm + " " + DynamicQuery.SORT_ASC + ", " + dateTerm + " " + DynamicQuery.SORT_DESC; - if (fq.isSortByNameAsc()) { - if (fq.isSortByDateAsc()) - orderClause = nameTerm + " " + DynamicQuery.SORT_ASC + ", " + dateTerm + " " + DynamicQuery.SORT_ASC; - } - else if (fq.isSortByNameDesc()) { - if (fq.isSortByDateAsc()) - orderClause = nameTerm + " " + DynamicQuery.SORT_DESC + ", " + dateTerm + " " + DynamicQuery.SORT_ASC; - else - orderClause = nameTerm + " " + DynamicQuery.SORT_DESC + ", " + dateTerm + " " + DynamicQuery.SORT_DESC; - } - else if (fq.isSortByDateAsc()) - orderClause = dateTerm + " " + DynamicQuery.SORT_ASC + ", " + nameTerm + " " + DynamicQuery.SORT_ASC; - else if (fq.isSortByDateDesc()) - orderClause = dateTerm + " " + DynamicQuery.SORT_DESC + ", " + nameTerm + " " + DynamicQuery.SORT_ASC; - - qry.ORDERBY().pad(); - qry.append(orderClause); - qry.pad(); - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.Collections; +import java.util.List; +import java.util.UUID; + +import javax.persistence.EntityManager; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.Property; +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.api_v3.ListDescription; + +/** + * The "select" method retrieves all the entities for the input key list and sorts according to the user settings. Paging is taken into account when retrieving + * the results. The result is a list of the entity objects containing all top level elements (restricted to the given page). + * + * NOTE: Results usually need multiple one-to-many collections to be fetched. Although this could be done in one query with eager fetching, this strategy is not + * recommended as it will lead to a potentially large Cartesian product. Therefore, the collections are initialized in separate queries during the mapping + * stage. If the returned results are small (maxRows parameters is set appropriately), a single query is likely faster, but probably not by enough to consider + * the optimization under these conditions. + * + * @author Jeff Faath + */ +public class FetchTModelsQuery extends TModelQuery { + + private static final Log log = LogFactory.getLog(FetchTModelsQuery.class); + + protected static final String selectSQL; + + static { + StringBuilder sql = new StringBuilder(200); + sql.append("select " + ENTITY_ALIAS + " from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); + selectSQL = sql.toString(); + } + + public static List select(EntityManager em, FindQualifiers fq, List keysIn, Integer maxRowsUser, Integer listHead, ListDescription listDesc, DynamicQuery.Parameter... restrictions) throws DispositionReportFaultMessage { + + // If keysIn is null or empty, then nothing to fetch. + if ((keysIn == null) || (keysIn.size() == 0)) + return Collections.emptyList(); + int maxRows = DEFAULT_MAXROWS; + try { + maxRows = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_ROWS, DEFAULT_MAXROWS); + } + catch(ConfigurationException ce) { + log.error("Configuration exception occurred retrieving: " + Property.JUDDI_MAX_ROWS); + } + DynamicQuery dynamicQry = new DynamicQuery(selectSQL); + if (keysIn.size() > maxRows) { + UUID uuid = UUID.randomUUID(); + storeIntermediateKeySetResults(em, uuid.toString(), keysIn); + appendTempTable(dynamicQry); + appendSortTables(dynamicQry); + appendTempJoin(dynamicQry, uuid.toString()); + } + else { + appendSortTables(dynamicQry); + dynamicQry.appendInListWithAnd(ENTITY_ALIAS + "." + KEY_NAME, keysIn); + } + if (restrictions != null && restrictions.length > 0) + dynamicQry.AND().pad().appendGroupedAnd(restrictions); + + appendSortCriteria(dynamicQry, fq); + + log.debug(dynamicQry); + + return getPagedResult(em, dynamicQry, maxRowsUser, listHead, listDesc); + } + + private static void appendTempTable(DynamicQuery qry) { + qry.comma().append(TEMP_ENTITY_NAME + " " + TEMP_ENTITY_ALIAS ); + } + + private static void appendTempJoin(DynamicQuery qry, String uuid) { + qry.pad().AND().pad().append(TEMP_ENTITY_PK_KEY_NAME).append(DynamicQuery.PREDICATE_EQUALS); + qry.append(ENTITY_ALIAS + "." + KEY_NAME); + qry.pad().AND().pad().append(TEMP_ENTITY_PK_TXID_NAME).append(DynamicQuery.PREDICATE_EQUALS); + qry.append("'" + uuid + "'").pad(); + } + + private static void appendSortTables(DynamicQuery qry) { + // TModels don't need the join table, the single name is in the main table. + qry.WHERE().pad().append("1=1").pad(); + } + + /* + * Default ordering is name ascending and date descending. If a name item is set, then it will always go first. If only a date item is set, then date will + * go first, and the name sort will occur second in ascending order. + */ + private static void appendSortCriteria(DynamicQuery qry, FindQualifiers fq) { + + String nameTerm = ENTITY_ALIAS + ".name"; + if (fq.isCaseInsensitiveSort()) { + // See JUDDI-785 + log.info("jUDDI does not support caseInsensitive sort, as JPA does not support sortBy " + + "with UPPER or LOWER, see https://issues.apache.org/jira/browse/OPENJPA-1817. " + + "A work around is to do a caseInsentive Match."); + //nameTerm = "upper(" + nameTerm + ")"; + } + String dateTerm = ENTITY_ALIAS + ".modified"; + + String orderClause = nameTerm + " " + DynamicQuery.SORT_ASC + ", " + dateTerm + " " + DynamicQuery.SORT_DESC; + if (fq.isSortByNameAsc()) { + if (fq.isSortByDateAsc()) + orderClause = nameTerm + " " + DynamicQuery.SORT_ASC + ", " + dateTerm + " " + DynamicQuery.SORT_ASC; + } + else if (fq.isSortByNameDesc()) { + if (fq.isSortByDateAsc()) + orderClause = nameTerm + " " + DynamicQuery.SORT_DESC + ", " + dateTerm + " " + DynamicQuery.SORT_ASC; + else + orderClause = nameTerm + " " + DynamicQuery.SORT_DESC + ", " + dateTerm + " " + DynamicQuery.SORT_DESC; + } + else if (fq.isSortByDateAsc()) + orderClause = dateTerm + " " + DynamicQuery.SORT_ASC + ", " + nameTerm + " " + DynamicQuery.SORT_ASC; + else if (fq.isSortByDateDesc()) + orderClause = dateTerm + " " + DynamicQuery.SORT_DESC + ", " + nameTerm + " " + DynamicQuery.SORT_ASC; + + qry.ORDERBY().pad(); + qry.append(orderClause); + qry.pad(); + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindBindingByCategoryGroupQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBindingByCategoryGroupQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindBindingByCategoryGroupQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBindingByCategoryGroupQuery.java index e65cbfce0..277acf078 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindBindingByCategoryGroupQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBindingByCategoryGroupQuery.java @@ -1,69 +1,69 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; - -import javax.persistence.EntityManager; - -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.api_v3.CategoryBag; - -/** - * Returns the list of binding keys possessing the keyedReferenceGroups in the passed category bag. - * Output is restricted by list of binding keys passed in. If null, all binding templates are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * From specification: - * "This optional argument is a list of category references in the form of keyedReference elements and keyedReferenceGroup - * structures. When used, the returned bindingDetail for this API will contain elements matching all of the categories - * passed (logical AND by default). Specifying the appropriate findQualifiers can override this behavior. - * - * A given keyedReferenceGroup "X" (e.g., within a given categoryBag) matches a keyedReferenceGroup "Y" in the registry if - * and only if the tModelKey assigned to the keyedReferenceGroup X matches the tModelKey assigned to the keyedReferenceGroup - * Y and the set of keyedReferences in "X" are a subset of the set of keyedReferences in "Y." The order of individual - * keyedReferences within a keyedReferenceGroup is not important. Matching rules for the individual contained keyedReference - * elements are the same as above." - * - * @author Jeff Faath - */ -public class FindBindingByCategoryGroupQuery { - - private static final String ENTITY_NAME_CHILD = "BindingCategoryBag"; - - private static final FindEntityByCategoryGroupQuery findQuery; - - static { - findQuery = new FindEntityByCategoryGroupQuery(BindingTemplateQuery.ENTITY_NAME, - BindingTemplateQuery.ENTITY_ALIAS, - BindingTemplateQuery.KEY_NAME, - BindingTemplateQuery.ENTITY_FIELD, - ENTITY_NAME_CHILD, - BindingTemplateQuery.SIGNATURE_PRESENT); - } - - public static List select(EntityManager em, FindQualifiers fq, CategoryBag categoryBag, String parentKey, List keysIn) { - if (parentKey != null && parentKey.length() > 0) { - DynamicQuery.Parameter param = new DynamicQuery.Parameter(BindingTemplateQuery.ENTITY_ALIAS + "." + BindingTemplateQuery.KEY_NAME_PARENT, parentKey, DynamicQuery.PREDICATE_EQUALS); - return findQuery.select(em, fq, categoryBag, keysIn, param); - } - else - return findQuery.select(em, fq, categoryBag, keysIn); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; + +import javax.persistence.EntityManager; + +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.api_v3.CategoryBag; + +/** + * Returns the list of binding keys possessing the keyedReferenceGroups in the passed category bag. + * Output is restricted by list of binding keys passed in. If null, all binding templates are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * From specification: + * "This optional argument is a list of category references in the form of keyedReference elements and keyedReferenceGroup + * structures. When used, the returned bindingDetail for this API will contain elements matching all of the categories + * passed (logical AND by default). Specifying the appropriate findQualifiers can override this behavior. + * + * A given keyedReferenceGroup "X" (e.g., within a given categoryBag) matches a keyedReferenceGroup "Y" in the registry if + * and only if the tModelKey assigned to the keyedReferenceGroup X matches the tModelKey assigned to the keyedReferenceGroup + * Y and the set of keyedReferences in "X" are a subset of the set of keyedReferences in "Y." The order of individual + * keyedReferences within a keyedReferenceGroup is not important. Matching rules for the individual contained keyedReference + * elements are the same as above." + * + * @author Jeff Faath + */ +public class FindBindingByCategoryGroupQuery { + + private static final String ENTITY_NAME_CHILD = "BindingCategoryBag"; + + private static final FindEntityByCategoryGroupQuery findQuery; + + static { + findQuery = new FindEntityByCategoryGroupQuery(BindingTemplateQuery.ENTITY_NAME, + BindingTemplateQuery.ENTITY_ALIAS, + BindingTemplateQuery.KEY_NAME, + BindingTemplateQuery.ENTITY_FIELD, + ENTITY_NAME_CHILD, + BindingTemplateQuery.SIGNATURE_PRESENT); + } + + public static List select(EntityManager em, FindQualifiers fq, CategoryBag categoryBag, String parentKey, List keysIn) { + if (parentKey != null && parentKey.length() > 0) { + DynamicQuery.Parameter param = new DynamicQuery.Parameter(BindingTemplateQuery.ENTITY_ALIAS + "." + BindingTemplateQuery.KEY_NAME_PARENT, parentKey, DynamicQuery.PREDICATE_EQUALS); + return findQuery.select(em, fq, categoryBag, keysIn, param); + } + else + return findQuery.select(em, fq, categoryBag, keysIn); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindBindingByCategoryQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBindingByCategoryQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindBindingByCategoryQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBindingByCategoryQuery.java index 2e34d9722..39891ab73 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindBindingByCategoryQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBindingByCategoryQuery.java @@ -1,63 +1,63 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; - -import javax.persistence.EntityManager; - -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.api_v3.CategoryBag; - -/** - * Returns the list of binding keys possessing the keyedReferences in the passed category bag. - * Output is restricted by list of binding keys passed in. If null, all binding templates are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * From specification: - * "This optional argument is a list of category references in the form of keyedReference elements and keyedReferenceGroup - * structures. When used, the returned bindingDetail for this API will contain elements matching all of the categories - * passed (logical AND by default). Specifying the appropriate findQualifiers can override this behavior." - * - * @author Jeff Faath - */ -public class FindBindingByCategoryQuery { - - private static final String ENTITY_NAME_CHILD = "BindingCategoryBag"; - - private static final FindEntityByCategoryQuery findQuery; - - static { - findQuery = new FindEntityByCategoryQuery(BindingTemplateQuery.ENTITY_NAME, - BindingTemplateQuery.ENTITY_ALIAS, - BindingTemplateQuery.KEY_NAME, - BindingTemplateQuery.ENTITY_FIELD, - ENTITY_NAME_CHILD, - BindingTemplateQuery.SIGNATURE_PRESENT); - } - - public static List select(EntityManager em, FindQualifiers fq, CategoryBag categoryBag, String parentKey, List keysIn) { - if (parentKey != null && parentKey.length() > 0) { - DynamicQuery.Parameter param = new DynamicQuery.Parameter(BindingTemplateQuery.ENTITY_ALIAS + "." + BindingTemplateQuery.KEY_NAME_PARENT, parentKey, DynamicQuery.PREDICATE_EQUALS); - return findQuery.select(em, fq, categoryBag, keysIn, param); - } - else - return findQuery.select(em, fq, categoryBag, keysIn); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; + +import javax.persistence.EntityManager; + +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.api_v3.CategoryBag; + +/** + * Returns the list of binding keys possessing the keyedReferences in the passed category bag. + * Output is restricted by list of binding keys passed in. If null, all binding templates are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * From specification: + * "This optional argument is a list of category references in the form of keyedReference elements and keyedReferenceGroup + * structures. When used, the returned bindingDetail for this API will contain elements matching all of the categories + * passed (logical AND by default). Specifying the appropriate findQualifiers can override this behavior." + * + * @author Jeff Faath + */ +public class FindBindingByCategoryQuery { + + private static final String ENTITY_NAME_CHILD = "BindingCategoryBag"; + + private static final FindEntityByCategoryQuery findQuery; + + static { + findQuery = new FindEntityByCategoryQuery(BindingTemplateQuery.ENTITY_NAME, + BindingTemplateQuery.ENTITY_ALIAS, + BindingTemplateQuery.KEY_NAME, + BindingTemplateQuery.ENTITY_FIELD, + ENTITY_NAME_CHILD, + BindingTemplateQuery.SIGNATURE_PRESENT); + } + + public static List select(EntityManager em, FindQualifiers fq, CategoryBag categoryBag, String parentKey, List keysIn) { + if (parentKey != null && parentKey.length() > 0) { + DynamicQuery.Parameter param = new DynamicQuery.Parameter(BindingTemplateQuery.ENTITY_ALIAS + "." + BindingTemplateQuery.KEY_NAME_PARENT, parentKey, DynamicQuery.PREDICATE_EQUALS); + return findQuery.select(em, fq, categoryBag, keysIn, param); + } + else + return findQuery.select(em, fq, categoryBag, keysIn); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindBindingByTModelKeyQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBindingByTModelKeyQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindBindingByTModelKeyQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBindingByTModelKeyQuery.java index 80d2df35b..6268207dc 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindBindingByTModelKeyQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBindingByTModelKeyQuery.java @@ -1,160 +1,160 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; -import javax.persistence.EntityManager; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.api_v3.TModelBag; - -/** - * Returns the list of binding keys possessing the tModels in the passed tModelBag. - * Output is restricted by list of binding keys passed in. If null, all bindings are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * From specification: - * "This collection of tModelKey elements represent in part or in whole the technical fingerprint of the bindingTemplate - * structures for which the search is being performed. At least one of either a tModelBag or a find_tModel argument SHOULD be - * supplied, unless a categoryBag based search is being used. - - * If a find_tModel argument is specified (see above), it is treated as an embedded inquiry. The tModelKeys returned as a - * result of this embedded find_tModel argument are used as if they had been - * supplied in a tModelBag argument. Changing the order of the keys in the collection or specifying the same tModelKey more than - * once does not change the behavior of the find. - * - * By default, only bindingTemplates that have a technical fingerprint containing - * all of the supplied tModelKeys match (logical AND). Specifying appropriate findQualifiers can override this behavior so that - * bindingTemplates with a technical fingerprint containing any of the specified tModelKeys are returned (logical OR)." - * - * @author Jeff Faath - */ -public class FindBindingByTModelKeyQuery extends BindingTemplateQuery { - - @SuppressWarnings("unused") - private static Log log = LogFactory.getLog(FindBindingByTModelKeyQuery.class); - - public static final String ENTITY_NAME_CHILD = "TmodelInstanceInfo"; - - protected static final String entityAliasChild; - - static { - entityAliasChild = buildAlias(ENTITY_NAME_CHILD); - } - - public static List select(EntityManager em, FindQualifiers fq, TModelBag tModels, String parentKey, - List keysIn, DynamicQuery.Parameter... restrictions) { - // If keysIn is not null and empty, then search is over. - //if ((keysIn != null) && (keysIn.size() == 0)) - // return keysIn; - - if (tModels == null) - return keysIn; - - List tmodelKeys = tModels.getTModelKey(); - if (tmodelKeys == null || tmodelKeys.size() == 0) - return keysIn; - - DynamicQuery dynamicQry = new DynamicQuery(selectSQL); - appendConditions(dynamicQry, fq, tmodelKeys); - if (parentKey != null && parentKey.length() > 0) - dynamicQry.AND().pad().appendGroupedAnd(new DynamicQuery.Parameter(BindingTemplateQuery.ENTITY_ALIAS + "." + BindingTemplateQuery.KEY_NAME_PARENT, parentKey, DynamicQuery.PREDICATE_EQUALS)); - - if (restrictions != null && restrictions.length > 0) - dynamicQry.AND().pad().appendGroupedAnd(restrictions); - - return getQueryResult(em, dynamicQry, keysIn, ENTITY_ALIAS + "." + KEY_NAME); - } - - - /* - * Appends the conditions to the query based on the tModelKey list. With the default or when "orAllKeys" is passed, the keyedReferences are autonomous and are - * all AND'd or OR'd respectively. - * - */ - public static void appendConditions(DynamicQuery qry, FindQualifiers fq, List tmodelKeys) { - - // Append the necessary tables (one will always be added connecting the entity to its instanceinfo table). - appendJoinTables(qry, fq, tmodelKeys); - qry.AND().pad().openParen().pad(); - - int count = 0; - int tblCount = -1; - for(String tmodelKey : tmodelKeys) { - - tblCount++; - String tmodelKeyTerm = (fq.isOrAllKeys()?entityAliasChild + "0":entityAliasChild + tblCount) + ".tmodelKey"; - qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS)); - - if (count + 1 < tmodelKeys.size()) { - if (fq.isOrAllKeys()) - qry.OR().pad(); - else - qry.AND().pad(); - } - - count++; - } - qry.closeParen().pad(); - - } - - /* - * Appends the necessary join table for the child entity and additional tables for when keys are AND'd. This is the default behavior - * so only need to add additional tables if "orAllKeys" has not been set. - */ - public static void appendJoinTables(DynamicQuery qry, FindQualifiers fq, List tmodelKeys) { - - if (tmodelKeys != null && tmodelKeys.size() > 0) { - - StringBuffer thetaJoins = new StringBuffer(200); - int tblCount = 0; - for(int count = 0; count < tmodelKeys.size(); count++) { - if (count != 0) { - if (!fq.isOrAllKeys()) { - tblCount++; - qry.comma().pad().append(ENTITY_NAME_CHILD + " " + entityAliasChild + tblCount).pad(); - thetaJoins.append(entityAliasChild + (tblCount - 1) + "." + ENTITY_FIELD + "." + KEY_NAME + " = " + entityAliasChild + tblCount + "." + ENTITY_FIELD + "." + KEY_NAME + " "); - thetaJoins.append(DynamicQuery.OPERATOR_AND + " "); - } - } - else { - qry.comma().pad().append(ENTITY_NAME_CHILD + " " + entityAliasChild + tblCount).pad(); - thetaJoins.append(ENTITY_ALIAS + "." + KEY_NAME + " = " + entityAliasChild + tblCount + "." + ENTITY_FIELD + "." + KEY_NAME + " "); - thetaJoins.append(DynamicQuery.OPERATOR_AND + " "); - } - } - - qry.WHERE().pad().openParen().pad(); - - String thetaJoinsStr = thetaJoins.toString(); - if (thetaJoinsStr.endsWith(DynamicQuery.OPERATOR_AND + " ")) - thetaJoinsStr = thetaJoinsStr.substring(0, thetaJoinsStr.length() - (DynamicQuery.OPERATOR_AND + " ").length()); - qry.append(thetaJoinsStr); - - qry.closeParen().pad(); - if (fq!=null && fq.isSignaturePresent()) { - qry.AND().pad().openParen().pad().append(BindingTemplateQuery.SIGNATURE_PRESENT).pad().closeParen().pad(); - } - } - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; +import javax.persistence.EntityManager; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.api_v3.TModelBag; + +/** + * Returns the list of binding keys possessing the tModels in the passed tModelBag. + * Output is restricted by list of binding keys passed in. If null, all bindings are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * From specification: + * "This collection of tModelKey elements represent in part or in whole the technical fingerprint of the bindingTemplate + * structures for which the search is being performed. At least one of either a tModelBag or a find_tModel argument SHOULD be + * supplied, unless a categoryBag based search is being used. + + * If a find_tModel argument is specified (see above), it is treated as an embedded inquiry. The tModelKeys returned as a + * result of this embedded find_tModel argument are used as if they had been + * supplied in a tModelBag argument. Changing the order of the keys in the collection or specifying the same tModelKey more than + * once does not change the behavior of the find. + * + * By default, only bindingTemplates that have a technical fingerprint containing + * all of the supplied tModelKeys match (logical AND). Specifying appropriate findQualifiers can override this behavior so that + * bindingTemplates with a technical fingerprint containing any of the specified tModelKeys are returned (logical OR)." + * + * @author Jeff Faath + */ +public class FindBindingByTModelKeyQuery extends BindingTemplateQuery { + + @SuppressWarnings("unused") + private static Log log = LogFactory.getLog(FindBindingByTModelKeyQuery.class); + + public static final String ENTITY_NAME_CHILD = "TmodelInstanceInfo"; + + protected static final String entityAliasChild; + + static { + entityAliasChild = buildAlias(ENTITY_NAME_CHILD); + } + + public static List select(EntityManager em, FindQualifiers fq, TModelBag tModels, String parentKey, + List keysIn, DynamicQuery.Parameter... restrictions) { + // If keysIn is not null and empty, then search is over. + //if ((keysIn != null) && (keysIn.size() == 0)) + // return keysIn; + + if (tModels == null) + return keysIn; + + List tmodelKeys = tModels.getTModelKey(); + if (tmodelKeys == null || tmodelKeys.size() == 0) + return keysIn; + + DynamicQuery dynamicQry = new DynamicQuery(selectSQL); + appendConditions(dynamicQry, fq, tmodelKeys); + if (parentKey != null && parentKey.length() > 0) + dynamicQry.AND().pad().appendGroupedAnd(new DynamicQuery.Parameter(BindingTemplateQuery.ENTITY_ALIAS + "." + BindingTemplateQuery.KEY_NAME_PARENT, parentKey, DynamicQuery.PREDICATE_EQUALS)); + + if (restrictions != null && restrictions.length > 0) + dynamicQry.AND().pad().appendGroupedAnd(restrictions); + + return getQueryResult(em, dynamicQry, keysIn, ENTITY_ALIAS + "." + KEY_NAME); + } + + + /* + * Appends the conditions to the query based on the tModelKey list. With the default or when "orAllKeys" is passed, the keyedReferences are autonomous and are + * all AND'd or OR'd respectively. + * + */ + public static void appendConditions(DynamicQuery qry, FindQualifiers fq, List tmodelKeys) { + + // Append the necessary tables (one will always be added connecting the entity to its instanceinfo table). + appendJoinTables(qry, fq, tmodelKeys); + qry.AND().pad().openParen().pad(); + + int count = 0; + int tblCount = -1; + for(String tmodelKey : tmodelKeys) { + + tblCount++; + String tmodelKeyTerm = (fq.isOrAllKeys()?entityAliasChild + "0":entityAliasChild + tblCount) + ".tmodelKey"; + qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS)); + + if (count + 1 < tmodelKeys.size()) { + if (fq.isOrAllKeys()) + qry.OR().pad(); + else + qry.AND().pad(); + } + + count++; + } + qry.closeParen().pad(); + + } + + /* + * Appends the necessary join table for the child entity and additional tables for when keys are AND'd. This is the default behavior + * so only need to add additional tables if "orAllKeys" has not been set. + */ + public static void appendJoinTables(DynamicQuery qry, FindQualifiers fq, List tmodelKeys) { + + if (tmodelKeys != null && tmodelKeys.size() > 0) { + + StringBuffer thetaJoins = new StringBuffer(200); + int tblCount = 0; + for(int count = 0; count < tmodelKeys.size(); count++) { + if (count != 0) { + if (!fq.isOrAllKeys()) { + tblCount++; + qry.comma().pad().append(ENTITY_NAME_CHILD + " " + entityAliasChild + tblCount).pad(); + thetaJoins.append(entityAliasChild + (tblCount - 1) + "." + ENTITY_FIELD + "." + KEY_NAME + " = " + entityAliasChild + tblCount + "." + ENTITY_FIELD + "." + KEY_NAME + " "); + thetaJoins.append(DynamicQuery.OPERATOR_AND + " "); + } + } + else { + qry.comma().pad().append(ENTITY_NAME_CHILD + " " + entityAliasChild + tblCount).pad(); + thetaJoins.append(ENTITY_ALIAS + "." + KEY_NAME + " = " + entityAliasChild + tblCount + "." + ENTITY_FIELD + "." + KEY_NAME + " "); + thetaJoins.append(DynamicQuery.OPERATOR_AND + " "); + } + } + + qry.WHERE().pad().openParen().pad(); + + String thetaJoinsStr = thetaJoins.toString(); + if (thetaJoinsStr.endsWith(DynamicQuery.OPERATOR_AND + " ")) + thetaJoinsStr = thetaJoinsStr.substring(0, thetaJoinsStr.length() - (DynamicQuery.OPERATOR_AND + " ").length()); + qry.append(thetaJoinsStr); + + qry.closeParen().pad(); + if (fq!=null && fq.isSignaturePresent()) { + qry.AND().pad().openParen().pad().append(BindingTemplateQuery.SIGNATURE_PRESENT).pad().closeParen().pad(); + } + } + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByCategoryGroupQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByCategoryGroupQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByCategoryGroupQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByCategoryGroupQuery.java index dfc628b95..755b924ea 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByCategoryGroupQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByCategoryGroupQuery.java @@ -1,63 +1,63 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; - -import javax.persistence.EntityManager; - -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.api_v3.CategoryBag; - -/** - * Returns the list of business keys possessing the keyedReferenceGroups in the passed category bag. - * Output is restricted by list of business keys passed in. If null, all business entities are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * From specification: - * "This is a list of category references in the form of keyedReference elements and keyedReferenceGroup - * structures. The returned businessList contains businessInfo elements matching all of the categories - * passed (logical AND by default). Specifying the appropriate findQualifiers can override this behavior. - * - * A given keyedReferenceGroup "X" (e.g., within a given categoryBag) matches a keyedReferenceGroup "Y" in the registry if - * and only if the tModelKey assigned to the keyedReferenceGroup X matches the tModelKey assigned to the keyedReferenceGroup - * Y and the set of keyedReferences in "X" are a subset of the set of keyedReferences in "Y." The order of individual - * keyedReferences within a keyedReferenceGroup is not important. Matching rules for the individual contained keyedReference - * elements are the same as above." - * - * @author Jeff Faath - */ -public class FindBusinessByCategoryGroupQuery { - - private static final String ENTITY_NAME_CHILD = "BusinessCategoryBag"; - - private static final FindEntityByCategoryGroupQuery findQuery; - - static { - findQuery = new FindEntityByCategoryGroupQuery(BusinessEntityQuery.ENTITY_NAME, - BusinessEntityQuery.ENTITY_ALIAS, - BusinessEntityQuery.KEY_NAME, - BusinessEntityQuery.ENTITY_FIELD, - ENTITY_NAME_CHILD, - BusinessEntityQuery.SIGNATURE_PRESENT); - } - - public static List select(EntityManager em, FindQualifiers fq, CategoryBag categoryBag, List keysIn) { - return findQuery.select(em, fq, categoryBag, keysIn); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; + +import javax.persistence.EntityManager; + +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.api_v3.CategoryBag; + +/** + * Returns the list of business keys possessing the keyedReferenceGroups in the passed category bag. + * Output is restricted by list of business keys passed in. If null, all business entities are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * From specification: + * "This is a list of category references in the form of keyedReference elements and keyedReferenceGroup + * structures. The returned businessList contains businessInfo elements matching all of the categories + * passed (logical AND by default). Specifying the appropriate findQualifiers can override this behavior. + * + * A given keyedReferenceGroup "X" (e.g., within a given categoryBag) matches a keyedReferenceGroup "Y" in the registry if + * and only if the tModelKey assigned to the keyedReferenceGroup X matches the tModelKey assigned to the keyedReferenceGroup + * Y and the set of keyedReferences in "X" are a subset of the set of keyedReferences in "Y." The order of individual + * keyedReferences within a keyedReferenceGroup is not important. Matching rules for the individual contained keyedReference + * elements are the same as above." + * + * @author Jeff Faath + */ +public class FindBusinessByCategoryGroupQuery { + + private static final String ENTITY_NAME_CHILD = "BusinessCategoryBag"; + + private static final FindEntityByCategoryGroupQuery findQuery; + + static { + findQuery = new FindEntityByCategoryGroupQuery(BusinessEntityQuery.ENTITY_NAME, + BusinessEntityQuery.ENTITY_ALIAS, + BusinessEntityQuery.KEY_NAME, + BusinessEntityQuery.ENTITY_FIELD, + ENTITY_NAME_CHILD, + BusinessEntityQuery.SIGNATURE_PRESENT); + } + + public static List select(EntityManager em, FindQualifiers fq, CategoryBag categoryBag, List keysIn) { + return findQuery.select(em, fq, categoryBag, keysIn); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByCategoryQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByCategoryQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByCategoryQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByCategoryQuery.java index cecb33983..a51eeb39a 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByCategoryQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByCategoryQuery.java @@ -1,57 +1,57 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; - -import javax.persistence.EntityManager; - -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.api_v3.CategoryBag; - -/** - * Returns the list of business keys possessing the keyedReferences in the passed category bag. - * Output is restricted by list of business keys passed in. If null, all business entities are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * From specification: - * "This is a list of category references in the form of keyedReference elements and keyedReferenceGroup - * structures. The returned businessList contains businessInfo elements matching all of the categories - * passed (logical AND by default). Specifying the appropriate findQualifiers can override this behavior." - * - * @author Jeff Faath - */ -public class FindBusinessByCategoryQuery { - - private static final String ENTITY_NAME_CHILD = "BusinessCategoryBag"; - - private static final FindEntityByCategoryQuery findQuery; - - static { - findQuery = new FindEntityByCategoryQuery(BusinessEntityQuery.ENTITY_NAME, - BusinessEntityQuery.ENTITY_ALIAS, - BusinessEntityQuery.KEY_NAME, - BusinessEntityQuery.ENTITY_FIELD, - ENTITY_NAME_CHILD, - BusinessEntityQuery.SIGNATURE_PRESENT); - } - - public static List select(EntityManager em, FindQualifiers fq, CategoryBag categoryBag, List keysIn) { - return findQuery.select(em, fq, categoryBag, keysIn); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; + +import javax.persistence.EntityManager; + +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.api_v3.CategoryBag; + +/** + * Returns the list of business keys possessing the keyedReferences in the passed category bag. + * Output is restricted by list of business keys passed in. If null, all business entities are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * From specification: + * "This is a list of category references in the form of keyedReference elements and keyedReferenceGroup + * structures. The returned businessList contains businessInfo elements matching all of the categories + * passed (logical AND by default). Specifying the appropriate findQualifiers can override this behavior." + * + * @author Jeff Faath + */ +public class FindBusinessByCategoryQuery { + + private static final String ENTITY_NAME_CHILD = "BusinessCategoryBag"; + + private static final FindEntityByCategoryQuery findQuery; + + static { + findQuery = new FindEntityByCategoryQuery(BusinessEntityQuery.ENTITY_NAME, + BusinessEntityQuery.ENTITY_ALIAS, + BusinessEntityQuery.KEY_NAME, + BusinessEntityQuery.ENTITY_FIELD, + ENTITY_NAME_CHILD, + BusinessEntityQuery.SIGNATURE_PRESENT); + } + + public static List select(EntityManager em, FindQualifiers fq, CategoryBag categoryBag, List keysIn) { + return findQuery.select(em, fq, categoryBag, keysIn); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByCombinedCategoryQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByCombinedCategoryQuery.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByCombinedCategoryQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByCombinedCategoryQuery.java diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByDiscoveryURLQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByDiscoveryURLQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByDiscoveryURLQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByDiscoveryURLQuery.java index ac8526460..8037b0ea9 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByDiscoveryURLQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByDiscoveryURLQuery.java @@ -1,120 +1,120 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; -import javax.persistence.EntityManager; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.api_v3.DiscoveryURLs; -import org.uddi.api_v3.DiscoveryURL; - -/** - * - * Returns the list of business keys possessing the DiscoveryUrls in the passed DiscoveryUrl list. - * Output is restricted by list of business keys passed in. If null, all businesses are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * From specification: - * "This is a list of discoveryURL structures to be matched against the discoveryURL data associated with registered businessEntity - * information. To search for URL without regard to useType attribute values, omit the useType attribute or pass it as an empty - * attribute. If useType values are included, the match occurs only on registered information that matches both the useType and - * URL value. The returned businessList contains businessInfo structures matching any of the URL's passed (logical OR)." - * - * @author Jeff Faath - */ -public class FindBusinessByDiscoveryURLQuery extends BusinessEntityQuery { - - @SuppressWarnings("unused") - private static Log log = LogFactory.getLog(FindBusinessByDiscoveryURLQuery.class); - - private static final String ENTITY_NAME_CHILD = "DiscoveryUrl"; - - private static final String entityAliasChild;; - - static { - entityAliasChild = buildAlias(ENTITY_NAME_CHILD); - } - - public static List select(EntityManager em, FindQualifiers fq, DiscoveryURLs discURLs, - List keysIn, DynamicQuery.Parameter... restrictions) { - // If keysIn is not null and empty, then search is over. - if ((keysIn != null) && (keysIn.size() == 0)) - return keysIn; - - if (discURLs == null) - return keysIn; - - List discURLlist = discURLs.getDiscoveryURL(); - if (discURLlist == null || discURLlist.size() == 0) - return keysIn; - - DynamicQuery dynamicQry = new DynamicQuery(selectSQL); - appendConditions(dynamicQry, fq, discURLlist); - if (restrictions != null && restrictions.length > 0) - dynamicQry.AND().pad().appendGroupedAnd(restrictions); - - return getQueryResult(em, dynamicQry, keysIn, ENTITY_ALIAS + "." + KEY_NAME); - } - - /* - * Appends the conditions to the query based on the discovery url list. By default, the urls are OR'd and this cannot be changed. - * - */ - public static void appendConditions(DynamicQuery qry, FindQualifiers fq, List discURLs) { - - // Append the necessary tables (one will always be added connecting the entity to its discovery url table). - appendJoinTables(qry, fq, discURLs); - qry.AND().pad().openParen().pad(); - - int count = 0; - for(DiscoveryURL discURL : discURLs) { - String urlTerm = entityAliasChild + ".url"; - String urlValue = discURL.getValue(); - - if (discURL.getUseType() == null || discURL.getUseType().length() == 0 ) { - qry.appendGroupedAnd(new DynamicQuery.Parameter(urlTerm, urlValue, DynamicQuery.PREDICATE_LIKE)); - } - else { - qry.appendGroupedAnd(new DynamicQuery.Parameter(urlTerm, urlValue, DynamicQuery.PREDICATE_LIKE), - new DynamicQuery.Parameter(entityAliasChild + ".useType", discURL.getUseType(), DynamicQuery.PREDICATE_EQUALS)); - } - - if (count + 1 < discURLs.size()) - qry.OR().pad(); - - count++; - } - qry.closeParen().pad(); - - } - - /* - * Appends the necessary join table for the child entity - */ - public static void appendJoinTables(DynamicQuery qry, FindQualifiers fq, List discURLs) { - qry.comma().pad().append(ENTITY_NAME_CHILD + " " + entityAliasChild).pad(); - qry.WHERE().pad().openParen().pad(); - qry.append(ENTITY_ALIAS + "." + KEY_NAME + " = " + entityAliasChild + "." + ENTITY_FIELD + "." + KEY_NAME + " "); - qry.closeParen().pad(); - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; +import javax.persistence.EntityManager; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.api_v3.DiscoveryURLs; +import org.uddi.api_v3.DiscoveryURL; + +/** + * + * Returns the list of business keys possessing the DiscoveryUrls in the passed DiscoveryUrl list. + * Output is restricted by list of business keys passed in. If null, all businesses are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * From specification: + * "This is a list of discoveryURL structures to be matched against the discoveryURL data associated with registered businessEntity + * information. To search for URL without regard to useType attribute values, omit the useType attribute or pass it as an empty + * attribute. If useType values are included, the match occurs only on registered information that matches both the useType and + * URL value. The returned businessList contains businessInfo structures matching any of the URL's passed (logical OR)." + * + * @author Jeff Faath + */ +public class FindBusinessByDiscoveryURLQuery extends BusinessEntityQuery { + + @SuppressWarnings("unused") + private static Log log = LogFactory.getLog(FindBusinessByDiscoveryURLQuery.class); + + private static final String ENTITY_NAME_CHILD = "DiscoveryUrl"; + + private static final String entityAliasChild;; + + static { + entityAliasChild = buildAlias(ENTITY_NAME_CHILD); + } + + public static List select(EntityManager em, FindQualifiers fq, DiscoveryURLs discURLs, + List keysIn, DynamicQuery.Parameter... restrictions) { + // If keysIn is not null and empty, then search is over. + if ((keysIn != null) && (keysIn.size() == 0)) + return keysIn; + + if (discURLs == null) + return keysIn; + + List discURLlist = discURLs.getDiscoveryURL(); + if (discURLlist == null || discURLlist.size() == 0) + return keysIn; + + DynamicQuery dynamicQry = new DynamicQuery(selectSQL); + appendConditions(dynamicQry, fq, discURLlist); + if (restrictions != null && restrictions.length > 0) + dynamicQry.AND().pad().appendGroupedAnd(restrictions); + + return getQueryResult(em, dynamicQry, keysIn, ENTITY_ALIAS + "." + KEY_NAME); + } + + /* + * Appends the conditions to the query based on the discovery url list. By default, the urls are OR'd and this cannot be changed. + * + */ + public static void appendConditions(DynamicQuery qry, FindQualifiers fq, List discURLs) { + + // Append the necessary tables (one will always be added connecting the entity to its discovery url table). + appendJoinTables(qry, fq, discURLs); + qry.AND().pad().openParen().pad(); + + int count = 0; + for(DiscoveryURL discURL : discURLs) { + String urlTerm = entityAliasChild + ".url"; + String urlValue = discURL.getValue(); + + if (discURL.getUseType() == null || discURL.getUseType().length() == 0 ) { + qry.appendGroupedAnd(new DynamicQuery.Parameter(urlTerm, urlValue, DynamicQuery.PREDICATE_LIKE)); + } + else { + qry.appendGroupedAnd(new DynamicQuery.Parameter(urlTerm, urlValue, DynamicQuery.PREDICATE_LIKE), + new DynamicQuery.Parameter(entityAliasChild + ".useType", discURL.getUseType(), DynamicQuery.PREDICATE_EQUALS)); + } + + if (count + 1 < discURLs.size()) + qry.OR().pad(); + + count++; + } + qry.closeParen().pad(); + + } + + /* + * Appends the necessary join table for the child entity + */ + public static void appendJoinTables(DynamicQuery qry, FindQualifiers fq, List discURLs) { + qry.comma().pad().append(ENTITY_NAME_CHILD + " " + entityAliasChild).pad(); + qry.WHERE().pad().openParen().pad(); + qry.append(ENTITY_ALIAS + "." + KEY_NAME + " = " + entityAliasChild + "." + ENTITY_FIELD + "." + KEY_NAME + " "); + qry.closeParen().pad(); + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByIdentifierQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByIdentifierQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByIdentifierQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByIdentifierQuery.java index 0c117f4d9..9645b0537 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByIdentifierQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByIdentifierQuery.java @@ -1,57 +1,57 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; -import javax.persistence.EntityManager; - -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.api_v3.IdentifierBag; - -/** - * Returns the list of business keys possessing the keyedReferences in the passed identifier bag. - * Output is restricted by list of business keys passed in. If null, all business entities are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * From specification: - * "This is a list of business identifier references in the form of keyedReference elements. The returned - * businessList contains businessInfo structures matching any of the identifiers passed (logical OR by default). - * Specifying the appropriate findQualifiers can override this behavior" - * - * @author Jeff Faath - */ -public class FindBusinessByIdentifierQuery { - - private static final String ENTITY_NAME_CHILD = "BusinessIdentifier"; - - private static final FindEntityByIdentifierQuery findQuery; - - static { - findQuery = new FindEntityByIdentifierQuery(BusinessEntityQuery.ENTITY_NAME, - BusinessEntityQuery.ENTITY_ALIAS, - BusinessEntityQuery.KEY_NAME, - BusinessEntityQuery.ENTITY_FIELD, - ENTITY_NAME_CHILD, - BusinessEntityQuery.SIGNATURE_PRESENT); - } - - public static List select(EntityManager em, FindQualifiers fq, IdentifierBag identifiers, List keysIn) { - return findQuery.select(em, fq, identifiers, keysIn); - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; +import javax.persistence.EntityManager; + +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.api_v3.IdentifierBag; + +/** + * Returns the list of business keys possessing the keyedReferences in the passed identifier bag. + * Output is restricted by list of business keys passed in. If null, all business entities are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * From specification: + * "This is a list of business identifier references in the form of keyedReference elements. The returned + * businessList contains businessInfo structures matching any of the identifiers passed (logical OR by default). + * Specifying the appropriate findQualifiers can override this behavior" + * + * @author Jeff Faath + */ +public class FindBusinessByIdentifierQuery { + + private static final String ENTITY_NAME_CHILD = "BusinessIdentifier"; + + private static final FindEntityByIdentifierQuery findQuery; + + static { + findQuery = new FindEntityByIdentifierQuery(BusinessEntityQuery.ENTITY_NAME, + BusinessEntityQuery.ENTITY_ALIAS, + BusinessEntityQuery.KEY_NAME, + BusinessEntityQuery.ENTITY_FIELD, + ENTITY_NAME_CHILD, + BusinessEntityQuery.SIGNATURE_PRESENT); + } + + public static List select(EntityManager em, FindQualifiers fq, IdentifierBag identifiers, List keysIn) { + return findQuery.select(em, fq, identifiers, keysIn); + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByNameQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByNameQuery.java similarity index 98% rename from juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByNameQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByNameQuery.java index b2a185a88..0c3ef1162 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByNameQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByNameQuery.java @@ -1,65 +1,65 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; -import javax.persistence.EntityManager; - -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.api_v3.Name; - -/** - * Returns the list of business keys possessing the Names in the passed Name list. - * Output is restricted by list of business keys passed in. If null, all businesses are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * From specification: - * "This optional collection of string values represents one or more names potentially qualified with xml:lang attributes. - * Since "exactMatch" is the default behavior, the value supplied for the name argument must be an exact match. If the "approximateMatch" - * findQualifier is used together with an appropriate wildcard character in the name, then any businessEntity matching this name with - * wildcards and the other criteria will be referenced in the results. For more on wildcard matching, see Section 5.1.6 About Wildcards. - * The businessList returned contains businessInfo structures for businesses whose name matches the value(s) passed - * (lexical-order match i.e., leftmost in left-to-right languages). If multiple name values are passed, the match occurs on a - * logical OR basis. Each name MAY be marked with an xml:lang adornment. If a language markup is specified, the search results report a - * match only on those entries that match both the name value and language criteria. The match on language is a leftmost case-insensitive - * comparison of the characters supplied. This allows one to find all businesses whose name begins with an "A" and are expressed in any - * dialect of French, for example. Values which can be passed in the language criteria adornment MUST obey the rules governing the - * xml:lang data type as defined in Section 3.3.2.3 name." - * - * @author Jeff Faath - */ -public class FindBusinessByNameQuery { - - public static final String ENTITY_NAME_CHILD = "BusinessName"; - - private final static FindEntityByNamesQuery findQuery; - - static { - findQuery = new FindEntityByNamesQuery(BusinessEntityQuery.ENTITY_NAME, - BusinessEntityQuery.ENTITY_ALIAS, - BusinessEntityQuery.KEY_NAME, - BusinessEntityQuery.ENTITY_FIELD, - ENTITY_NAME_CHILD, - BusinessEntityQuery.SIGNATURE_PRESENT); - } - - public static List select(EntityManager em, FindQualifiers fq, List names, List keysIn) { - return findQuery.select(em, fq, names, keysIn); - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; +import javax.persistence.EntityManager; + +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.api_v3.Name; + +/** + * Returns the list of business keys possessing the Names in the passed Name list. + * Output is restricted by list of business keys passed in. If null, all businesses are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * From specification: + * "This optional collection of string values represents one or more names potentially qualified with xml:lang attributes. + * Since "exactMatch" is the default behavior, the value supplied for the name argument must be an exact match. If the "approximateMatch" + * findQualifier is used together with an appropriate wildcard character in the name, then any businessEntity matching this name with + * wildcards and the other criteria will be referenced in the results. For more on wildcard matching, see Section 5.1.6 About Wildcards. + * The businessList returned contains businessInfo structures for businesses whose name matches the value(s) passed + * (lexical-order match i.e., leftmost in left-to-right languages). If multiple name values are passed, the match occurs on a + * logical OR basis. Each name MAY be marked with an xml:lang adornment. If a language markup is specified, the search results report a + * match only on those entries that match both the name value and language criteria. The match on language is a leftmost case-insensitive + * comparison of the characters supplied. This allows one to find all businesses whose name begins with an "A" and are expressed in any + * dialect of French, for example. Values which can be passed in the language criteria adornment MUST obey the rules governing the + * xml:lang data type as defined in Section 3.3.2.3 name." + * + * @author Jeff Faath + */ +public class FindBusinessByNameQuery { + + public static final String ENTITY_NAME_CHILD = "BusinessName"; + + private final static FindEntityByNamesQuery findQuery; + + static { + findQuery = new FindEntityByNamesQuery(BusinessEntityQuery.ENTITY_NAME, + BusinessEntityQuery.ENTITY_ALIAS, + BusinessEntityQuery.KEY_NAME, + BusinessEntityQuery.ENTITY_FIELD, + ENTITY_NAME_CHILD, + BusinessEntityQuery.SIGNATURE_PRESENT); + } + + public static List select(EntityManager em, FindQualifiers fq, List names, List keysIn) { + return findQuery.select(em, fq, names, keysIn); + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByPublisherQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByPublisherQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByPublisherQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByPublisherQuery.java index ebcb21c3f..5409f1225 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByPublisherQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByPublisherQuery.java @@ -1,51 +1,51 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; -import javax.persistence.EntityManager; - -import org.apache.juddi.query.util.FindQualifiers; -import org.apache.juddi.model.UddiEntityPublisher; - -/** - * Returns the list of business keys possessing the publisherId in the passed UddiEntityPublisher. - * Output is restricted by list of business keys passed in. If null, all businesses are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * - * @author Jeff Faath - */ -public class FindBusinessByPublisherQuery { - - - private final static FindEntityByPublisherQuery findQuery; - - static { - findQuery = new FindEntityByPublisherQuery( - BusinessEntityQuery.ENTITY_NAME, - BusinessEntityQuery.ENTITY_ALIAS, - BusinessEntityQuery.KEY_NAME, - BusinessEntityQuery.SIGNATURE_PRESENT); - } - - public static List select(EntityManager em, FindQualifiers fq, UddiEntityPublisher publisher, List keysIn) { - return findQuery.select(em, fq, publisher, keysIn); - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; +import javax.persistence.EntityManager; + +import org.apache.juddi.query.util.FindQualifiers; +import org.apache.juddi.model.UddiEntityPublisher; + +/** + * Returns the list of business keys possessing the publisherId in the passed UddiEntityPublisher. + * Output is restricted by list of business keys passed in. If null, all businesses are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * + * @author Jeff Faath + */ +public class FindBusinessByPublisherQuery { + + + private final static FindEntityByPublisherQuery findQuery; + + static { + findQuery = new FindEntityByPublisherQuery( + BusinessEntityQuery.ENTITY_NAME, + BusinessEntityQuery.ENTITY_ALIAS, + BusinessEntityQuery.KEY_NAME, + BusinessEntityQuery.SIGNATURE_PRESENT); + } + + public static List select(EntityManager em, FindQualifiers fq, UddiEntityPublisher publisher, List keysIn) { + return findQuery.select(em, fq, publisher, keysIn); + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByTModelKeyQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByTModelKeyQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByTModelKeyQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByTModelKeyQuery.java index bde5d2b77..1e7c6dbe4 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindBusinessByTModelKeyQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindBusinessByTModelKeyQuery.java @@ -1,164 +1,164 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; -import javax.persistence.EntityManager; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.api_v3.TModelBag; - -/** - * Returns the list of business keys with services that have bindings that possess the tModels in the passed tModelBag. - * Output is restricted by list of service keys passed in. If null, all services are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * From specification: - * "Every Web service instance exposed by a registered businessEntity is represented in UDDI by a bindingTemplate contained - * within the businessEntity. Each bindingTemplate contains a collection of tModel references called its "technical fingerprint" - * that specifies its type. The tModelBag argument is a collection of tModelKey elements specifying that the search results are - * to be limited to businesses that expose Web services with technical fingerprints that match. - * - * If a find_tModel argument is specified (see above), it is treated as an embedded inquiry. The tModelKeys returned as a result - * of this embedded find_tModel argument are used as if they had been supplied in a tModelBag argument. Changing the order of the - * keys in the collection or specifying the same tModelKey more than once does not change the behavior of the find. - * - * By default, only bindingTemplates that contain all of the tModelKeys in the technical fingerprint match (logical AND). Specifying - * appropriate findQualifiers can override this behavior so that bindingTemplates containing any of the specified tModelKeys match - * (logical OR)." - * - * @author Jeff Faath - */ -public class FindBusinessByTModelKeyQuery extends BusinessEntityQuery { - - @SuppressWarnings("unused") - private final static Log log = LogFactory.getLog(FindBusinessByTModelKeyQuery.class); - - public static final String ENTITY_NAME_CHILD = "TmodelInstanceInfo"; - - protected static final String entityAliasChild; - - static { - entityAliasChild = buildAlias(ENTITY_NAME_CHILD); - } - - public static List select(EntityManager em, FindQualifiers fq, TModelBag tModels, List keysIn, DynamicQuery.Parameter... restrictions) { - // If keysIn is not null and empty, then search is over. - if ((keysIn != null) && (keysIn.isEmpty())) - return keysIn; - - if (tModels == null) - return keysIn; - - List tmodelKeys = tModels.getTModelKey(); - if (tmodelKeys == null || tmodelKeys.isEmpty()) - return keysIn; - - DynamicQuery dynamicQry = new DynamicQuery(selectSQL); - appendConditions(dynamicQry, fq, tmodelKeys); - - if (restrictions != null && restrictions.length > 0) - dynamicQry.AND().pad().appendGroupedAnd(restrictions); - - return getQueryResult(em, dynamicQry, keysIn, ENTITY_ALIAS + "." + KEY_NAME); - } - - - /* - * Appends the conditions to the query based on the tModelKey list. With the default or when "orAllKeys" is passed, the keyedReferences are autonomous and are - * all AND'd or OR'd respectively. - * - */ - public static void appendConditions(DynamicQuery qry, FindQualifiers fq, List tmodelKeys) { - - // Append the necessary tables (one will always be added connecting the entity to its instanceinfo table). - appendJoinTables(qry, fq, tmodelKeys); - qry.AND().pad().openParen().pad(); - - int count = 0; - int tblCount = -1; - for(String tmodelKey : tmodelKeys) { - - tblCount++; - String tmodelKeyTerm = (fq.isOrAllKeys()?entityAliasChild + "0":entityAliasChild + tblCount) + ".tmodelKey"; - qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS)); - - if (count + 1 < tmodelKeys.size()) { - if (fq.isOrAllKeys()) - qry.OR().pad(); - else - qry.AND().pad(); - } - - count++; - } - qry.closeParen().pad(); - - } - - /* - * Appends the necessary join table for the child entity and additional tables for when keys are AND'd. This is the default behavior - * so only need to add additional tables if "orAllKeys" has not been set. - */ - public static void appendJoinTables(DynamicQuery qry, FindQualifiers fq, List tmodelKeys) { - - - if (tmodelKeys != null && tmodelKeys.size() > 0) { - qry.comma().pad().append(BusinessServiceQuery.ENTITY_NAME + " " + BusinessServiceQuery.ENTITY_ALIAS).pad(); - qry.comma().pad().append(BindingTemplateQuery.ENTITY_NAME + " " + BindingTemplateQuery.ENTITY_ALIAS).pad(); - - StringBuilder thetaJoins = new StringBuilder(200); - int tblCount = 0; - for(int count = 0; count < tmodelKeys.size(); count++) { - if (count != 0) { - if (!fq.isOrAllKeys()) { - tblCount++; - qry.comma().pad().append(ENTITY_NAME_CHILD + " " + entityAliasChild + tblCount).pad(); - thetaJoins.append(entityAliasChild + (tblCount - 1) + "." + BindingTemplateQuery.ENTITY_FIELD + "." + BindingTemplateQuery.KEY_NAME + " = " + entityAliasChild + tblCount + "." + BindingTemplateQuery.ENTITY_FIELD + "." + BindingTemplateQuery.KEY_NAME + " "); - thetaJoins.append(DynamicQuery.OPERATOR_AND + " "); - } - } - else { - qry.comma().pad().append(ENTITY_NAME_CHILD + " " + entityAliasChild + tblCount).pad(); - thetaJoins.append(BindingTemplateQuery.ENTITY_ALIAS + "." + BindingTemplateQuery.KEY_NAME + " = " + entityAliasChild + tblCount + "." + BindingTemplateQuery.ENTITY_FIELD + "." + BindingTemplateQuery.KEY_NAME + " "); - thetaJoins.append(DynamicQuery.OPERATOR_AND + " "); - } - } - - qry.WHERE().pad().openParen().pad(); - - qry.append(ENTITY_ALIAS + "." + KEY_NAME + " = " + BusinessServiceQuery.ENTITY_ALIAS + "." + ENTITY_FIELD + "." + KEY_NAME).pad(); - qry.AND().pad().append(BusinessServiceQuery.ENTITY_ALIAS + "." + BusinessServiceQuery.KEY_NAME + " = " + BindingTemplateQuery.ENTITY_ALIAS + "." + BusinessServiceQuery.ENTITY_FIELD + "." + BusinessServiceQuery.KEY_NAME).pad(); - qry.AND().pad(); - - String thetaJoinsStr = thetaJoins.toString(); - if (thetaJoinsStr.endsWith(DynamicQuery.OPERATOR_AND + " ")) - thetaJoinsStr = thetaJoinsStr.substring(0, thetaJoinsStr.length() - (DynamicQuery.OPERATOR_AND + " ").length()); - qry.append(thetaJoinsStr); - - qry.closeParen().pad(); - if (fq!=null && fq.isSignaturePresent()) { - qry.AND().pad().openParen().pad().append(BusinessEntityQuery.SIGNATURE_PRESENT).pad().closeParen().pad(); - } - } - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; +import javax.persistence.EntityManager; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.api_v3.TModelBag; + +/** + * Returns the list of business keys with services that have bindings that possess the tModels in the passed tModelBag. + * Output is restricted by list of service keys passed in. If null, all services are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * From specification: + * "Every Web service instance exposed by a registered businessEntity is represented in UDDI by a bindingTemplate contained + * within the businessEntity. Each bindingTemplate contains a collection of tModel references called its "technical fingerprint" + * that specifies its type. The tModelBag argument is a collection of tModelKey elements specifying that the search results are + * to be limited to businesses that expose Web services with technical fingerprints that match. + * + * If a find_tModel argument is specified (see above), it is treated as an embedded inquiry. The tModelKeys returned as a result + * of this embedded find_tModel argument are used as if they had been supplied in a tModelBag argument. Changing the order of the + * keys in the collection or specifying the same tModelKey more than once does not change the behavior of the find. + * + * By default, only bindingTemplates that contain all of the tModelKeys in the technical fingerprint match (logical AND). Specifying + * appropriate findQualifiers can override this behavior so that bindingTemplates containing any of the specified tModelKeys match + * (logical OR)." + * + * @author Jeff Faath + */ +public class FindBusinessByTModelKeyQuery extends BusinessEntityQuery { + + @SuppressWarnings("unused") + private final static Log log = LogFactory.getLog(FindBusinessByTModelKeyQuery.class); + + public static final String ENTITY_NAME_CHILD = "TmodelInstanceInfo"; + + protected static final String entityAliasChild; + + static { + entityAliasChild = buildAlias(ENTITY_NAME_CHILD); + } + + public static List select(EntityManager em, FindQualifiers fq, TModelBag tModels, List keysIn, DynamicQuery.Parameter... restrictions) { + // If keysIn is not null and empty, then search is over. + if ((keysIn != null) && (keysIn.isEmpty())) + return keysIn; + + if (tModels == null) + return keysIn; + + List tmodelKeys = tModels.getTModelKey(); + if (tmodelKeys == null || tmodelKeys.isEmpty()) + return keysIn; + + DynamicQuery dynamicQry = new DynamicQuery(selectSQL); + appendConditions(dynamicQry, fq, tmodelKeys); + + if (restrictions != null && restrictions.length > 0) + dynamicQry.AND().pad().appendGroupedAnd(restrictions); + + return getQueryResult(em, dynamicQry, keysIn, ENTITY_ALIAS + "." + KEY_NAME); + } + + + /* + * Appends the conditions to the query based on the tModelKey list. With the default or when "orAllKeys" is passed, the keyedReferences are autonomous and are + * all AND'd or OR'd respectively. + * + */ + public static void appendConditions(DynamicQuery qry, FindQualifiers fq, List tmodelKeys) { + + // Append the necessary tables (one will always be added connecting the entity to its instanceinfo table). + appendJoinTables(qry, fq, tmodelKeys); + qry.AND().pad().openParen().pad(); + + int count = 0; + int tblCount = -1; + for(String tmodelKey : tmodelKeys) { + + tblCount++; + String tmodelKeyTerm = (fq.isOrAllKeys()?entityAliasChild + "0":entityAliasChild + tblCount) + ".tmodelKey"; + qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS)); + + if (count + 1 < tmodelKeys.size()) { + if (fq.isOrAllKeys()) + qry.OR().pad(); + else + qry.AND().pad(); + } + + count++; + } + qry.closeParen().pad(); + + } + + /* + * Appends the necessary join table for the child entity and additional tables for when keys are AND'd. This is the default behavior + * so only need to add additional tables if "orAllKeys" has not been set. + */ + public static void appendJoinTables(DynamicQuery qry, FindQualifiers fq, List tmodelKeys) { + + + if (tmodelKeys != null && tmodelKeys.size() > 0) { + qry.comma().pad().append(BusinessServiceQuery.ENTITY_NAME + " " + BusinessServiceQuery.ENTITY_ALIAS).pad(); + qry.comma().pad().append(BindingTemplateQuery.ENTITY_NAME + " " + BindingTemplateQuery.ENTITY_ALIAS).pad(); + + StringBuilder thetaJoins = new StringBuilder(200); + int tblCount = 0; + for(int count = 0; count < tmodelKeys.size(); count++) { + if (count != 0) { + if (!fq.isOrAllKeys()) { + tblCount++; + qry.comma().pad().append(ENTITY_NAME_CHILD + " " + entityAliasChild + tblCount).pad(); + thetaJoins.append(entityAliasChild + (tblCount - 1) + "." + BindingTemplateQuery.ENTITY_FIELD + "." + BindingTemplateQuery.KEY_NAME + " = " + entityAliasChild + tblCount + "." + BindingTemplateQuery.ENTITY_FIELD + "." + BindingTemplateQuery.KEY_NAME + " "); + thetaJoins.append(DynamicQuery.OPERATOR_AND + " "); + } + } + else { + qry.comma().pad().append(ENTITY_NAME_CHILD + " " + entityAliasChild + tblCount).pad(); + thetaJoins.append(BindingTemplateQuery.ENTITY_ALIAS + "." + BindingTemplateQuery.KEY_NAME + " = " + entityAliasChild + tblCount + "." + BindingTemplateQuery.ENTITY_FIELD + "." + BindingTemplateQuery.KEY_NAME + " "); + thetaJoins.append(DynamicQuery.OPERATOR_AND + " "); + } + } + + qry.WHERE().pad().openParen().pad(); + + qry.append(ENTITY_ALIAS + "." + KEY_NAME + " = " + BusinessServiceQuery.ENTITY_ALIAS + "." + ENTITY_FIELD + "." + KEY_NAME).pad(); + qry.AND().pad().append(BusinessServiceQuery.ENTITY_ALIAS + "." + BusinessServiceQuery.KEY_NAME + " = " + BindingTemplateQuery.ENTITY_ALIAS + "." + BusinessServiceQuery.ENTITY_FIELD + "." + BusinessServiceQuery.KEY_NAME).pad(); + qry.AND().pad(); + + String thetaJoinsStr = thetaJoins.toString(); + if (thetaJoinsStr.endsWith(DynamicQuery.OPERATOR_AND + " ")) + thetaJoinsStr = thetaJoinsStr.substring(0, thetaJoinsStr.length() - (DynamicQuery.OPERATOR_AND + " ").length()); + qry.append(thetaJoinsStr); + + qry.closeParen().pad(); + if (fq!=null && fq.isSignaturePresent()) { + qry.AND().pad().openParen().pad().append(BusinessEntityQuery.SIGNATURE_PRESENT).pad().closeParen().pad(); + } + } + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindEntityByCategoryGroupQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindEntityByCategoryGroupQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindEntityByCategoryGroupQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindEntityByCategoryGroupQuery.java index 178e5f3d2..4a33144d3 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindEntityByCategoryGroupQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindEntityByCategoryGroupQuery.java @@ -1,325 +1,325 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.persistence.EntityManager; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.config.Constants; -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.apache.juddi.query.util.KeyedRefGroupTModelComparator; -import org.uddi.api_v3.CategoryBag; -import org.uddi.api_v3.KeyedReference; -import org.uddi.api_v3.KeyedReferenceGroup; - -/** - * Returns the list of "entity" keys possessing the keyedReferenceGroups in the passed category bag. - * Output is restricted by list of "entity" keys passed in. If null, all entities are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * NOTES: - * 1) Category groups are grouped with a logical AND by default. - * 2) Concerning when the categories are AND'd together - the only way this can be done with a single query was to create a self-join for - * each category. If there are a lot of categories, the performance could suffer. - * TODO: Test performance with multiple AND'd categories. If too slow, look to process this query in multiple steps. - * 3) The "orLikeKeys" qualifier complicates matters. The "like" keys are OR'd together and these groups of "like" keys are AND'd together. - * As with "andAllKeys", self-joins are created but only one for each group of "like" keys. If none of the keyedReferences passed are alike then this - * will reduce to an "andAllKeys" query. If all are alike, then this will query will exhibit the behavior of OR'ing all keys. - * - * @author Jeff Faath - */ -public class FindEntityByCategoryGroupQuery extends EntityQuery { - - @SuppressWarnings("unused") - private final static Log log = LogFactory.getLog(FindEntityByCategoryGroupQuery.class); - - private static final String ENTITY_KEYEDREFERENCEGROUP = "KeyedReferenceGroup"; - private static final String ALIAS_KEYEDREFERENCEGROUP = "krg"; - private static final String FIELD_CATEGORYBAG = "categoryBag"; - - private static final String ENTITY_KEYEDREFERENCE = "KeyedReference"; - private static final String ALIAS_KEYEDREFERENCE = buildAlias(ENTITY_KEYEDREFERENCE); - private static final String FIELD_KEYEDREFERENCEGROUP = "keyedReferenceGroup"; - - private final String entityName; - private final String entityAlias; - private final String keyName; - private final String entityField; - private final String entityNameChild; - private final String entityAliasChild; - private final String selectSQL; - private String signaturePresent; - - public FindEntityByCategoryGroupQuery(String entityName, String entityAlias, String keyName, - String entityField, String entityNameChild, String signaturePresent) { - this.entityName = entityName; - this.entityAlias = entityAlias; - this.keyName = keyName; - this.entityField = entityField; - this.entityNameChild = entityNameChild; - this.entityAliasChild = buildAlias(entityNameChild); - this.signaturePresent = signaturePresent; - - StringBuffer sql = new StringBuffer(200); - sql.append("select distinct " + entityAlias + "." + keyName + " from " - + entityName + " " + entityAlias + " , " - + entityNameChild + " " + entityAliasChild + " , " - + ENTITY_KEYEDREFERENCEGROUP + " " + ALIAS_KEYEDREFERENCEGROUP + " "); - selectSQL = sql.toString(); - } - - public String getEntityName() { - return entityName; - } - - public String getEntityAlias() { - return entityAlias; - } - - public String getKeyName() { - return keyName; - } - - public String getEntityField() { - return entityField; - } - - public String getEntityNameChild() { - return entityNameChild; - } - - public String getEntityAliasChild() { - return entityAliasChild; - } - - public String getSelectSQL() { - return selectSQL; - } - - public String getSignaturePresent() { - return signaturePresent; - } - - public void setSignaturePresent(String signaturePresent) { - this.signaturePresent = signaturePresent; - } - - @SuppressWarnings("unchecked") - public List select(EntityManager em, FindQualifiers fq, CategoryBag categoryBag, List keysIn, DynamicQuery.Parameter... restrictions) { - // If keysIn is not null and empty, then search is over. - if ((keysIn != null) && (keysIn.size() == 0)) - return keysIn; - - if (categoryBag == null) - return keysIn; - - List categories = categoryBag.getKeyedReferenceGroup(); - if (categories == null || categories.size() == 0) - return keysIn; - - List keyedRefGroups = new ArrayList(0); - for (KeyedReferenceGroup elem : categories) { - if (elem instanceof KeyedReferenceGroup) - keyedRefGroups.add((KeyedReferenceGroup)elem); - } - if (keyedRefGroups.size() == 0) - return keysIn; - - - Collections.sort(keyedRefGroups, new KeyedRefGroupTModelComparator()); - int count = 0; - String prevTModelKey = null; - Set orResults = new HashSet(0); - List restrictionList = keysIn; - List curResult = null; - for (KeyedReferenceGroup keyedRefGroup : keyedRefGroups) { - String curTModelKey = keyedRefGroup.getTModelKey(); - - DynamicQuery dynamicQry = new DynamicQuery(selectSQL); - appendConditions(dynamicQry, fq, keyedRefGroup); - if (restrictions != null && restrictions.length > 0) - dynamicQry.AND().pad().appendGroupedAnd(restrictions); - - - if (fq.isOrLikeKeys()) { - if (!curTModelKey.equals(prevTModelKey)) { - if (count != 0) { - restrictionList = new ArrayList(orResults); - orResults.clear(); - } - } - } - else if (!fq.isOrAllKeys()) { - if (count != 0) - restrictionList = curResult; - } - - if (restrictionList != null && restrictionList.size() == 0) - break; - - curResult = getQueryResult(em, dynamicQry, restrictionList, entityAlias + "." + keyName); - - if (fq.isOrAllKeys() || fq.isOrLikeKeys()) { - orResults.addAll((List)curResult); - } - - prevTModelKey = curTModelKey; - count++; - } - - List result = null; - if (fq.isOrAllKeys() || fq.isOrLikeKeys()) { - result = new ArrayList(0); - result.addAll(orResults); - } - else - result = (List)curResult; - - return result; - - } - - /* - * Appends the conditions to the query based on the keyedReferenceGroup. According to the specification, a keyedReference group matches if all - * keyedReferences within the group are a subset of the target entity's group. Thus, - */ - public void appendConditions(DynamicQuery qry, FindQualifiers fq, KeyedReferenceGroup keyedRefGroup) { - - // Append the necessary tables (two will always be added connecting the entity to its category bag table and then the category table to the keyed reference group). - appendJoinTables(qry, fq, keyedRefGroup); - - // First, appending the group's tmodel key as a condition - qry.AND().pad().appendGroupedAnd(new DynamicQuery.Parameter(ALIAS_KEYEDREFERENCEGROUP + ".tmodelKey", keyedRefGroup.getTModelKey(), DynamicQuery.PREDICATE_EQUALS)); - - List keyedRefs = keyedRefGroup.getKeyedReference(); - if (keyedRefs != null && keyedRefs.size() > 0) { - - qry.AND().pad().openParen().pad(); - - String predicate = DynamicQuery.PREDICATE_EQUALS; - if (fq.isApproximateMatch()) { - predicate = DynamicQuery.PREDICATE_LIKE; - } - - int count = 0; - int tblCount = -1; - for(KeyedReference keyedRef : keyedRefs) { - String tmodelKey = keyedRef.getTModelKey(); - String keyValue = keyedRef.getKeyValue(); - String keyName = keyedRef.getKeyName(); - - if (fq.isApproximateMatch()) { - // JUDDI-235: wildcards are provided by user (only commenting in case a new interpretation arises) - //keyValue = keyValue.endsWith(DynamicQuery.WILDCARD)?keyValue:keyValue + DynamicQuery.WILDCARD; - //keyName = keyName.endsWith(DynamicQuery.WILDCARD)?keyName:keyName + DynamicQuery.WILDCARD; - } - - tblCount++; - String keyValueTerm = ALIAS_KEYEDREFERENCE + tblCount + ".keyValue"; - String keyNameTerm = ALIAS_KEYEDREFERENCE + tblCount + ".keyName"; - String tmodelKeyTerm = ALIAS_KEYEDREFERENCE + tblCount + ".tmodelKeyRef"; - if (fq.isCaseInsensitiveMatch()) { - keyValueTerm = "upper(" + keyValueTerm + ")"; - keyValue = keyValue.toUpperCase(); - - keyNameTerm = "upper(" + keyNameTerm + ")"; - keyName = keyName.toUpperCase(); - } - - // According to specification, if the "general keyword" tmodel is used, then the keyName must be part of the query. - if (Constants.GENERAL_KEYWORD_TMODEL.equalsIgnoreCase(tmodelKey)) { - qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS), - new DynamicQuery.Parameter(keyValueTerm, keyValue, predicate), - new DynamicQuery.Parameter(keyNameTerm, keyName, predicate)); - } - else { - qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS), - new DynamicQuery.Parameter(keyValueTerm, keyValue, predicate)); - - } - - if (count + 1 < keyedRefs.size()) - qry.AND().pad(); - - count++; - } - qry.closeParen().pad(); - } - - } - - - - /* - * Appends the necessary join table for the child entity and additional tables for when keys are AND'd. When "orLikeKeys" is used, - * we only need an extra table for each distinct tmodelKey. - */ - public void appendJoinTables(DynamicQuery qry, FindQualifiers fq, KeyedReferenceGroup keyedRefGroup) { - - if (keyedRefGroup != null) { - - List keyedRefs = keyedRefGroup.getKeyedReference(); - StringBuffer thetaJoins = new StringBuffer(200); - if (keyedRefs != null && keyedRefs.size() > 0) { - int tblCount = 0; - for(int count = 0; count 0) - qry.AND().pad(); - - if (thetaJoinsStr.endsWith(DynamicQuery.OPERATOR_AND + " ")) - thetaJoinsStr = thetaJoinsStr.substring(0, thetaJoinsStr.length() - (DynamicQuery.OPERATOR_AND + " ").length()); - qry.append(thetaJoinsStr); - - qry.closeParen().pad(); - if (fq!=null && fq.isSignaturePresent()) { - qry.AND().pad().openParen().pad().append(getSignaturePresent()).pad().closeParen().pad(); - } - } - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.persistence.EntityManager; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.config.Constants; +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.apache.juddi.query.util.KeyedRefGroupTModelComparator; +import org.uddi.api_v3.CategoryBag; +import org.uddi.api_v3.KeyedReference; +import org.uddi.api_v3.KeyedReferenceGroup; + +/** + * Returns the list of "entity" keys possessing the keyedReferenceGroups in the passed category bag. + * Output is restricted by list of "entity" keys passed in. If null, all entities are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * NOTES: + * 1) Category groups are grouped with a logical AND by default. + * 2) Concerning when the categories are AND'd together - the only way this can be done with a single query was to create a self-join for + * each category. If there are a lot of categories, the performance could suffer. + * TODO: Test performance with multiple AND'd categories. If too slow, look to process this query in multiple steps. + * 3) The "orLikeKeys" qualifier complicates matters. The "like" keys are OR'd together and these groups of "like" keys are AND'd together. + * As with "andAllKeys", self-joins are created but only one for each group of "like" keys. If none of the keyedReferences passed are alike then this + * will reduce to an "andAllKeys" query. If all are alike, then this will query will exhibit the behavior of OR'ing all keys. + * + * @author Jeff Faath + */ +public class FindEntityByCategoryGroupQuery extends EntityQuery { + + @SuppressWarnings("unused") + private final static Log log = LogFactory.getLog(FindEntityByCategoryGroupQuery.class); + + private static final String ENTITY_KEYEDREFERENCEGROUP = "KeyedReferenceGroup"; + private static final String ALIAS_KEYEDREFERENCEGROUP = "krg"; + private static final String FIELD_CATEGORYBAG = "categoryBag"; + + private static final String ENTITY_KEYEDREFERENCE = "KeyedReference"; + private static final String ALIAS_KEYEDREFERENCE = buildAlias(ENTITY_KEYEDREFERENCE); + private static final String FIELD_KEYEDREFERENCEGROUP = "keyedReferenceGroup"; + + private final String entityName; + private final String entityAlias; + private final String keyName; + private final String entityField; + private final String entityNameChild; + private final String entityAliasChild; + private final String selectSQL; + private String signaturePresent; + + public FindEntityByCategoryGroupQuery(String entityName, String entityAlias, String keyName, + String entityField, String entityNameChild, String signaturePresent) { + this.entityName = entityName; + this.entityAlias = entityAlias; + this.keyName = keyName; + this.entityField = entityField; + this.entityNameChild = entityNameChild; + this.entityAliasChild = buildAlias(entityNameChild); + this.signaturePresent = signaturePresent; + + StringBuffer sql = new StringBuffer(200); + sql.append("select distinct " + entityAlias + "." + keyName + " from " + + entityName + " " + entityAlias + " , " + + entityNameChild + " " + entityAliasChild + " , " + + ENTITY_KEYEDREFERENCEGROUP + " " + ALIAS_KEYEDREFERENCEGROUP + " "); + selectSQL = sql.toString(); + } + + public String getEntityName() { + return entityName; + } + + public String getEntityAlias() { + return entityAlias; + } + + public String getKeyName() { + return keyName; + } + + public String getEntityField() { + return entityField; + } + + public String getEntityNameChild() { + return entityNameChild; + } + + public String getEntityAliasChild() { + return entityAliasChild; + } + + public String getSelectSQL() { + return selectSQL; + } + + public String getSignaturePresent() { + return signaturePresent; + } + + public void setSignaturePresent(String signaturePresent) { + this.signaturePresent = signaturePresent; + } + + @SuppressWarnings("unchecked") + public List select(EntityManager em, FindQualifiers fq, CategoryBag categoryBag, List keysIn, DynamicQuery.Parameter... restrictions) { + // If keysIn is not null and empty, then search is over. + if ((keysIn != null) && (keysIn.size() == 0)) + return keysIn; + + if (categoryBag == null) + return keysIn; + + List categories = categoryBag.getKeyedReferenceGroup(); + if (categories == null || categories.size() == 0) + return keysIn; + + List keyedRefGroups = new ArrayList(0); + for (KeyedReferenceGroup elem : categories) { + if (elem instanceof KeyedReferenceGroup) + keyedRefGroups.add((KeyedReferenceGroup)elem); + } + if (keyedRefGroups.size() == 0) + return keysIn; + + + Collections.sort(keyedRefGroups, new KeyedRefGroupTModelComparator()); + int count = 0; + String prevTModelKey = null; + Set orResults = new HashSet(0); + List restrictionList = keysIn; + List curResult = null; + for (KeyedReferenceGroup keyedRefGroup : keyedRefGroups) { + String curTModelKey = keyedRefGroup.getTModelKey(); + + DynamicQuery dynamicQry = new DynamicQuery(selectSQL); + appendConditions(dynamicQry, fq, keyedRefGroup); + if (restrictions != null && restrictions.length > 0) + dynamicQry.AND().pad().appendGroupedAnd(restrictions); + + + if (fq.isOrLikeKeys()) { + if (!curTModelKey.equals(prevTModelKey)) { + if (count != 0) { + restrictionList = new ArrayList(orResults); + orResults.clear(); + } + } + } + else if (!fq.isOrAllKeys()) { + if (count != 0) + restrictionList = curResult; + } + + if (restrictionList != null && restrictionList.size() == 0) + break; + + curResult = getQueryResult(em, dynamicQry, restrictionList, entityAlias + "." + keyName); + + if (fq.isOrAllKeys() || fq.isOrLikeKeys()) { + orResults.addAll((List)curResult); + } + + prevTModelKey = curTModelKey; + count++; + } + + List result = null; + if (fq.isOrAllKeys() || fq.isOrLikeKeys()) { + result = new ArrayList(0); + result.addAll(orResults); + } + else + result = (List)curResult; + + return result; + + } + + /* + * Appends the conditions to the query based on the keyedReferenceGroup. According to the specification, a keyedReference group matches if all + * keyedReferences within the group are a subset of the target entity's group. Thus, + */ + public void appendConditions(DynamicQuery qry, FindQualifiers fq, KeyedReferenceGroup keyedRefGroup) { + + // Append the necessary tables (two will always be added connecting the entity to its category bag table and then the category table to the keyed reference group). + appendJoinTables(qry, fq, keyedRefGroup); + + // First, appending the group's tmodel key as a condition + qry.AND().pad().appendGroupedAnd(new DynamicQuery.Parameter(ALIAS_KEYEDREFERENCEGROUP + ".tmodelKey", keyedRefGroup.getTModelKey(), DynamicQuery.PREDICATE_EQUALS)); + + List keyedRefs = keyedRefGroup.getKeyedReference(); + if (keyedRefs != null && keyedRefs.size() > 0) { + + qry.AND().pad().openParen().pad(); + + String predicate = DynamicQuery.PREDICATE_EQUALS; + if (fq.isApproximateMatch()) { + predicate = DynamicQuery.PREDICATE_LIKE; + } + + int count = 0; + int tblCount = -1; + for(KeyedReference keyedRef : keyedRefs) { + String tmodelKey = keyedRef.getTModelKey(); + String keyValue = keyedRef.getKeyValue(); + String keyName = keyedRef.getKeyName(); + + if (fq.isApproximateMatch()) { + // JUDDI-235: wildcards are provided by user (only commenting in case a new interpretation arises) + //keyValue = keyValue.endsWith(DynamicQuery.WILDCARD)?keyValue:keyValue + DynamicQuery.WILDCARD; + //keyName = keyName.endsWith(DynamicQuery.WILDCARD)?keyName:keyName + DynamicQuery.WILDCARD; + } + + tblCount++; + String keyValueTerm = ALIAS_KEYEDREFERENCE + tblCount + ".keyValue"; + String keyNameTerm = ALIAS_KEYEDREFERENCE + tblCount + ".keyName"; + String tmodelKeyTerm = ALIAS_KEYEDREFERENCE + tblCount + ".tmodelKeyRef"; + if (fq.isCaseInsensitiveMatch()) { + keyValueTerm = "upper(" + keyValueTerm + ")"; + keyValue = keyValue.toUpperCase(); + + keyNameTerm = "upper(" + keyNameTerm + ")"; + keyName = keyName.toUpperCase(); + } + + // According to specification, if the "general keyword" tmodel is used, then the keyName must be part of the query. + if (Constants.GENERAL_KEYWORD_TMODEL.equalsIgnoreCase(tmodelKey)) { + qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS), + new DynamicQuery.Parameter(keyValueTerm, keyValue, predicate), + new DynamicQuery.Parameter(keyNameTerm, keyName, predicate)); + } + else { + qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS), + new DynamicQuery.Parameter(keyValueTerm, keyValue, predicate)); + + } + + if (count + 1 < keyedRefs.size()) + qry.AND().pad(); + + count++; + } + qry.closeParen().pad(); + } + + } + + + + /* + * Appends the necessary join table for the child entity and additional tables for when keys are AND'd. When "orLikeKeys" is used, + * we only need an extra table for each distinct tmodelKey. + */ + public void appendJoinTables(DynamicQuery qry, FindQualifiers fq, KeyedReferenceGroup keyedRefGroup) { + + if (keyedRefGroup != null) { + + List keyedRefs = keyedRefGroup.getKeyedReference(); + StringBuffer thetaJoins = new StringBuffer(200); + if (keyedRefs != null && keyedRefs.size() > 0) { + int tblCount = 0; + for(int count = 0; count 0) + qry.AND().pad(); + + if (thetaJoinsStr.endsWith(DynamicQuery.OPERATOR_AND + " ")) + thetaJoinsStr = thetaJoinsStr.substring(0, thetaJoinsStr.length() - (DynamicQuery.OPERATOR_AND + " ").length()); + qry.append(thetaJoinsStr); + + qry.closeParen().pad(); + if (fq!=null && fq.isSignaturePresent()) { + qry.AND().pad().openParen().pad().append(getSignaturePresent()).pad().closeParen().pad(); + } + } + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindEntityByCategoryQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindEntityByCategoryQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindEntityByCategoryQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindEntityByCategoryQuery.java index 0f7910eac..967e72c15 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindEntityByCategoryQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindEntityByCategoryQuery.java @@ -1,308 +1,308 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.persistence.EntityManager; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.config.Constants; -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.apache.juddi.query.util.KeyedRefTModelComparator; -import org.uddi.api_v3.CategoryBag; -import org.uddi.api_v3.KeyedReference; - -/** - * Returns the list of "entity" keys possessing the keyedReferences in the passed category bag. - * Output is restricted by list of "entity" keys passed in. If null, all entities are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * NOTES: - * 1) Categories are grouped with a logical AND by default. - * 2) Concerning when the categories are AND'd together - the only way this can be done with a single query was to create a self-join for - * each category. If there are a lot of categories, the performance could suffer. - * TODO: Test performance with multiple AND'd categories. If too slow, look to process this query in multiple steps. - * 3) The "orLikeKeys" qualifier complicates matters. The "like" keys are OR'd together and these groups of "like" keys are AND'd together. - * As with "andAllKeys", self-joins are created but only one for each group of "like" keys. If none of the keyedReferences passed are alike then this - * will reduce to an "andAllKeys" query. If all are alike, then this will query will exhibit the behavior of OR'ing all keys. - * - * @author Jeff Faath - */ -public class FindEntityByCategoryQuery extends EntityQuery { - - @SuppressWarnings("unused") - private final static Log log = LogFactory.getLog(FindEntityByCategoryQuery.class); - - private static final String ENTITY_KEYEDREFERENCE = "KeyedReference"; - private static final String ALIAS_KEYEDREFERENCE = buildAlias(ENTITY_KEYEDREFERENCE); - private static final String FIELD_CATEGORYBAG = "categoryBag"; - - protected String entityName; - protected String entityAlias; - protected String keyName; - protected String entityField; - protected String entityNameChild; - protected String entityAliasChild; - protected String selectSQL; - protected String signaturePresent; - - public FindEntityByCategoryQuery(String entityName, String entityAlias, String keyName, - String entityField, String entityNameChild, String signaturePresent) { - this.entityName = entityName; - this.entityAlias = entityAlias; - this.keyName = keyName; - this.entityField = entityField; - this.entityNameChild = entityNameChild; - this.entityAliasChild = buildAlias(entityNameChild); - this.signaturePresent = signaturePresent; - - StringBuffer sql = new StringBuffer(200); - sql.append("select distinct " + entityAlias + "." + keyName + " from " + entityName + " " + entityAlias + " , " + entityNameChild + " " + entityAliasChild + " "); - selectSQL = sql.toString(); - } - - public String getEntityName() { - return entityName; - } - - public String getEntityAlias() { - return entityAlias; - } - - public String getKeyName() { - return keyName; - } - - public String getEntityField() { - return entityField; - } - - public String getEntityNameChild() { - return entityNameChild; - } - - public String getEntityAliasChild() { - return entityAliasChild; - } - - public String getSelectSQL() { - return selectSQL; - } - - public String getSignaturePresent() { - return signaturePresent; - } - - public void setSignaturePresent(String signaturePresent) { - this.signaturePresent = signaturePresent; - } - - public List select(EntityManager em, FindQualifiers fq, CategoryBag categoryBag, List keysIn, DynamicQuery.Parameter... restrictions) { - // If keysIn is not null and empty, then search is over. - if ((keysIn != null) && (keysIn.size() == 0)) - return keysIn; - - if (categoryBag == null) - return keysIn; - - List categories = categoryBag.getKeyedReference(); - if (categories == null || categories.size() == 0) - return keysIn; - - List keyedRefs = new ArrayList(0); - for (KeyedReference elem : categories) { - if (elem instanceof KeyedReference) - keyedRefs.add((KeyedReference)elem); - } - if (keyedRefs.isEmpty()) - return keysIn; - - DynamicQuery dynamicQry = new DynamicQuery(selectSQL); - appendConditions(dynamicQry, fq, keyedRefs); - if (restrictions != null && restrictions.length > 0) - dynamicQry.AND().pad().appendGroupedAnd(restrictions); - - return getQueryResult(em, dynamicQry, keysIn, entityAlias + "." + keyName); - } - - - /* - * Appends the conditions to the query based on the keyedReference list. With the default or when "orAllKeys" is passed, the keyedReferences are autonomous and are - * all AND'd or OR'd respectively. However, "orLikeKeys" requires special treatment. The goal is to create the conditions in this format: - * - * (likeKey1 = X or likeKey1 = Y) and (likeKey2 = A or likeKey2 = B or likeKey2 = C) - * - * ie. the "like" KeyedReferences are OR'd and the groups of "like" KeyedReferences are AND'd with each other. - */ - public void appendConditions(DynamicQuery qry, FindQualifiers fq, List keyedRefs) { - - // Append the necessary tables (two will always be added connecting the entity to its category table and then the category table to the keyed references). - appendJoinTables(qry, fq, keyedRefs); - qry.AND().pad().openParen().pad(); - - String predicate = DynamicQuery.PREDICATE_EQUALS; - if (fq.isApproximateMatch()) { - predicate = DynamicQuery.PREDICATE_LIKE; - } - - // Sorting the collection by tModel Key - Collections.sort(keyedRefs, new KeyedRefTModelComparator()); - - String prevTModelKey = null; - int count = 0; - int tblCount = -1; - for(KeyedReference keyedRef : keyedRefs) { - String tmodelKey = keyedRef.getTModelKey(); - String keyValue = keyedRef.getKeyValue(); - String keyName = keyedRef.getKeyName(); - - if (fq.isApproximateMatch()) { - // JUDDI-235: wildcards are provided by user (only commenting in case a new interpretation arises) - //keyValue = keyValue.endsWith(DynamicQuery.WILDCARD)?keyValue:keyValue + DynamicQuery.WILDCARD; - //keyName = keyName.endsWith(DynamicQuery.WILDCARD)?keyName:keyName + DynamicQuery.WILDCARD; - } - - // Either opening up (and AND'ing) a new "group" of like keys or simply appending an "or". If this is not "orLikeKeys", then just need to increment - // the table count. - if (fq.isOrLikeKeys()) { - if (count == 0) { - qry.openParen().pad(); - tblCount++; - } - else { - if (!tmodelKey.equals(prevTModelKey)) { - qry.closeParen().pad().AND().pad().openParen().pad(); - tblCount++; - } - else - qry.OR().pad(); - } - } - else - tblCount++; - - String keyValueTerm = (fq.isOrAllKeys()?ALIAS_KEYEDREFERENCE + "0":ALIAS_KEYEDREFERENCE + tblCount) + ".keyValue"; - String keyNameTerm = (fq.isOrAllKeys()?ALIAS_KEYEDREFERENCE + "0":ALIAS_KEYEDREFERENCE + tblCount) + ".keyName"; - String tmodelKeyTerm = (fq.isOrAllKeys()?ALIAS_KEYEDREFERENCE + "0":ALIAS_KEYEDREFERENCE + tblCount) + ".tmodelKeyRef"; - if (fq.isCaseInsensitiveMatch()) { - keyValueTerm = "upper(" + keyValueTerm + ")"; - keyValue = keyValue.toUpperCase(); - - keyNameTerm = "upper(" + keyNameTerm + ")"; - keyName = keyName.toUpperCase(); - } - - - // According to specification, if the "general keyword" tmodel is used, then the keyName must be part of the query. - if (Constants.GENERAL_KEYWORD_TMODEL.equalsIgnoreCase(tmodelKey)) { - qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS), - new DynamicQuery.Parameter(keyValueTerm, keyValue, predicate), - new DynamicQuery.Parameter(keyNameTerm, keyName, predicate)); - } - else { - qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS), - new DynamicQuery.Parameter(keyValueTerm, keyValue, predicate)); - - } - - if (count + 1 < keyedRefs.size()) { - if (fq.isOrAllKeys()) - qry.OR().pad(); - else if (fq.isOrLikeKeys()) { - } - else - qry.AND().pad(); - } - - // The "orLikeKeys" will always leave an unclosed parenthesis. This will close it. - if (fq.isOrLikeKeys() && (count + 1 == keyedRefs.size())) - qry.closeParen().pad(); - - prevTModelKey = tmodelKey; - count++; - } - qry.closeParen().pad(); - - } - - - - /* - * Appends the necessary join table for the child entity and additional tables for when keys are AND'd. When "orLikeKeys" is used, - * we only need an extra table for each distinct tmodelKey. - */ - public void appendJoinTables(DynamicQuery qry, FindQualifiers fq, List keyedRefs) { - - if (keyedRefs != null && keyedRefs.size() > 0) { - // Sorting the collection by tModel Key - Collections.sort(keyedRefs, new KeyedRefTModelComparator()); - - StringBuffer thetaJoins = new StringBuffer(200); - int tblCount = 0; - int count = 0; - String curTModelKey = null; - String prevTModelKey = null; - for(KeyedReference kr : keyedRefs) { - curTModelKey = kr.getTModelKey(); - if (count != 0) { - if (!fq.isOrAllKeys()) { - if (fq.isOrLikeKeys() && curTModelKey.equals(prevTModelKey)) { - // Do nothing - } - else { - tblCount++; - qry.comma().pad().append(ENTITY_KEYEDREFERENCE + " " + ALIAS_KEYEDREFERENCE + tblCount).pad(); - thetaJoins.append(ALIAS_KEYEDREFERENCE + (tblCount - 1) + "." + FIELD_CATEGORYBAG + ".id = " + ALIAS_KEYEDREFERENCE + tblCount + "." + FIELD_CATEGORYBAG + ".id "); - thetaJoins.append(DynamicQuery.OPERATOR_AND + " "); - } - } - - } - else { - qry.comma().pad().append(ENTITY_KEYEDREFERENCE + " " + ALIAS_KEYEDREFERENCE + tblCount).pad(); - thetaJoins.append(entityAliasChild + ".id = " + ALIAS_KEYEDREFERENCE + tblCount + "." + FIELD_CATEGORYBAG + ".id "); - thetaJoins.append(DynamicQuery.OPERATOR_AND + " "); - } - prevTModelKey = curTModelKey; - count++; - } - - qry.WHERE().pad().openParen().pad(); - - // Appending the middling entity-specific category table condition - qry.append(entityAlias + "." + keyName + " = " + entityAliasChild + "." + entityField + "." + KEY_NAME).pad(); - qry.AND().pad(); - - String thetaJoinsStr = thetaJoins.toString(); - if (thetaJoinsStr.endsWith(DynamicQuery.OPERATOR_AND + " ")) - thetaJoinsStr = thetaJoinsStr.substring(0, thetaJoinsStr.length() - (DynamicQuery.OPERATOR_AND + " ").length()); - qry.append(thetaJoinsStr); - - qry.closeParen().pad(); - if (fq!=null && fq.isSignaturePresent()) { - qry.AND().pad().openParen().pad().append(getSignaturePresent()).pad().closeParen().pad(); - } - } - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.persistence.EntityManager; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.config.Constants; +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.apache.juddi.query.util.KeyedRefTModelComparator; +import org.uddi.api_v3.CategoryBag; +import org.uddi.api_v3.KeyedReference; + +/** + * Returns the list of "entity" keys possessing the keyedReferences in the passed category bag. + * Output is restricted by list of "entity" keys passed in. If null, all entities are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * NOTES: + * 1) Categories are grouped with a logical AND by default. + * 2) Concerning when the categories are AND'd together - the only way this can be done with a single query was to create a self-join for + * each category. If there are a lot of categories, the performance could suffer. + * TODO: Test performance with multiple AND'd categories. If too slow, look to process this query in multiple steps. + * 3) The "orLikeKeys" qualifier complicates matters. The "like" keys are OR'd together and these groups of "like" keys are AND'd together. + * As with "andAllKeys", self-joins are created but only one for each group of "like" keys. If none of the keyedReferences passed are alike then this + * will reduce to an "andAllKeys" query. If all are alike, then this will query will exhibit the behavior of OR'ing all keys. + * + * @author Jeff Faath + */ +public class FindEntityByCategoryQuery extends EntityQuery { + + @SuppressWarnings("unused") + private final static Log log = LogFactory.getLog(FindEntityByCategoryQuery.class); + + private static final String ENTITY_KEYEDREFERENCE = "KeyedReference"; + private static final String ALIAS_KEYEDREFERENCE = buildAlias(ENTITY_KEYEDREFERENCE); + private static final String FIELD_CATEGORYBAG = "categoryBag"; + + protected String entityName; + protected String entityAlias; + protected String keyName; + protected String entityField; + protected String entityNameChild; + protected String entityAliasChild; + protected String selectSQL; + protected String signaturePresent; + + public FindEntityByCategoryQuery(String entityName, String entityAlias, String keyName, + String entityField, String entityNameChild, String signaturePresent) { + this.entityName = entityName; + this.entityAlias = entityAlias; + this.keyName = keyName; + this.entityField = entityField; + this.entityNameChild = entityNameChild; + this.entityAliasChild = buildAlias(entityNameChild); + this.signaturePresent = signaturePresent; + + StringBuffer sql = new StringBuffer(200); + sql.append("select distinct " + entityAlias + "." + keyName + " from " + entityName + " " + entityAlias + " , " + entityNameChild + " " + entityAliasChild + " "); + selectSQL = sql.toString(); + } + + public String getEntityName() { + return entityName; + } + + public String getEntityAlias() { + return entityAlias; + } + + public String getKeyName() { + return keyName; + } + + public String getEntityField() { + return entityField; + } + + public String getEntityNameChild() { + return entityNameChild; + } + + public String getEntityAliasChild() { + return entityAliasChild; + } + + public String getSelectSQL() { + return selectSQL; + } + + public String getSignaturePresent() { + return signaturePresent; + } + + public void setSignaturePresent(String signaturePresent) { + this.signaturePresent = signaturePresent; + } + + public List select(EntityManager em, FindQualifiers fq, CategoryBag categoryBag, List keysIn, DynamicQuery.Parameter... restrictions) { + // If keysIn is not null and empty, then search is over. + if ((keysIn != null) && (keysIn.size() == 0)) + return keysIn; + + if (categoryBag == null) + return keysIn; + + List categories = categoryBag.getKeyedReference(); + if (categories == null || categories.size() == 0) + return keysIn; + + List keyedRefs = new ArrayList(0); + for (KeyedReference elem : categories) { + if (elem instanceof KeyedReference) + keyedRefs.add((KeyedReference)elem); + } + if (keyedRefs.isEmpty()) + return keysIn; + + DynamicQuery dynamicQry = new DynamicQuery(selectSQL); + appendConditions(dynamicQry, fq, keyedRefs); + if (restrictions != null && restrictions.length > 0) + dynamicQry.AND().pad().appendGroupedAnd(restrictions); + + return getQueryResult(em, dynamicQry, keysIn, entityAlias + "." + keyName); + } + + + /* + * Appends the conditions to the query based on the keyedReference list. With the default or when "orAllKeys" is passed, the keyedReferences are autonomous and are + * all AND'd or OR'd respectively. However, "orLikeKeys" requires special treatment. The goal is to create the conditions in this format: + * + * (likeKey1 = X or likeKey1 = Y) and (likeKey2 = A or likeKey2 = B or likeKey2 = C) + * + * ie. the "like" KeyedReferences are OR'd and the groups of "like" KeyedReferences are AND'd with each other. + */ + public void appendConditions(DynamicQuery qry, FindQualifiers fq, List keyedRefs) { + + // Append the necessary tables (two will always be added connecting the entity to its category table and then the category table to the keyed references). + appendJoinTables(qry, fq, keyedRefs); + qry.AND().pad().openParen().pad(); + + String predicate = DynamicQuery.PREDICATE_EQUALS; + if (fq.isApproximateMatch()) { + predicate = DynamicQuery.PREDICATE_LIKE; + } + + // Sorting the collection by tModel Key + Collections.sort(keyedRefs, new KeyedRefTModelComparator()); + + String prevTModelKey = null; + int count = 0; + int tblCount = -1; + for(KeyedReference keyedRef : keyedRefs) { + String tmodelKey = keyedRef.getTModelKey(); + String keyValue = keyedRef.getKeyValue(); + String keyName = keyedRef.getKeyName(); + + if (fq.isApproximateMatch()) { + // JUDDI-235: wildcards are provided by user (only commenting in case a new interpretation arises) + //keyValue = keyValue.endsWith(DynamicQuery.WILDCARD)?keyValue:keyValue + DynamicQuery.WILDCARD; + //keyName = keyName.endsWith(DynamicQuery.WILDCARD)?keyName:keyName + DynamicQuery.WILDCARD; + } + + // Either opening up (and AND'ing) a new "group" of like keys or simply appending an "or". If this is not "orLikeKeys", then just need to increment + // the table count. + if (fq.isOrLikeKeys()) { + if (count == 0) { + qry.openParen().pad(); + tblCount++; + } + else { + if (!tmodelKey.equals(prevTModelKey)) { + qry.closeParen().pad().AND().pad().openParen().pad(); + tblCount++; + } + else + qry.OR().pad(); + } + } + else + tblCount++; + + String keyValueTerm = (fq.isOrAllKeys()?ALIAS_KEYEDREFERENCE + "0":ALIAS_KEYEDREFERENCE + tblCount) + ".keyValue"; + String keyNameTerm = (fq.isOrAllKeys()?ALIAS_KEYEDREFERENCE + "0":ALIAS_KEYEDREFERENCE + tblCount) + ".keyName"; + String tmodelKeyTerm = (fq.isOrAllKeys()?ALIAS_KEYEDREFERENCE + "0":ALIAS_KEYEDREFERENCE + tblCount) + ".tmodelKeyRef"; + if (fq.isCaseInsensitiveMatch()) { + keyValueTerm = "upper(" + keyValueTerm + ")"; + keyValue = keyValue.toUpperCase(); + + keyNameTerm = "upper(" + keyNameTerm + ")"; + keyName = keyName.toUpperCase(); + } + + + // According to specification, if the "general keyword" tmodel is used, then the keyName must be part of the query. + if (Constants.GENERAL_KEYWORD_TMODEL.equalsIgnoreCase(tmodelKey)) { + qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS), + new DynamicQuery.Parameter(keyValueTerm, keyValue, predicate), + new DynamicQuery.Parameter(keyNameTerm, keyName, predicate)); + } + else { + qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS), + new DynamicQuery.Parameter(keyValueTerm, keyValue, predicate)); + + } + + if (count + 1 < keyedRefs.size()) { + if (fq.isOrAllKeys()) + qry.OR().pad(); + else if (fq.isOrLikeKeys()) { + } + else + qry.AND().pad(); + } + + // The "orLikeKeys" will always leave an unclosed parenthesis. This will close it. + if (fq.isOrLikeKeys() && (count + 1 == keyedRefs.size())) + qry.closeParen().pad(); + + prevTModelKey = tmodelKey; + count++; + } + qry.closeParen().pad(); + + } + + + + /* + * Appends the necessary join table for the child entity and additional tables for when keys are AND'd. When "orLikeKeys" is used, + * we only need an extra table for each distinct tmodelKey. + */ + public void appendJoinTables(DynamicQuery qry, FindQualifiers fq, List keyedRefs) { + + if (keyedRefs != null && keyedRefs.size() > 0) { + // Sorting the collection by tModel Key + Collections.sort(keyedRefs, new KeyedRefTModelComparator()); + + StringBuffer thetaJoins = new StringBuffer(200); + int tblCount = 0; + int count = 0; + String curTModelKey = null; + String prevTModelKey = null; + for(KeyedReference kr : keyedRefs) { + curTModelKey = kr.getTModelKey(); + if (count != 0) { + if (!fq.isOrAllKeys()) { + if (fq.isOrLikeKeys() && curTModelKey.equals(prevTModelKey)) { + // Do nothing + } + else { + tblCount++; + qry.comma().pad().append(ENTITY_KEYEDREFERENCE + " " + ALIAS_KEYEDREFERENCE + tblCount).pad(); + thetaJoins.append(ALIAS_KEYEDREFERENCE + (tblCount - 1) + "." + FIELD_CATEGORYBAG + ".id = " + ALIAS_KEYEDREFERENCE + tblCount + "." + FIELD_CATEGORYBAG + ".id "); + thetaJoins.append(DynamicQuery.OPERATOR_AND + " "); + } + } + + } + else { + qry.comma().pad().append(ENTITY_KEYEDREFERENCE + " " + ALIAS_KEYEDREFERENCE + tblCount).pad(); + thetaJoins.append(entityAliasChild + ".id = " + ALIAS_KEYEDREFERENCE + tblCount + "." + FIELD_CATEGORYBAG + ".id "); + thetaJoins.append(DynamicQuery.OPERATOR_AND + " "); + } + prevTModelKey = curTModelKey; + count++; + } + + qry.WHERE().pad().openParen().pad(); + + // Appending the middling entity-specific category table condition + qry.append(entityAlias + "." + keyName + " = " + entityAliasChild + "." + entityField + "." + KEY_NAME).pad(); + qry.AND().pad(); + + String thetaJoinsStr = thetaJoins.toString(); + if (thetaJoinsStr.endsWith(DynamicQuery.OPERATOR_AND + " ")) + thetaJoinsStr = thetaJoinsStr.substring(0, thetaJoinsStr.length() - (DynamicQuery.OPERATOR_AND + " ").length()); + qry.append(thetaJoinsStr); + + qry.closeParen().pad(); + if (fq!=null && fq.isSignaturePresent()) { + qry.AND().pad().openParen().pad().append(getSignaturePresent()).pad().closeParen().pad(); + } + } + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindEntityByCombinedCategoryQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindEntityByCombinedCategoryQuery.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/query/FindEntityByCombinedCategoryQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindEntityByCombinedCategoryQuery.java diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindEntityByIdentifierQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindEntityByIdentifierQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindEntityByIdentifierQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindEntityByIdentifierQuery.java index d520b3378..e506f0312 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindEntityByIdentifierQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindEntityByIdentifierQuery.java @@ -1,288 +1,288 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.Collections; -import java.util.List; - -import javax.persistence.EntityManager; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.config.Constants; -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.apache.juddi.query.util.KeyedRefTModelComparator; -import org.uddi.api_v3.IdentifierBag; -import org.uddi.api_v3.KeyedReference; - -/** - * Returns the list of "entity" keys possessing the keyedReferences in the passed identifier bag. - * Output is restricted by list of "entity" keys passed in. If null, all entities are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * NOTES: - * 1) Identifiers are grouped with a logical OR by default. - * 2) In the case that the "andAllKeys" find qualifier is used the identifiers are AND'd together. The only way this can be done - * with a single query was to create a self-join for each identifier. If there are a lot of identifiers, the performance could suffer. - * TODO: Test performance with multiple AND'd identifiers. If too slow, look to process this query in multiple steps. - * 3) The "orLikeKeys" qualifier complicates matters. The "like" keys are OR'd together and these groups of "like" keys are AND'd together. - * As with "andAllKeys", self-joins are created but only one for each group of "like" keys. If none of the keyedReferences passed are alike then this - * will reduce to an "andAllKeys" query. If all are alike, then this will query will exhibit the default behavior of OR'ing all keys. - * - * @author Jeff Faath - */ -public class FindEntityByIdentifierQuery extends EntityQuery { - - @SuppressWarnings("unused") - private final static Log log = LogFactory.getLog(FindEntityByIdentifierQuery.class); - - private final String entityName; - private final String entityAlias; - private final String keyName; - private final String entityField; - private final String entityNameChild; - private final String entityAliasChild; - private final String selectSQL; - private String signaturePresent; - - public FindEntityByIdentifierQuery(String entityName, String entityAlias, String keyName, - String entityField, String entityNameChild, String signaturePresent) { - this.entityName = entityName; - this.entityAlias = entityAlias; - this.keyName = keyName; - this.entityField = entityField; - this.entityNameChild = entityNameChild; - this.entityAliasChild = buildAlias(entityNameChild); - this.signaturePresent = signaturePresent; - - StringBuilder sql = new StringBuilder(200); - sql.append("select distinct ").append(entityAlias).append(".").append(keyName).append(" from ").append(entityName).append(" ").append(entityAlias).append(" "); - selectSQL = sql.toString(); - } - - public String getEntityName() { - return entityName; - } - - public String getEntityAlias() { - return entityAlias; - } - - public String getKeyName() { - return keyName; - } - - public String getEntityField() { - return entityField; - } - - public String getEntityNameChild() { - return entityNameChild; - } - - public String getEntityAliasChild() { - return entityAliasChild; - } - - public String getSelectSQL() { - return selectSQL; - } - - public String getSignaturePresent() { - return signaturePresent; - } - - public void setSignaturePresent(String signaturePresent) { - this.signaturePresent = signaturePresent; - } - - - public List select(EntityManager em, FindQualifiers fq, IdentifierBag identifiers, List keysIn, DynamicQuery.Parameter... restrictions) { - // If keysIn is not null and empty, then search is over. - if ((keysIn != null) && (keysIn.size() == 0)) - return keysIn; - - if (identifiers == null) - return keysIn; - - List keyedRefs = identifiers.getKeyedReference(); - if (keyedRefs == null || keyedRefs.size() == 0) - return keysIn; - - DynamicQuery dynamicQry = new DynamicQuery(selectSQL); - appendConditions(dynamicQry, fq, keyedRefs); - if (restrictions != null && restrictions.length > 0) - dynamicQry.AND().pad().appendGroupedAnd(restrictions); - - return getQueryResult(em, dynamicQry, keysIn, entityAlias + "." + keyName); - } - - - /* - * Appends the conditions to the query based on the keyedReference list. With the default or when "andAllKeys" is passed, the keyedReferences are autonomous and are - * all OR'd or AND'd respectively. However, "orLikeKeys" requires special treatment. The goal is to create the conditions in this format: - * - * (likeKey1 = X or likeKey1 = Y) and (likeKey2 = A or likeKey2 = B or likeKey2 = C) - * - * ie. the "like" KeyedReferences are OR'd and the groups of "like" KeyedReferences are AND'd with each other. - */ - public void appendConditions(DynamicQuery qry, FindQualifiers fq, List keyedRefs) { - - // Append the necessary tables (one will always be added connecting the entity to its identifier table). - appendJoinTables(qry, fq, keyedRefs); - qry.AND().pad().openParen().pad(); - - String predicate = DynamicQuery.PREDICATE_EQUALS; - if (fq.isApproximateMatch()) { - predicate = DynamicQuery.PREDICATE_LIKE; - } - - // Sorting the collection by tModel Key - Collections.sort(keyedRefs, new KeyedRefTModelComparator()); - - String prevTModelKey = null; - int count = 0; - int tblCount = -1; - for(KeyedReference keyedRef : keyedRefs) { - String tmodelKey = keyedRef.getTModelKey(); - String keyValue = keyedRef.getKeyValue(); - String keyName = keyedRef.getKeyName(); - - if (fq.isApproximateMatch()) { - // JUDDI-235: wildcards are provided by user (only commenting in case a new interpretation arises) - //keyValue = keyValue.endsWith(DynamicQuery.WILDCARD)?keyValue:keyValue + DynamicQuery.WILDCARD; - //keyName = keyName.endsWith(DynamicQuery.WILDCARD)?keyName:keyName + DynamicQuery.WILDCARD; - } - - // Either opening up (and AND'ing) a new "group" of like keys or simply appending an "or". If this is not "orLikeKeys", then just need to increment - // the table count. - if (fq.isOrLikeKeys()) { - if (count == 0) { - qry.openParen().pad(); - tblCount++; - } - else { - if (!tmodelKey.equals(prevTModelKey)) { - qry.closeParen().pad().AND().pad().openParen().pad(); - tblCount++; - } - else - qry.OR().pad(); - } - } - else - tblCount++; - - String keyValueTerm = (fq.isAndAllKeys()||fq.isOrLikeKeys()?entityAliasChild + tblCount:entityAliasChild + "0") + ".keyValue"; - String keyNameTerm = (fq.isAndAllKeys()||fq.isOrLikeKeys()?entityAliasChild + tblCount:entityAliasChild + "0") + ".keyName"; - String tmodelKeyTerm = (fq.isAndAllKeys()||fq.isOrLikeKeys()?entityAliasChild + tblCount:entityAliasChild + "0") + ".tmodelKeyRef"; - if (fq.isCaseInsensitiveMatch()) { - keyValueTerm = "upper(" + keyValueTerm + ")"; - keyValue = keyValue.toUpperCase(); - - keyNameTerm = "upper(" + keyNameTerm + ")"; - keyName = keyName.toUpperCase(); - } - - - // According to specification, if the "general keyword" tmodel is used, then the keyName must be part of the query. - if (Constants.GENERAL_KEYWORD_TMODEL.equalsIgnoreCase(tmodelKey)) { - qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS), - new DynamicQuery.Parameter(keyValueTerm, keyValue, predicate), - new DynamicQuery.Parameter(keyNameTerm, keyName, predicate)); - } - else { - qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS), - new DynamicQuery.Parameter(keyValueTerm, keyValue, predicate)); - - } - - if (count + 1 < keyedRefs.size()) { - if (fq.isAndAllKeys()) - qry.AND().pad(); - else if (fq.isOrLikeKeys()) { - } - else - qry.OR().pad(); - } - - // The "orLikeKeys" will always leave an unclosed parenthesis. This will close it. - if (fq.isOrLikeKeys() && (count + 1 == keyedRefs.size())) - qry.closeParen().pad(); - - prevTModelKey = tmodelKey; - count++; - } - qry.closeParen().pad(); - - } - - /* - * Appends the necessary join table for the child entity and additional tables for when keys are AND'd. When "orLikeKeys" is used, - * we only need an extra table for each distinct tmodelKey. - */ - public void appendJoinTables(DynamicQuery qry, FindQualifiers fq, List keyedRefs) { - - if (keyedRefs != null && keyedRefs.size() > 0) { - // Sorting the collection by tModel Key - Collections.sort(keyedRefs, new KeyedRefTModelComparator()); - - StringBuffer thetaJoins = new StringBuffer(200); - int tblCount = 0; - int count = 0; - String curTModelKey = null; - String prevTModelKey = null; - for(KeyedReference kr : keyedRefs) { - curTModelKey = kr.getTModelKey(); - if (count != 0) { - if (fq.isOrLikeKeys() && curTModelKey.equals(prevTModelKey)) { - // Do nothing - } - else { - tblCount++; - qry.comma().pad().append(entityNameChild + " " + entityAliasChild + tblCount).pad(); - thetaJoins.append(entityAliasChild + (tblCount - 1) + "." + entityField + "." + keyName + " = " + entityAliasChild + tblCount + "." + entityField + "." + keyName + " "); - thetaJoins.append(DynamicQuery.OPERATOR_AND + " "); - } - - } - else { - qry.comma().pad().append(entityNameChild + " " + entityAliasChild + tblCount).pad(); - thetaJoins.append(entityAlias + "." + keyName + " = " + entityAliasChild + tblCount + "." + entityField + "." + keyName + " "); - thetaJoins.append(DynamicQuery.OPERATOR_AND + " "); - } - prevTModelKey = curTModelKey; - count++; - } - - qry.WHERE().pad().openParen().pad(); - - String thetaJoinsStr = thetaJoins.toString(); - if (thetaJoinsStr.endsWith(DynamicQuery.OPERATOR_AND + " ")) - thetaJoinsStr = thetaJoinsStr.substring(0, thetaJoinsStr.length() - (DynamicQuery.OPERATOR_AND + " ").length()); - qry.append(thetaJoinsStr); - - qry.closeParen().pad(); - if (fq!=null && fq.isSignaturePresent()) { - qry.AND().pad().openParen().pad().append(getSignaturePresent()).pad().closeParen().pad(); - } - } - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.Collections; +import java.util.List; + +import javax.persistence.EntityManager; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.config.Constants; +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.apache.juddi.query.util.KeyedRefTModelComparator; +import org.uddi.api_v3.IdentifierBag; +import org.uddi.api_v3.KeyedReference; + +/** + * Returns the list of "entity" keys possessing the keyedReferences in the passed identifier bag. + * Output is restricted by list of "entity" keys passed in. If null, all entities are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * NOTES: + * 1) Identifiers are grouped with a logical OR by default. + * 2) In the case that the "andAllKeys" find qualifier is used the identifiers are AND'd together. The only way this can be done + * with a single query was to create a self-join for each identifier. If there are a lot of identifiers, the performance could suffer. + * TODO: Test performance with multiple AND'd identifiers. If too slow, look to process this query in multiple steps. + * 3) The "orLikeKeys" qualifier complicates matters. The "like" keys are OR'd together and these groups of "like" keys are AND'd together. + * As with "andAllKeys", self-joins are created but only one for each group of "like" keys. If none of the keyedReferences passed are alike then this + * will reduce to an "andAllKeys" query. If all are alike, then this will query will exhibit the default behavior of OR'ing all keys. + * + * @author Jeff Faath + */ +public class FindEntityByIdentifierQuery extends EntityQuery { + + @SuppressWarnings("unused") + private final static Log log = LogFactory.getLog(FindEntityByIdentifierQuery.class); + + private final String entityName; + private final String entityAlias; + private final String keyName; + private final String entityField; + private final String entityNameChild; + private final String entityAliasChild; + private final String selectSQL; + private String signaturePresent; + + public FindEntityByIdentifierQuery(String entityName, String entityAlias, String keyName, + String entityField, String entityNameChild, String signaturePresent) { + this.entityName = entityName; + this.entityAlias = entityAlias; + this.keyName = keyName; + this.entityField = entityField; + this.entityNameChild = entityNameChild; + this.entityAliasChild = buildAlias(entityNameChild); + this.signaturePresent = signaturePresent; + + StringBuilder sql = new StringBuilder(200); + sql.append("select distinct ").append(entityAlias).append(".").append(keyName).append(" from ").append(entityName).append(" ").append(entityAlias).append(" "); + selectSQL = sql.toString(); + } + + public String getEntityName() { + return entityName; + } + + public String getEntityAlias() { + return entityAlias; + } + + public String getKeyName() { + return keyName; + } + + public String getEntityField() { + return entityField; + } + + public String getEntityNameChild() { + return entityNameChild; + } + + public String getEntityAliasChild() { + return entityAliasChild; + } + + public String getSelectSQL() { + return selectSQL; + } + + public String getSignaturePresent() { + return signaturePresent; + } + + public void setSignaturePresent(String signaturePresent) { + this.signaturePresent = signaturePresent; + } + + + public List select(EntityManager em, FindQualifiers fq, IdentifierBag identifiers, List keysIn, DynamicQuery.Parameter... restrictions) { + // If keysIn is not null and empty, then search is over. + if ((keysIn != null) && (keysIn.size() == 0)) + return keysIn; + + if (identifiers == null) + return keysIn; + + List keyedRefs = identifiers.getKeyedReference(); + if (keyedRefs == null || keyedRefs.size() == 0) + return keysIn; + + DynamicQuery dynamicQry = new DynamicQuery(selectSQL); + appendConditions(dynamicQry, fq, keyedRefs); + if (restrictions != null && restrictions.length > 0) + dynamicQry.AND().pad().appendGroupedAnd(restrictions); + + return getQueryResult(em, dynamicQry, keysIn, entityAlias + "." + keyName); + } + + + /* + * Appends the conditions to the query based on the keyedReference list. With the default or when "andAllKeys" is passed, the keyedReferences are autonomous and are + * all OR'd or AND'd respectively. However, "orLikeKeys" requires special treatment. The goal is to create the conditions in this format: + * + * (likeKey1 = X or likeKey1 = Y) and (likeKey2 = A or likeKey2 = B or likeKey2 = C) + * + * ie. the "like" KeyedReferences are OR'd and the groups of "like" KeyedReferences are AND'd with each other. + */ + public void appendConditions(DynamicQuery qry, FindQualifiers fq, List keyedRefs) { + + // Append the necessary tables (one will always be added connecting the entity to its identifier table). + appendJoinTables(qry, fq, keyedRefs); + qry.AND().pad().openParen().pad(); + + String predicate = DynamicQuery.PREDICATE_EQUALS; + if (fq.isApproximateMatch()) { + predicate = DynamicQuery.PREDICATE_LIKE; + } + + // Sorting the collection by tModel Key + Collections.sort(keyedRefs, new KeyedRefTModelComparator()); + + String prevTModelKey = null; + int count = 0; + int tblCount = -1; + for(KeyedReference keyedRef : keyedRefs) { + String tmodelKey = keyedRef.getTModelKey(); + String keyValue = keyedRef.getKeyValue(); + String keyName = keyedRef.getKeyName(); + + if (fq.isApproximateMatch()) { + // JUDDI-235: wildcards are provided by user (only commenting in case a new interpretation arises) + //keyValue = keyValue.endsWith(DynamicQuery.WILDCARD)?keyValue:keyValue + DynamicQuery.WILDCARD; + //keyName = keyName.endsWith(DynamicQuery.WILDCARD)?keyName:keyName + DynamicQuery.WILDCARD; + } + + // Either opening up (and AND'ing) a new "group" of like keys or simply appending an "or". If this is not "orLikeKeys", then just need to increment + // the table count. + if (fq.isOrLikeKeys()) { + if (count == 0) { + qry.openParen().pad(); + tblCount++; + } + else { + if (!tmodelKey.equals(prevTModelKey)) { + qry.closeParen().pad().AND().pad().openParen().pad(); + tblCount++; + } + else + qry.OR().pad(); + } + } + else + tblCount++; + + String keyValueTerm = (fq.isAndAllKeys()||fq.isOrLikeKeys()?entityAliasChild + tblCount:entityAliasChild + "0") + ".keyValue"; + String keyNameTerm = (fq.isAndAllKeys()||fq.isOrLikeKeys()?entityAliasChild + tblCount:entityAliasChild + "0") + ".keyName"; + String tmodelKeyTerm = (fq.isAndAllKeys()||fq.isOrLikeKeys()?entityAliasChild + tblCount:entityAliasChild + "0") + ".tmodelKeyRef"; + if (fq.isCaseInsensitiveMatch()) { + keyValueTerm = "upper(" + keyValueTerm + ")"; + keyValue = keyValue.toUpperCase(); + + keyNameTerm = "upper(" + keyNameTerm + ")"; + keyName = keyName.toUpperCase(); + } + + + // According to specification, if the "general keyword" tmodel is used, then the keyName must be part of the query. + if (Constants.GENERAL_KEYWORD_TMODEL.equalsIgnoreCase(tmodelKey)) { + qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS), + new DynamicQuery.Parameter(keyValueTerm, keyValue, predicate), + new DynamicQuery.Parameter(keyNameTerm, keyName, predicate)); + } + else { + qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS), + new DynamicQuery.Parameter(keyValueTerm, keyValue, predicate)); + + } + + if (count + 1 < keyedRefs.size()) { + if (fq.isAndAllKeys()) + qry.AND().pad(); + else if (fq.isOrLikeKeys()) { + } + else + qry.OR().pad(); + } + + // The "orLikeKeys" will always leave an unclosed parenthesis. This will close it. + if (fq.isOrLikeKeys() && (count + 1 == keyedRefs.size())) + qry.closeParen().pad(); + + prevTModelKey = tmodelKey; + count++; + } + qry.closeParen().pad(); + + } + + /* + * Appends the necessary join table for the child entity and additional tables for when keys are AND'd. When "orLikeKeys" is used, + * we only need an extra table for each distinct tmodelKey. + */ + public void appendJoinTables(DynamicQuery qry, FindQualifiers fq, List keyedRefs) { + + if (keyedRefs != null && keyedRefs.size() > 0) { + // Sorting the collection by tModel Key + Collections.sort(keyedRefs, new KeyedRefTModelComparator()); + + StringBuffer thetaJoins = new StringBuffer(200); + int tblCount = 0; + int count = 0; + String curTModelKey = null; + String prevTModelKey = null; + for(KeyedReference kr : keyedRefs) { + curTModelKey = kr.getTModelKey(); + if (count != 0) { + if (fq.isOrLikeKeys() && curTModelKey.equals(prevTModelKey)) { + // Do nothing + } + else { + tblCount++; + qry.comma().pad().append(entityNameChild + " " + entityAliasChild + tblCount).pad(); + thetaJoins.append(entityAliasChild + (tblCount - 1) + "." + entityField + "." + keyName + " = " + entityAliasChild + tblCount + "." + entityField + "." + keyName + " "); + thetaJoins.append(DynamicQuery.OPERATOR_AND + " "); + } + + } + else { + qry.comma().pad().append(entityNameChild + " " + entityAliasChild + tblCount).pad(); + thetaJoins.append(entityAlias + "." + keyName + " = " + entityAliasChild + tblCount + "." + entityField + "." + keyName + " "); + thetaJoins.append(DynamicQuery.OPERATOR_AND + " "); + } + prevTModelKey = curTModelKey; + count++; + } + + qry.WHERE().pad().openParen().pad(); + + String thetaJoinsStr = thetaJoins.toString(); + if (thetaJoinsStr.endsWith(DynamicQuery.OPERATOR_AND + " ")) + thetaJoinsStr = thetaJoinsStr.substring(0, thetaJoinsStr.length() - (DynamicQuery.OPERATOR_AND + " ").length()); + qry.append(thetaJoinsStr); + + qry.closeParen().pad(); + if (fq!=null && fq.isSignaturePresent()) { + qry.AND().pad().openParen().pad().append(getSignaturePresent()).pad().closeParen().pad(); + } + } + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindEntityByNamesQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindEntityByNamesQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindEntityByNamesQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindEntityByNamesQuery.java index ba1c3bff4..71e1cae1a 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindEntityByNamesQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindEntityByNamesQuery.java @@ -1,178 +1,178 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; - -import javax.persistence.EntityManager; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.api_v3.Name; - -/** - * Returns the list of "entity" keys possessing the Names in the passed Name list. - * Output is restricted by list of "entity" keys passed in. If null, all entities are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * @author Jeff Faath - */ -public class FindEntityByNamesQuery extends EntityQuery { - - @SuppressWarnings("unused") - private static Log log = LogFactory.getLog(FindEntityByNamesQuery.class); - - private final String entityName; - private final String entityAlias; - private final String keyName; - private final String entityField; - private final String entityNameChild; - private final String entityAliasChild; - private final String selectSQL; - private String signaturePresent; - - public FindEntityByNamesQuery(String entityName, String entityAlias, String keyName, String entityField, - String entityNameChild, String signaturePresent) { - this.entityName = entityName; - this.entityAlias = entityAlias; - this.keyName = keyName; - this.entityField = entityField; - this.entityNameChild = entityNameChild; - this.entityAliasChild = buildAlias(entityNameChild); - this.signaturePresent = signaturePresent; - - StringBuffer sql = new StringBuffer(200); - sql.append("select distinct " + entityAlias + "." + keyName + " from " + entityName + " " + entityAlias + " "); - selectSQL = sql.toString(); - } - - public String getEntityName() { - return entityName; - } - - public String getEntityAlias() { - return entityAlias; - } - - public String getKeyName() { - return keyName; - } - - public String getEntityField() { - return entityField; - } - - public String getEntityNameChild() { - return entityNameChild; - } - - public String getEntityAliasChild() { - return entityAliasChild; - } - - public String getSelectSQL() { - return selectSQL; - } - - public String getSignaturePresent() { - return signaturePresent; - } - - public void setSignaturePresent(String signaturePresent) { - this.signaturePresent = signaturePresent; - } - - public List select(EntityManager em, FindQualifiers fq, List names, List keysIn, DynamicQuery.Parameter... restrictions) { - // If keysIn is not null and empty, then search is over. - if ((keysIn != null) && (keysIn.size() == 0)) - return keysIn; - - if (names == null || names.size() == 0) - return keysIn; - - DynamicQuery dynamicQry = new DynamicQuery(selectSQL); - appendConditions(dynamicQry, fq, names); - if (restrictions != null && restrictions.length > 0) - dynamicQry.AND().pad().appendGroupedAnd(restrictions); - - return getQueryResult(em, dynamicQry, keysIn, entityAlias + "." + keyName); - } - - /* - * Appends the conditions to the query based on the name list. - */ - public void appendConditions(DynamicQuery qry, FindQualifiers fq, List names) { - - // Append the necessary tables (one will always be added connecting the entity to its name table). - appendJoinTables(qry, fq, names); - qry.AND().pad().openParen().pad(); - - String namePredicate = DynamicQuery.PREDICATE_EQUALS; - if (fq.isApproximateMatch()) { - namePredicate = DynamicQuery.PREDICATE_LIKE; - } - - int count = 0; - for(Name n : names) { - String nameTerm = entityAliasChild + ".name"; - String nameValue = n.getValue(); - if (fq.isCaseInsensitiveMatch()) { - nameTerm = "upper(" + entityAliasChild + ".name)"; - nameValue = n.getValue().toUpperCase(); - } - // JUDDI-235: wildcards are provided by user (only commenting in case a new interpretation arises) - //if (fq.isApproximateMatch()) - // nameValue = nameValue.endsWith(DynamicQuery.WILDCARD)?nameValue:nameValue + DynamicQuery.WILDCARD; - - if (n.getLang() == null || n.getLang().length() == 0 ) { - qry.appendGroupedAnd(new DynamicQuery.Parameter(nameTerm, nameValue, namePredicate)); - } - else { - // Per spec, the language argument is always wildcarded and case insensitive - String langValue = n.getLang().endsWith(DynamicQuery.WILDCARD)?n.getLang().toUpperCase():n.getLang().toUpperCase() + DynamicQuery.WILDCARD; - qry.appendGroupedAnd(new DynamicQuery.Parameter(nameTerm, nameValue, namePredicate), - new DynamicQuery.Parameter("upper(" + entityAliasChild + ".langCode)", langValue, DynamicQuery.PREDICATE_LIKE)); - } - - if (count + 1 < names.size()) - qry.OR().pad(); - - count++; - } - qry.closeParen().pad(); - - } - - /* - * Appends the necessary join table for the child entity - */ - public void appendJoinTables(DynamicQuery qry, FindQualifiers fq, List names) { - qry.comma().pad().append(entityNameChild + " " + entityAliasChild).pad(); - qry.WHERE().pad().openParen().pad(); - qry.append(entityAlias + "." + keyName + " = " + entityAliasChild + "." + entityField + "." + keyName + " "); - qry.closeParen().pad(); - if (fq!=null && fq.isSignaturePresent()) { - qry.AND().pad().openParen().pad().append(getSignaturePresent()).pad().closeParen().pad(); - } - } - - - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; + +import javax.persistence.EntityManager; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.api_v3.Name; + +/** + * Returns the list of "entity" keys possessing the Names in the passed Name list. + * Output is restricted by list of "entity" keys passed in. If null, all entities are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * @author Jeff Faath + */ +public class FindEntityByNamesQuery extends EntityQuery { + + @SuppressWarnings("unused") + private static Log log = LogFactory.getLog(FindEntityByNamesQuery.class); + + private final String entityName; + private final String entityAlias; + private final String keyName; + private final String entityField; + private final String entityNameChild; + private final String entityAliasChild; + private final String selectSQL; + private String signaturePresent; + + public FindEntityByNamesQuery(String entityName, String entityAlias, String keyName, String entityField, + String entityNameChild, String signaturePresent) { + this.entityName = entityName; + this.entityAlias = entityAlias; + this.keyName = keyName; + this.entityField = entityField; + this.entityNameChild = entityNameChild; + this.entityAliasChild = buildAlias(entityNameChild); + this.signaturePresent = signaturePresent; + + StringBuffer sql = new StringBuffer(200); + sql.append("select distinct " + entityAlias + "." + keyName + " from " + entityName + " " + entityAlias + " "); + selectSQL = sql.toString(); + } + + public String getEntityName() { + return entityName; + } + + public String getEntityAlias() { + return entityAlias; + } + + public String getKeyName() { + return keyName; + } + + public String getEntityField() { + return entityField; + } + + public String getEntityNameChild() { + return entityNameChild; + } + + public String getEntityAliasChild() { + return entityAliasChild; + } + + public String getSelectSQL() { + return selectSQL; + } + + public String getSignaturePresent() { + return signaturePresent; + } + + public void setSignaturePresent(String signaturePresent) { + this.signaturePresent = signaturePresent; + } + + public List select(EntityManager em, FindQualifiers fq, List names, List keysIn, DynamicQuery.Parameter... restrictions) { + // If keysIn is not null and empty, then search is over. + if ((keysIn != null) && (keysIn.size() == 0)) + return keysIn; + + if (names == null || names.size() == 0) + return keysIn; + + DynamicQuery dynamicQry = new DynamicQuery(selectSQL); + appendConditions(dynamicQry, fq, names); + if (restrictions != null && restrictions.length > 0) + dynamicQry.AND().pad().appendGroupedAnd(restrictions); + + return getQueryResult(em, dynamicQry, keysIn, entityAlias + "." + keyName); + } + + /* + * Appends the conditions to the query based on the name list. + */ + public void appendConditions(DynamicQuery qry, FindQualifiers fq, List names) { + + // Append the necessary tables (one will always be added connecting the entity to its name table). + appendJoinTables(qry, fq, names); + qry.AND().pad().openParen().pad(); + + String namePredicate = DynamicQuery.PREDICATE_EQUALS; + if (fq.isApproximateMatch()) { + namePredicate = DynamicQuery.PREDICATE_LIKE; + } + + int count = 0; + for(Name n : names) { + String nameTerm = entityAliasChild + ".name"; + String nameValue = n.getValue(); + if (fq.isCaseInsensitiveMatch()) { + nameTerm = "upper(" + entityAliasChild + ".name)"; + nameValue = n.getValue().toUpperCase(); + } + // JUDDI-235: wildcards are provided by user (only commenting in case a new interpretation arises) + //if (fq.isApproximateMatch()) + // nameValue = nameValue.endsWith(DynamicQuery.WILDCARD)?nameValue:nameValue + DynamicQuery.WILDCARD; + + if (n.getLang() == null || n.getLang().length() == 0 ) { + qry.appendGroupedAnd(new DynamicQuery.Parameter(nameTerm, nameValue, namePredicate)); + } + else { + // Per spec, the language argument is always wildcarded and case insensitive + String langValue = n.getLang().endsWith(DynamicQuery.WILDCARD)?n.getLang().toUpperCase():n.getLang().toUpperCase() + DynamicQuery.WILDCARD; + qry.appendGroupedAnd(new DynamicQuery.Parameter(nameTerm, nameValue, namePredicate), + new DynamicQuery.Parameter("upper(" + entityAliasChild + ".langCode)", langValue, DynamicQuery.PREDICATE_LIKE)); + } + + if (count + 1 < names.size()) + qry.OR().pad(); + + count++; + } + qry.closeParen().pad(); + + } + + /* + * Appends the necessary join table for the child entity + */ + public void appendJoinTables(DynamicQuery qry, FindQualifiers fq, List names) { + qry.comma().pad().append(entityNameChild + " " + entityAliasChild).pad(); + qry.WHERE().pad().openParen().pad(); + qry.append(entityAlias + "." + keyName + " = " + entityAliasChild + "." + entityField + "." + keyName + " "); + qry.closeParen().pad(); + if (fq!=null && fq.isSignaturePresent()) { + qry.AND().pad().openParen().pad().append(getSignaturePresent()).pad().closeParen().pad(); + } + } + + + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindEntityByPublisherQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindEntityByPublisherQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindEntityByPublisherQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindEntityByPublisherQuery.java index 2f42d8330..7db438dba 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindEntityByPublisherQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindEntityByPublisherQuery.java @@ -1,108 +1,108 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; -import javax.persistence.EntityManager; - -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.apache.juddi.model.UddiEntityPublisher; - -/** - * Returns the list of "entity" keys possessing the publisher Id in the passed in UddiEntityPublisher - * Output is restricted by list of "entity" keys passed in. If null, all entities are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * @author Jeff Faath - */ -public class FindEntityByPublisherQuery extends EntityQuery { - - public static final String AUTHORIZED_NAME_FIELD = "authorizedName"; - - private final String entityName; - private final String entityAlias; - private final String keyName; - private final String selectSQL; - private String signaturePresent; - - public FindEntityByPublisherQuery(String entityName, String entityAlias, String keyName, String signaturePresent) { - this.entityName = entityName; - this.entityAlias = entityAlias; - this.keyName = keyName; - this.signaturePresent = signaturePresent; - - StringBuilder sql = new StringBuilder(200); - sql.append("select distinct ").append(entityAlias).append(".").append(keyName).append(" from ").append(entityName).append(" ").append(entityAlias).append(" "); - selectSQL = sql.toString(); - } - - public String getEntityName() { - return entityName; - } - - public String getEntityAlias() { - return entityAlias; - } - - public String getKeyName() { - return keyName; - } - - public String getSelectSQL() { - return selectSQL; - } - - public String getSignaturePresent() { - return signaturePresent; - } - - public void setSignaturePresent(String signaturePresent) { - this.signaturePresent = signaturePresent; - } - - - public List select(EntityManager em, FindQualifiers fq, UddiEntityPublisher publisher, List keysIn, DynamicQuery.Parameter... restrictions) { - // If keysIn is not null and empty, then search is over. - if ((keysIn != null) && (keysIn.size() == 0)) - return keysIn; - - if (publisher == null) - return keysIn; - - DynamicQuery dynamicQry = new DynamicQuery(selectSQL); - appendConditions(dynamicQry, fq, publisher); - if (restrictions != null && restrictions.length > 0) - dynamicQry.AND().pad().appendGroupedAnd(restrictions); - - return getQueryResult(em, dynamicQry, keysIn, entityAlias + "." + keyName); - } - - /* - * Appends the conditions to the query based on the publisher id - */ - public void appendConditions(DynamicQuery qry, FindQualifiers fq, UddiEntityPublisher publisher) { - qry.WHERE().pad(); - if (fq!=null && fq.isSignaturePresent()) { - qry.pad().openParen().pad().append(getSignaturePresent()).pad().closeParen().pad().AND(); - } - qry.appendGroupedAnd(new DynamicQuery.Parameter(entityAlias + "." + AUTHORIZED_NAME_FIELD, publisher.getAuthorizedName(), DynamicQuery.PREDICATE_EQUALS)); - } - - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; +import javax.persistence.EntityManager; + +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.apache.juddi.model.UddiEntityPublisher; + +/** + * Returns the list of "entity" keys possessing the publisher Id in the passed in UddiEntityPublisher + * Output is restricted by list of "entity" keys passed in. If null, all entities are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * @author Jeff Faath + */ +public class FindEntityByPublisherQuery extends EntityQuery { + + public static final String AUTHORIZED_NAME_FIELD = "authorizedName"; + + private final String entityName; + private final String entityAlias; + private final String keyName; + private final String selectSQL; + private String signaturePresent; + + public FindEntityByPublisherQuery(String entityName, String entityAlias, String keyName, String signaturePresent) { + this.entityName = entityName; + this.entityAlias = entityAlias; + this.keyName = keyName; + this.signaturePresent = signaturePresent; + + StringBuilder sql = new StringBuilder(200); + sql.append("select distinct ").append(entityAlias).append(".").append(keyName).append(" from ").append(entityName).append(" ").append(entityAlias).append(" "); + selectSQL = sql.toString(); + } + + public String getEntityName() { + return entityName; + } + + public String getEntityAlias() { + return entityAlias; + } + + public String getKeyName() { + return keyName; + } + + public String getSelectSQL() { + return selectSQL; + } + + public String getSignaturePresent() { + return signaturePresent; + } + + public void setSignaturePresent(String signaturePresent) { + this.signaturePresent = signaturePresent; + } + + + public List select(EntityManager em, FindQualifiers fq, UddiEntityPublisher publisher, List keysIn, DynamicQuery.Parameter... restrictions) { + // If keysIn is not null and empty, then search is over. + if ((keysIn != null) && (keysIn.size() == 0)) + return keysIn; + + if (publisher == null) + return keysIn; + + DynamicQuery dynamicQry = new DynamicQuery(selectSQL); + appendConditions(dynamicQry, fq, publisher); + if (restrictions != null && restrictions.length > 0) + dynamicQry.AND().pad().appendGroupedAnd(restrictions); + + return getQueryResult(em, dynamicQry, keysIn, entityAlias + "." + keyName); + } + + /* + * Appends the conditions to the query based on the publisher id + */ + public void appendConditions(DynamicQuery qry, FindQualifiers fq, UddiEntityPublisher publisher) { + qry.WHERE().pad(); + if (fq!=null && fq.isSignaturePresent()) { + qry.pad().openParen().pad().append(getSignaturePresent()).pad().closeParen().pad().AND(); + } + qry.appendGroupedAnd(new DynamicQuery.Parameter(entityAlias + "." + AUTHORIZED_NAME_FIELD, publisher.getAuthorizedName(), DynamicQuery.PREDICATE_EQUALS)); + } + + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindPublisherAssertionByBusinessQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindPublisherAssertionByBusinessQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindPublisherAssertionByBusinessQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindPublisherAssertionByBusinessQuery.java index afe27d76f..3d210f09c 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindPublisherAssertionByBusinessQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindPublisherAssertionByBusinessQuery.java @@ -1,102 +1,102 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.Query; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.model.PublisherAssertion; -import org.apache.juddi.query.util.DynamicQuery; -import org.uddi.api_v3.CompletionStatus; - -/** - * - * Returns the list of PublisherAssertions that contain the input businessKeys as their from or to key - * * - * @author Jeff Faath - */ -public class FindPublisherAssertionByBusinessQuery extends PublisherAssertionQuery { - - private static Log log = LogFactory.getLog(FindPublisherAssertionByBusinessQuery.class); - - @SuppressWarnings("unchecked") - public static List select(EntityManager em, List businessKeys, CompletionStatus completionStatus) { - if ((businessKeys == null) || (businessKeys.isEmpty())) - return null; - - DynamicQuery dynamicQry = new DynamicQuery(selectSQL); - appendConditions(dynamicQry, businessKeys, completionStatus); - - log.debug(dynamicQry); - - Query qry = dynamicQry.buildJPAQuery(em); - List result = qry.getResultList(); - - return result; - } - - /* - * Appends the conditions to the query based on the businessKey list. The keys can either be in the fromKey or toKey of the publisher assertion. - */ - public static void appendConditions(DynamicQuery qry, List businessKeys, CompletionStatus completionStatus) { - - qry.WHERE().pad().openParen().pad(); - - qry.appendInList(ENTITY_ALIAS + "." + FROM_KEY_NAME, businessKeys); - qry.pad().OR().pad(); - qry.appendInList(ENTITY_ALIAS + "." + TO_KEY_NAME, businessKeys); - qry.closeParen().pad(); - - if (completionStatus != null) { - qry.AND().pad().openParen().pad(); - - String fromCheckTerm = "UPPER(" + ENTITY_ALIAS + ".fromCheck)"; - String toCheckTerm = "UPPER(" + ENTITY_ALIAS + ".toCheck)"; - if (completionStatus == CompletionStatus.STATUS_BOTH_INCOMPLETE) { - qry.appendGroupedAnd(new DynamicQuery.Parameter(fromCheckTerm, "TRUE", DynamicQuery.PREDICATE_NOTEQUALS)); - qry.AND().pad(); - qry.appendGroupedAnd(new DynamicQuery.Parameter(toCheckTerm, "TRUE", DynamicQuery.PREDICATE_NOTEQUALS)); - } - else if (completionStatus == CompletionStatus.STATUS_COMPLETE) { - qry.appendGroupedAnd(new DynamicQuery.Parameter(fromCheckTerm, "TRUE", DynamicQuery.PREDICATE_EQUALS)); - qry.AND().pad(); - qry.appendGroupedAnd(new DynamicQuery.Parameter(toCheckTerm, "TRUE", DynamicQuery.PREDICATE_EQUALS)); - } - else if (completionStatus == CompletionStatus.STATUS_FROM_KEY_INCOMPLETE) { - qry.appendGroupedAnd(new DynamicQuery.Parameter(fromCheckTerm, "TRUE", DynamicQuery.PREDICATE_NOTEQUALS)); - qry.AND().pad(); - qry.appendGroupedAnd(new DynamicQuery.Parameter(toCheckTerm, "TRUE", DynamicQuery.PREDICATE_EQUALS)); - } - else if (completionStatus == CompletionStatus.STATUS_TO_KEY_INCOMPLETE) { - qry.appendGroupedAnd(new DynamicQuery.Parameter(fromCheckTerm, "TRUE", DynamicQuery.PREDICATE_EQUALS)); - qry.AND().pad(); - qry.appendGroupedAnd(new DynamicQuery.Parameter(toCheckTerm, "TRUE", DynamicQuery.PREDICATE_NOTEQUALS)); - } - - qry.closeParen().pad(); - } - - - } - - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.Query; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.model.PublisherAssertion; +import org.apache.juddi.query.util.DynamicQuery; +import org.uddi.api_v3.CompletionStatus; + +/** + * + * Returns the list of PublisherAssertions that contain the input businessKeys as their from or to key + * * + * @author Jeff Faath + */ +public class FindPublisherAssertionByBusinessQuery extends PublisherAssertionQuery { + + private static Log log = LogFactory.getLog(FindPublisherAssertionByBusinessQuery.class); + + @SuppressWarnings("unchecked") + public static List select(EntityManager em, List businessKeys, CompletionStatus completionStatus) { + if ((businessKeys == null) || (businessKeys.isEmpty())) + return null; + + DynamicQuery dynamicQry = new DynamicQuery(selectSQL); + appendConditions(dynamicQry, businessKeys, completionStatus); + + log.debug(dynamicQry); + + Query qry = dynamicQry.buildJPAQuery(em); + List result = qry.getResultList(); + + return result; + } + + /* + * Appends the conditions to the query based on the businessKey list. The keys can either be in the fromKey or toKey of the publisher assertion. + */ + public static void appendConditions(DynamicQuery qry, List businessKeys, CompletionStatus completionStatus) { + + qry.WHERE().pad().openParen().pad(); + + qry.appendInList(ENTITY_ALIAS + "." + FROM_KEY_NAME, businessKeys); + qry.pad().OR().pad(); + qry.appendInList(ENTITY_ALIAS + "." + TO_KEY_NAME, businessKeys); + qry.closeParen().pad(); + + if (completionStatus != null) { + qry.AND().pad().openParen().pad(); + + String fromCheckTerm = "UPPER(" + ENTITY_ALIAS + ".fromCheck)"; + String toCheckTerm = "UPPER(" + ENTITY_ALIAS + ".toCheck)"; + if (completionStatus == CompletionStatus.STATUS_BOTH_INCOMPLETE) { + qry.appendGroupedAnd(new DynamicQuery.Parameter(fromCheckTerm, "TRUE", DynamicQuery.PREDICATE_NOTEQUALS)); + qry.AND().pad(); + qry.appendGroupedAnd(new DynamicQuery.Parameter(toCheckTerm, "TRUE", DynamicQuery.PREDICATE_NOTEQUALS)); + } + else if (completionStatus == CompletionStatus.STATUS_COMPLETE) { + qry.appendGroupedAnd(new DynamicQuery.Parameter(fromCheckTerm, "TRUE", DynamicQuery.PREDICATE_EQUALS)); + qry.AND().pad(); + qry.appendGroupedAnd(new DynamicQuery.Parameter(toCheckTerm, "TRUE", DynamicQuery.PREDICATE_EQUALS)); + } + else if (completionStatus == CompletionStatus.STATUS_FROM_KEY_INCOMPLETE) { + qry.appendGroupedAnd(new DynamicQuery.Parameter(fromCheckTerm, "TRUE", DynamicQuery.PREDICATE_NOTEQUALS)); + qry.AND().pad(); + qry.appendGroupedAnd(new DynamicQuery.Parameter(toCheckTerm, "TRUE", DynamicQuery.PREDICATE_EQUALS)); + } + else if (completionStatus == CompletionStatus.STATUS_TO_KEY_INCOMPLETE) { + qry.appendGroupedAnd(new DynamicQuery.Parameter(fromCheckTerm, "TRUE", DynamicQuery.PREDICATE_EQUALS)); + qry.AND().pad(); + qry.appendGroupedAnd(new DynamicQuery.Parameter(toCheckTerm, "TRUE", DynamicQuery.PREDICATE_NOTEQUALS)); + } + + qry.closeParen().pad(); + } + + + } + + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindServiceByCategoryGroupQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindServiceByCategoryGroupQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindServiceByCategoryGroupQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindServiceByCategoryGroupQuery.java index 688f70a2d..8db060161 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindServiceByCategoryGroupQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindServiceByCategoryGroupQuery.java @@ -1,68 +1,68 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; - -import javax.persistence.EntityManager; - -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.api_v3.CategoryBag; - -/** - * Returns the list of service keys possessing the keyedReferenceGroups in the passed category bag. - * Output is restricted by list of service keys passed in. If null, all services are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * From specification: - * "This is a list of category references. The returned serviceList contains serviceInfo structures matching all of the - * categories passed (logical AND by default). Specifying the appropriate findQualifiers can override this behavior. - * - * A given keyedReferenceGroup "X" (e.g., within a given categoryBag) matches a keyedReferenceGroup "Y" in the registry if - * and only if the tModelKey assigned to the keyedReferenceGroup X matches the tModelKey assigned to the keyedReferenceGroup - * Y and the set of keyedReferences in "X" are a subset of the set of keyedReferences in "Y." The order of individual - * keyedReferences within a keyedReferenceGroup is not important. Matching rules for the individual contained keyedReference - * elements are the same as above." - * - * @author Jeff Faath - */ -public class FindServiceByCategoryGroupQuery { - - private static final String ENTITY_NAME_CHILD = "ServiceCategoryBag"; - - private static final FindEntityByCategoryGroupQuery findQuery; - - static { - findQuery = new FindEntityByCategoryGroupQuery(BusinessServiceQuery.ENTITY_NAME, - BusinessServiceQuery.ENTITY_ALIAS, - BusinessServiceQuery.KEY_NAME, - BusinessServiceQuery.ENTITY_FIELD, - ENTITY_NAME_CHILD, - BusinessServiceQuery.SIGNATURE_PRESENT); - } - - public static List select(EntityManager em, FindQualifiers fq, CategoryBag categoryBag, String parentKey, List keysIn) { - if (parentKey != null && parentKey.length() > 0) { - DynamicQuery.Parameter param = new DynamicQuery.Parameter(BusinessServiceQuery.ENTITY_ALIAS + "." + BusinessServiceQuery.KEY_NAME_PARENT, parentKey, DynamicQuery.PREDICATE_EQUALS); - return findQuery.select(em, fq, categoryBag, keysIn, param); - } - else - return findQuery.select(em, fq, categoryBag, keysIn); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; + +import javax.persistence.EntityManager; + +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.api_v3.CategoryBag; + +/** + * Returns the list of service keys possessing the keyedReferenceGroups in the passed category bag. + * Output is restricted by list of service keys passed in. If null, all services are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * From specification: + * "This is a list of category references. The returned serviceList contains serviceInfo structures matching all of the + * categories passed (logical AND by default). Specifying the appropriate findQualifiers can override this behavior. + * + * A given keyedReferenceGroup "X" (e.g., within a given categoryBag) matches a keyedReferenceGroup "Y" in the registry if + * and only if the tModelKey assigned to the keyedReferenceGroup X matches the tModelKey assigned to the keyedReferenceGroup + * Y and the set of keyedReferences in "X" are a subset of the set of keyedReferences in "Y." The order of individual + * keyedReferences within a keyedReferenceGroup is not important. Matching rules for the individual contained keyedReference + * elements are the same as above." + * + * @author Jeff Faath + */ +public class FindServiceByCategoryGroupQuery { + + private static final String ENTITY_NAME_CHILD = "ServiceCategoryBag"; + + private static final FindEntityByCategoryGroupQuery findQuery; + + static { + findQuery = new FindEntityByCategoryGroupQuery(BusinessServiceQuery.ENTITY_NAME, + BusinessServiceQuery.ENTITY_ALIAS, + BusinessServiceQuery.KEY_NAME, + BusinessServiceQuery.ENTITY_FIELD, + ENTITY_NAME_CHILD, + BusinessServiceQuery.SIGNATURE_PRESENT); + } + + public static List select(EntityManager em, FindQualifiers fq, CategoryBag categoryBag, String parentKey, List keysIn) { + if (parentKey != null && parentKey.length() > 0) { + DynamicQuery.Parameter param = new DynamicQuery.Parameter(BusinessServiceQuery.ENTITY_ALIAS + "." + BusinessServiceQuery.KEY_NAME_PARENT, parentKey, DynamicQuery.PREDICATE_EQUALS); + return findQuery.select(em, fq, categoryBag, keysIn, param); + } + else + return findQuery.select(em, fq, categoryBag, keysIn); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindServiceByCategoryQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindServiceByCategoryQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindServiceByCategoryQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindServiceByCategoryQuery.java index 978e5c72c..fd4119f59 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindServiceByCategoryQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindServiceByCategoryQuery.java @@ -1,63 +1,63 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; - -import javax.persistence.EntityManager; - -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.api_v3.CategoryBag; - -/** - * Returns the list of service keys possessing the keyedReferences in the passed category bag. - * Output is restricted by list of service keys passed in. If null, all business services are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * From specification: - * "This is a list of category references. The returned serviceList contains serviceInfo structures matching all of - * the categories passed (logical AND by default). Specifying the appropriate findQualifiers can override this behavior." - * - * @author Jeff Faath - */ -public class FindServiceByCategoryQuery { - - private static final String ENTITY_NAME_CHILD = "ServiceCategoryBag"; - - private static final FindEntityByCategoryQuery findQuery; - - static { - findQuery = new FindEntityByCategoryQuery(BusinessServiceQuery.ENTITY_NAME, - BusinessServiceQuery.ENTITY_ALIAS, - BusinessServiceQuery.KEY_NAME, - BusinessServiceQuery.ENTITY_FIELD, - ENTITY_NAME_CHILD, - BusinessServiceQuery.SIGNATURE_PRESENT); - } - - public static List select(EntityManager em, FindQualifiers fq, CategoryBag categoryBag, String parentKey, List keysIn) { - if (parentKey != null && parentKey.length() > 0) { - DynamicQuery.Parameter param = new DynamicQuery.Parameter(BusinessServiceQuery.ENTITY_ALIAS + "." - + BusinessServiceQuery.KEY_NAME_PARENT, parentKey, DynamicQuery.PREDICATE_EQUALS); - return findQuery.select(em, fq, categoryBag, keysIn, param); - } - else - return findQuery.select(em, fq, categoryBag, keysIn); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; + +import javax.persistence.EntityManager; + +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.api_v3.CategoryBag; + +/** + * Returns the list of service keys possessing the keyedReferences in the passed category bag. + * Output is restricted by list of service keys passed in. If null, all business services are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * From specification: + * "This is a list of category references. The returned serviceList contains serviceInfo structures matching all of + * the categories passed (logical AND by default). Specifying the appropriate findQualifiers can override this behavior." + * + * @author Jeff Faath + */ +public class FindServiceByCategoryQuery { + + private static final String ENTITY_NAME_CHILD = "ServiceCategoryBag"; + + private static final FindEntityByCategoryQuery findQuery; + + static { + findQuery = new FindEntityByCategoryQuery(BusinessServiceQuery.ENTITY_NAME, + BusinessServiceQuery.ENTITY_ALIAS, + BusinessServiceQuery.KEY_NAME, + BusinessServiceQuery.ENTITY_FIELD, + ENTITY_NAME_CHILD, + BusinessServiceQuery.SIGNATURE_PRESENT); + } + + public static List select(EntityManager em, FindQualifiers fq, CategoryBag categoryBag, String parentKey, List keysIn) { + if (parentKey != null && parentKey.length() > 0) { + DynamicQuery.Parameter param = new DynamicQuery.Parameter(BusinessServiceQuery.ENTITY_ALIAS + "." + + BusinessServiceQuery.KEY_NAME_PARENT, parentKey, DynamicQuery.PREDICATE_EQUALS); + return findQuery.select(em, fq, categoryBag, keysIn, param); + } + else + return findQuery.select(em, fq, categoryBag, keysIn); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindServiceByCombinedCategoryQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindServiceByCombinedCategoryQuery.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/query/FindServiceByCombinedCategoryQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindServiceByCombinedCategoryQuery.java diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindServiceByNameQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindServiceByNameQuery.java similarity index 98% rename from juddi-core/src/main/java/org/apache/juddi/query/FindServiceByNameQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindServiceByNameQuery.java index e6f1e94ca..7d11ab77a 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindServiceByNameQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindServiceByNameQuery.java @@ -1,71 +1,71 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; -import javax.persistence.EntityManager; - -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.api_v3.Name; - -/** - * Returns the list of service keys possessing the Names in the passed Name list. - * Output is restricted by list of service keys passed in. If null, all services are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * From specification: - * "This optional collection of string values represents one or more names potentially qualified with xml:lang attributes. - * Since "exactMatch" is the default behavior, the value supplied for the name argument must be an exact match. If the "approximateMatch" - * findQualifier is used together with an appropriate wildcard character in the name, then any businessService data contained in the specified - * businessEntity (or across all businesses if the businessKey is omitted or specified as empty) with matching name value will be returned. - * Matching occurs using wildcard matching rules. See Section 5.1.6 About Wildcards. If multiple name values are passed, the match occurs - * on a logical OR basis within any names supplied. Each name MAY be marked with an xml:lang adornment. If a language markup is specified, - * the search results report a match only on those entries that match both the name value and language criteria. The match on language is a - * leftmost case-insensitive comparison of the characters supplied. This allows one to find all services whose name begins with an "A" and are - * expressed in any dialect of French, for example. Values which can be passed in the language criteria adornment MUST obey the rules governing - * the xml:lang data type as defined in Section 3.3.2.3 name." - * - * @author Jeff Faath - */ -public class FindServiceByNameQuery { - - public static final String ENTITY_NAME_CHILD = "ServiceName"; - - private static final FindEntityByNamesQuery findQuery; - - static { - findQuery = new FindEntityByNamesQuery(BusinessServiceQuery.ENTITY_NAME, - BusinessServiceQuery.ENTITY_ALIAS, - BusinessServiceQuery.KEY_NAME, - BusinessServiceQuery.ENTITY_FIELD, - ENTITY_NAME_CHILD, - BusinessServiceQuery.SIGNATURE_PRESENT); - } - - public static List select(EntityManager em, FindQualifiers fq, List names, String parentKey, List keysIn) { - if (parentKey != null && parentKey.length() > 0) { - DynamicQuery.Parameter param = new DynamicQuery.Parameter(BusinessServiceQuery.ENTITY_ALIAS + "." + BusinessServiceQuery.KEY_NAME_PARENT, parentKey, DynamicQuery.PREDICATE_EQUALS); - return findQuery.select(em, fq, names, keysIn, param); - } - else - return findQuery.select(em, fq, names, keysIn); - - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; +import javax.persistence.EntityManager; + +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.api_v3.Name; + +/** + * Returns the list of service keys possessing the Names in the passed Name list. + * Output is restricted by list of service keys passed in. If null, all services are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * From specification: + * "This optional collection of string values represents one or more names potentially qualified with xml:lang attributes. + * Since "exactMatch" is the default behavior, the value supplied for the name argument must be an exact match. If the "approximateMatch" + * findQualifier is used together with an appropriate wildcard character in the name, then any businessService data contained in the specified + * businessEntity (or across all businesses if the businessKey is omitted or specified as empty) with matching name value will be returned. + * Matching occurs using wildcard matching rules. See Section 5.1.6 About Wildcards. If multiple name values are passed, the match occurs + * on a logical OR basis within any names supplied. Each name MAY be marked with an xml:lang adornment. If a language markup is specified, + * the search results report a match only on those entries that match both the name value and language criteria. The match on language is a + * leftmost case-insensitive comparison of the characters supplied. This allows one to find all services whose name begins with an "A" and are + * expressed in any dialect of French, for example. Values which can be passed in the language criteria adornment MUST obey the rules governing + * the xml:lang data type as defined in Section 3.3.2.3 name." + * + * @author Jeff Faath + */ +public class FindServiceByNameQuery { + + public static final String ENTITY_NAME_CHILD = "ServiceName"; + + private static final FindEntityByNamesQuery findQuery; + + static { + findQuery = new FindEntityByNamesQuery(BusinessServiceQuery.ENTITY_NAME, + BusinessServiceQuery.ENTITY_ALIAS, + BusinessServiceQuery.KEY_NAME, + BusinessServiceQuery.ENTITY_FIELD, + ENTITY_NAME_CHILD, + BusinessServiceQuery.SIGNATURE_PRESENT); + } + + public static List select(EntityManager em, FindQualifiers fq, List names, String parentKey, List keysIn) { + if (parentKey != null && parentKey.length() > 0) { + DynamicQuery.Parameter param = new DynamicQuery.Parameter(BusinessServiceQuery.ENTITY_ALIAS + "." + BusinessServiceQuery.KEY_NAME_PARENT, parentKey, DynamicQuery.PREDICATE_EQUALS); + return findQuery.select(em, fq, names, keysIn, param); + } + else + return findQuery.select(em, fq, names, keysIn); + + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindServiceByTModelKeyQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindServiceByTModelKeyQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindServiceByTModelKeyQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindServiceByTModelKeyQuery.java index 991230eae..54481f59c 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindServiceByTModelKeyQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindServiceByTModelKeyQuery.java @@ -1,167 +1,167 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; - -import javax.persistence.EntityManager; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.api_v3.TModelBag; - -/** - * Returns the list of service keys with bindings that possess the tModels in the passed tModelBag. - * Output is restricted by list of service keys passed in. If null, all services are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * From specification: - * "Every Web service instance is represented in UDDI by a bindingTemplate contained within some businessService. A - * bindingTemplate contains a collection of tModel references called its "technical fingerprint" that specifies its type. - * The tModelBag argument is a collection of tModelKey values specifying that the search results are to be limited to - * businessServices containing bindingTemplates with technical fingerprints that match. - * - * If a find_tModel argument is specified (see below), it is treated as an embedded inquiry. The tModelKeys returned as a result - * of this embedded find_tModel argument are used as if they had been supplied in a tModelBag argument. Changing the order of - * the keys in the collection or specifying the same tModelKey more than once does not change the behavior of the find. - * - * By default, only bindingTemplates that contain all of the tModelKeys in the technical fingerprint match (logical AND). Specifying - * appropriate findQualifiers can override this behavior so that bindingTemplates containing any of the specified tModelKeys - * match (logical OR)." - * - * @author Jeff Faath - * @author Tom Cunningham - */ -public class FindServiceByTModelKeyQuery extends BusinessServiceQuery { - - @SuppressWarnings("unused") - private static Log log = LogFactory.getLog(FindServiceByTModelKeyQuery.class); - - public static final String ENTITY_NAME_CHILD = "TmodelInstanceInfo"; - - protected static final String entityAliasChild; - - static { - entityAliasChild = buildAlias(ENTITY_NAME_CHILD); - } - - public static List select(EntityManager em, FindQualifiers fq, TModelBag tModels, String parentKey, List keysIn, DynamicQuery.Parameter... restrictions) { - // If keysIn is not null and empty, then search is over. - if ((keysIn != null) && (keysIn.isEmpty())) - return keysIn; - - if (tModels == null) - return keysIn; - - List tmodelKeys = tModels.getTModelKey(); - if (tmodelKeys == null || tmodelKeys.isEmpty()) - return keysIn; - - DynamicQuery dynamicQry = new DynamicQuery(selectSQL); - appendConditions(dynamicQry, fq, tmodelKeys); - if (parentKey != null && parentKey.length() > 0) - dynamicQry.AND().pad().appendGroupedAnd(new DynamicQuery.Parameter(BusinessServiceQuery.ENTITY_ALIAS + "." + BusinessServiceQuery.KEY_NAME_PARENT, parentKey, DynamicQuery.PREDICATE_EQUALS)); - //dynamicQry.AND().pad().appendGroupedAnd(new DynamicQuery.Parameter(BindingTemplateQuery.ENTITY_ALIAS + "." + BindingTemplateQuery.KEY_NAME_PARENT, parentKey, DynamicQuery.PREDICATE_EQUALS)); - - if (restrictions != null && restrictions.length > 0) - dynamicQry.AND().pad().appendGroupedAnd(restrictions); - - return getQueryResult(em, dynamicQry, keysIn, ENTITY_ALIAS + "." + KEY_NAME); - } - - - /* - * Appends the conditions to the query based on the tModelKey list. With the default or when "orAllKeys" is passed, the keyedReferences are autonomous and are - * all AND'd or OR'd respectively. - * - */ - public static void appendConditions(DynamicQuery qry, FindQualifiers fq, List tmodelKeys) { - - // Append the necessary tables (one will always be added connecting the entity to its instanceinfo table). - appendJoinTables(qry, fq, tmodelKeys); - qry.AND().pad().openParen().pad(); - - int count = 0; - int tblCount = -1; - for(String tmodelKey : tmodelKeys) { - - tblCount++; - String tmodelKeyTerm = (fq.isOrAllKeys()?entityAliasChild + "0":entityAliasChild + tblCount) + ".tmodelKey"; - qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS)); - - if (count + 1 < tmodelKeys.size()) { - if (fq.isOrAllKeys()) - qry.OR().pad(); - else - qry.AND().pad(); - } - - count++; - } - qry.closeParen().pad(); - - } - - /* - * Appends the necessary join table for the child entity and additional tables for when keys are AND'd. This is the default behavior - * so only need to add additional tables if "orAllKeys" has not been set. - */ - public static void appendJoinTables(DynamicQuery qry, FindQualifiers fq, List tmodelKeys) { - - - if (tmodelKeys != null && tmodelKeys.size() > 0) { - qry.comma().pad().append(BindingTemplateQuery.ENTITY_NAME + " " + BindingTemplateQuery.ENTITY_ALIAS).pad(); - - StringBuilder thetaJoins = new StringBuilder(200); - int tblCount = 0; - for(int count = 0; count < tmodelKeys.size(); count++) { - if (count != 0) { - if (!fq.isOrAllKeys()) { - tblCount++; - qry.comma().pad().append(ENTITY_NAME_CHILD + " " + entityAliasChild + tblCount).pad(); - thetaJoins.append(entityAliasChild).append(tblCount - 1).append("." + BindingTemplateQuery.ENTITY_FIELD + "." + BindingTemplateQuery.KEY_NAME + " = ").append(entityAliasChild).append(tblCount).append("." + BindingTemplateQuery.ENTITY_FIELD + "." + BindingTemplateQuery.KEY_NAME + " "); - thetaJoins.append(DynamicQuery.OPERATOR_AND + " "); - } - } - else { - qry.comma().pad().append(ENTITY_NAME_CHILD + " " + entityAliasChild + tblCount).pad(); - thetaJoins.append(BindingTemplateQuery.ENTITY_ALIAS + "." + BindingTemplateQuery.KEY_NAME + " = ").append(entityAliasChild).append(tblCount).append("." + BindingTemplateQuery.ENTITY_FIELD + "." + BindingTemplateQuery.KEY_NAME + " "); - thetaJoins.append(DynamicQuery.OPERATOR_AND + " "); - } - } - - qry.WHERE().pad().openParen().pad(); - - qry.append(ENTITY_ALIAS + "." + KEY_NAME + " = " + BindingTemplateQuery.ENTITY_ALIAS + "." + ENTITY_FIELD + "." + KEY_NAME).pad(); - qry.AND().pad(); - - String thetaJoinsStr = thetaJoins.toString(); - if (thetaJoinsStr.endsWith(DynamicQuery.OPERATOR_AND + " ")) - thetaJoinsStr = thetaJoinsStr.substring(0, thetaJoinsStr.length() - (DynamicQuery.OPERATOR_AND + " ").length()); - qry.append(thetaJoinsStr); - - qry.closeParen().pad(); - if (fq!=null && fq.isSignaturePresent()) { - qry.AND().pad().openParen().pad().append(BusinessServiceQuery.SIGNATURE_PRESENT).pad().closeParen().pad(); - } - } - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; + +import javax.persistence.EntityManager; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.api_v3.TModelBag; + +/** + * Returns the list of service keys with bindings that possess the tModels in the passed tModelBag. + * Output is restricted by list of service keys passed in. If null, all services are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * From specification: + * "Every Web service instance is represented in UDDI by a bindingTemplate contained within some businessService. A + * bindingTemplate contains a collection of tModel references called its "technical fingerprint" that specifies its type. + * The tModelBag argument is a collection of tModelKey values specifying that the search results are to be limited to + * businessServices containing bindingTemplates with technical fingerprints that match. + * + * If a find_tModel argument is specified (see below), it is treated as an embedded inquiry. The tModelKeys returned as a result + * of this embedded find_tModel argument are used as if they had been supplied in a tModelBag argument. Changing the order of + * the keys in the collection or specifying the same tModelKey more than once does not change the behavior of the find. + * + * By default, only bindingTemplates that contain all of the tModelKeys in the technical fingerprint match (logical AND). Specifying + * appropriate findQualifiers can override this behavior so that bindingTemplates containing any of the specified tModelKeys + * match (logical OR)." + * + * @author Jeff Faath + * @author Tom Cunningham + */ +public class FindServiceByTModelKeyQuery extends BusinessServiceQuery { + + @SuppressWarnings("unused") + private static Log log = LogFactory.getLog(FindServiceByTModelKeyQuery.class); + + public static final String ENTITY_NAME_CHILD = "TmodelInstanceInfo"; + + protected static final String entityAliasChild; + + static { + entityAliasChild = buildAlias(ENTITY_NAME_CHILD); + } + + public static List select(EntityManager em, FindQualifiers fq, TModelBag tModels, String parentKey, List keysIn, DynamicQuery.Parameter... restrictions) { + // If keysIn is not null and empty, then search is over. + if ((keysIn != null) && (keysIn.isEmpty())) + return keysIn; + + if (tModels == null) + return keysIn; + + List tmodelKeys = tModels.getTModelKey(); + if (tmodelKeys == null || tmodelKeys.isEmpty()) + return keysIn; + + DynamicQuery dynamicQry = new DynamicQuery(selectSQL); + appendConditions(dynamicQry, fq, tmodelKeys); + if (parentKey != null && parentKey.length() > 0) + dynamicQry.AND().pad().appendGroupedAnd(new DynamicQuery.Parameter(BusinessServiceQuery.ENTITY_ALIAS + "." + BusinessServiceQuery.KEY_NAME_PARENT, parentKey, DynamicQuery.PREDICATE_EQUALS)); + //dynamicQry.AND().pad().appendGroupedAnd(new DynamicQuery.Parameter(BindingTemplateQuery.ENTITY_ALIAS + "." + BindingTemplateQuery.KEY_NAME_PARENT, parentKey, DynamicQuery.PREDICATE_EQUALS)); + + if (restrictions != null && restrictions.length > 0) + dynamicQry.AND().pad().appendGroupedAnd(restrictions); + + return getQueryResult(em, dynamicQry, keysIn, ENTITY_ALIAS + "." + KEY_NAME); + } + + + /* + * Appends the conditions to the query based on the tModelKey list. With the default or when "orAllKeys" is passed, the keyedReferences are autonomous and are + * all AND'd or OR'd respectively. + * + */ + public static void appendConditions(DynamicQuery qry, FindQualifiers fq, List tmodelKeys) { + + // Append the necessary tables (one will always be added connecting the entity to its instanceinfo table). + appendJoinTables(qry, fq, tmodelKeys); + qry.AND().pad().openParen().pad(); + + int count = 0; + int tblCount = -1; + for(String tmodelKey : tmodelKeys) { + + tblCount++; + String tmodelKeyTerm = (fq.isOrAllKeys()?entityAliasChild + "0":entityAliasChild + tblCount) + ".tmodelKey"; + qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS)); + + if (count + 1 < tmodelKeys.size()) { + if (fq.isOrAllKeys()) + qry.OR().pad(); + else + qry.AND().pad(); + } + + count++; + } + qry.closeParen().pad(); + + } + + /* + * Appends the necessary join table for the child entity and additional tables for when keys are AND'd. This is the default behavior + * so only need to add additional tables if "orAllKeys" has not been set. + */ + public static void appendJoinTables(DynamicQuery qry, FindQualifiers fq, List tmodelKeys) { + + + if (tmodelKeys != null && tmodelKeys.size() > 0) { + qry.comma().pad().append(BindingTemplateQuery.ENTITY_NAME + " " + BindingTemplateQuery.ENTITY_ALIAS).pad(); + + StringBuilder thetaJoins = new StringBuilder(200); + int tblCount = 0; + for(int count = 0; count < tmodelKeys.size(); count++) { + if (count != 0) { + if (!fq.isOrAllKeys()) { + tblCount++; + qry.comma().pad().append(ENTITY_NAME_CHILD + " " + entityAliasChild + tblCount).pad(); + thetaJoins.append(entityAliasChild).append(tblCount - 1).append("." + BindingTemplateQuery.ENTITY_FIELD + "." + BindingTemplateQuery.KEY_NAME + " = ").append(entityAliasChild).append(tblCount).append("." + BindingTemplateQuery.ENTITY_FIELD + "." + BindingTemplateQuery.KEY_NAME + " "); + thetaJoins.append(DynamicQuery.OPERATOR_AND + " "); + } + } + else { + qry.comma().pad().append(ENTITY_NAME_CHILD + " " + entityAliasChild + tblCount).pad(); + thetaJoins.append(BindingTemplateQuery.ENTITY_ALIAS + "." + BindingTemplateQuery.KEY_NAME + " = ").append(entityAliasChild).append(tblCount).append("." + BindingTemplateQuery.ENTITY_FIELD + "." + BindingTemplateQuery.KEY_NAME + " "); + thetaJoins.append(DynamicQuery.OPERATOR_AND + " "); + } + } + + qry.WHERE().pad().openParen().pad(); + + qry.append(ENTITY_ALIAS + "." + KEY_NAME + " = " + BindingTemplateQuery.ENTITY_ALIAS + "." + ENTITY_FIELD + "." + KEY_NAME).pad(); + qry.AND().pad(); + + String thetaJoinsStr = thetaJoins.toString(); + if (thetaJoinsStr.endsWith(DynamicQuery.OPERATOR_AND + " ")) + thetaJoinsStr = thetaJoinsStr.substring(0, thetaJoinsStr.length() - (DynamicQuery.OPERATOR_AND + " ").length()); + qry.append(thetaJoinsStr); + + qry.closeParen().pad(); + if (fq!=null && fq.isSignaturePresent()) { + qry.AND().pad().openParen().pad().append(BusinessServiceQuery.SIGNATURE_PRESENT).pad().closeParen().pad(); + } + } + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindSubscriptionByPublisherQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindSubscriptionByPublisherQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindSubscriptionByPublisherQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindSubscriptionByPublisherQuery.java index a6cc2c833..b8a5bba13 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindSubscriptionByPublisherQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindSubscriptionByPublisherQuery.java @@ -1,40 +1,40 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; - -import javax.persistence.EntityManager; - -import org.apache.juddi.query.util.DynamicQuery; - -/** - * Finds and returns a list of subscriptions by the authorized name. - * - * @author Jeff Faath - */ -public class FindSubscriptionByPublisherQuery extends SubscriptionQuery { - - - public static List select(EntityManager em, String authorizedName) { - DynamicQuery dynamicQry = new DynamicQuery(selectSQL); - dynamicQry.WHERE().pad(); - dynamicQry.appendGroupedAnd(new DynamicQuery.Parameter(ENTITY_ALIAS + "." + FindEntityByPublisherQuery.AUTHORIZED_NAME_FIELD, authorizedName, DynamicQuery.PREDICATE_EQUALS)); - return getQueryResult(em, dynamicQry, null, null); - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; + +import javax.persistence.EntityManager; + +import org.apache.juddi.query.util.DynamicQuery; + +/** + * Finds and returns a list of subscriptions by the authorized name. + * + * @author Jeff Faath + */ +public class FindSubscriptionByPublisherQuery extends SubscriptionQuery { + + + public static List select(EntityManager em, String authorizedName) { + DynamicQuery dynamicQry = new DynamicQuery(selectSQL); + dynamicQry.WHERE().pad(); + dynamicQry.appendGroupedAnd(new DynamicQuery.Parameter(ENTITY_ALIAS + "." + FindEntityByPublisherQuery.AUTHORIZED_NAME_FIELD, authorizedName, DynamicQuery.PREDICATE_EQUALS)); + return getQueryResult(em, dynamicQry, null, null); + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindTModelByCategoryGroupQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindTModelByCategoryGroupQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindTModelByCategoryGroupQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindTModelByCategoryGroupQuery.java index 29750dff6..e8ccd2e8a 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindTModelByCategoryGroupQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindTModelByCategoryGroupQuery.java @@ -1,65 +1,65 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; - -import javax.persistence.EntityManager; - -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.api_v3.CategoryBag; - -/** - * Returns the list of tmodel keys possessing the keyedReferenceGroups in the passed category bag. - * Output is restricted by list of tmodel keys passed in. If null, all tmodels are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * From specification: - * "This is a list of category references. The returned tModelList contains tModelInfo elements whose associated tModels - * match all of the categories passed (logical AND by default). Specifying the appropriate findQualifiers can override - * this behavior. - * - * A given keyedReferenceGroup "X" (e.g., within a given categoryBag) matches a keyedReferenceGroup "Y" in the registry if - * and only if the tModelKey assigned to the keyedReferenceGroup X matches the tModelKey assigned to the keyedReferenceGroup - * Y and the set of keyedReferences in "X" are a subset of the set of keyedReferences in "Y." The order of individual - * keyedReferences within a keyedReferenceGroup is not important. Matching rules for the individual contained keyedReference - * elements are the same as above." - * - * @author Jeff Faath - */ -public class FindTModelByCategoryGroupQuery { - - private static final String ENTITY_NAME_CHILD = "TmodelCategoryBag"; - - private static final FindEntityByCategoryGroupQuery findQuery; - - static { - findQuery = new FindEntityByCategoryGroupQuery(TModelQuery.ENTITY_NAME, - TModelQuery.ENTITY_ALIAS, - TModelQuery.KEY_NAME, - TModelQuery.ENTITY_FIELD, - ENTITY_NAME_CHILD, - TModelQuery.SIGNATURE_PRESENT); - } - - public static List select(EntityManager em, FindQualifiers fq, CategoryBag categoryBag, List keysIn) { - return findQuery.select(em, fq, categoryBag, keysIn, new DynamicQuery.Parameter(TModelQuery.ENTITY_ALIAS - + ".deleted", Boolean.FALSE, DynamicQuery.PREDICATE_EQUALS)); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; + +import javax.persistence.EntityManager; + +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.api_v3.CategoryBag; + +/** + * Returns the list of tmodel keys possessing the keyedReferenceGroups in the passed category bag. + * Output is restricted by list of tmodel keys passed in. If null, all tmodels are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * From specification: + * "This is a list of category references. The returned tModelList contains tModelInfo elements whose associated tModels + * match all of the categories passed (logical AND by default). Specifying the appropriate findQualifiers can override + * this behavior. + * + * A given keyedReferenceGroup "X" (e.g., within a given categoryBag) matches a keyedReferenceGroup "Y" in the registry if + * and only if the tModelKey assigned to the keyedReferenceGroup X matches the tModelKey assigned to the keyedReferenceGroup + * Y and the set of keyedReferences in "X" are a subset of the set of keyedReferences in "Y." The order of individual + * keyedReferences within a keyedReferenceGroup is not important. Matching rules for the individual contained keyedReference + * elements are the same as above." + * + * @author Jeff Faath + */ +public class FindTModelByCategoryGroupQuery { + + private static final String ENTITY_NAME_CHILD = "TmodelCategoryBag"; + + private static final FindEntityByCategoryGroupQuery findQuery; + + static { + findQuery = new FindEntityByCategoryGroupQuery(TModelQuery.ENTITY_NAME, + TModelQuery.ENTITY_ALIAS, + TModelQuery.KEY_NAME, + TModelQuery.ENTITY_FIELD, + ENTITY_NAME_CHILD, + TModelQuery.SIGNATURE_PRESENT); + } + + public static List select(EntityManager em, FindQualifiers fq, CategoryBag categoryBag, List keysIn) { + return findQuery.select(em, fq, categoryBag, keysIn, new DynamicQuery.Parameter(TModelQuery.ENTITY_ALIAS + + ".deleted", Boolean.FALSE, DynamicQuery.PREDICATE_EQUALS)); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindTModelByCategoryQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindTModelByCategoryQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindTModelByCategoryQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindTModelByCategoryQuery.java index edf0bd65e..080663ce4 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindTModelByCategoryQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindTModelByCategoryQuery.java @@ -1,59 +1,59 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; - -import javax.persistence.EntityManager; - -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.api_v3.CategoryBag; - -/** - * Returns the list of tModel keys possessing the keyedReferences in the passed category bag. - * Output is restricted by list of tModel keys passed in. If null, all tModels are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * From specification: - * "This is a list of category references. The returned tModelList contains tModelInfo elements whose - * associated tModels match all of the categories passed (logical AND by default). Specifying the - * appropriate findQualifiers can override this behavior." - * - * @author Jeff Faath - */ -public class FindTModelByCategoryQuery { - - private static final String ENTITY_NAME_CHILD = "TmodelCategoryBag"; - - private static final FindEntityByCategoryQuery findQuery; - - static { - findQuery = new FindEntityByCategoryQuery(TModelQuery.ENTITY_NAME, - TModelQuery.ENTITY_ALIAS, - TModelQuery.KEY_NAME, - TModelQuery.ENTITY_FIELD, - ENTITY_NAME_CHILD, - TModelQuery.SIGNATURE_PRESENT); - } - - public static List select(EntityManager em, FindQualifiers fq, CategoryBag categoryBag, List keysIn) { - return findQuery.select(em, fq, categoryBag, keysIn, new DynamicQuery.Parameter(TModelQuery.ENTITY_ALIAS - + ".deleted", Boolean.FALSE, DynamicQuery.PREDICATE_EQUALS)); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; + +import javax.persistence.EntityManager; + +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.api_v3.CategoryBag; + +/** + * Returns the list of tModel keys possessing the keyedReferences in the passed category bag. + * Output is restricted by list of tModel keys passed in. If null, all tModels are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * From specification: + * "This is a list of category references. The returned tModelList contains tModelInfo elements whose + * associated tModels match all of the categories passed (logical AND by default). Specifying the + * appropriate findQualifiers can override this behavior." + * + * @author Jeff Faath + */ +public class FindTModelByCategoryQuery { + + private static final String ENTITY_NAME_CHILD = "TmodelCategoryBag"; + + private static final FindEntityByCategoryQuery findQuery; + + static { + findQuery = new FindEntityByCategoryQuery(TModelQuery.ENTITY_NAME, + TModelQuery.ENTITY_ALIAS, + TModelQuery.KEY_NAME, + TModelQuery.ENTITY_FIELD, + ENTITY_NAME_CHILD, + TModelQuery.SIGNATURE_PRESENT); + } + + public static List select(EntityManager em, FindQualifiers fq, CategoryBag categoryBag, List keysIn) { + return findQuery.select(em, fq, categoryBag, keysIn, new DynamicQuery.Parameter(TModelQuery.ENTITY_ALIAS + + ".deleted", Boolean.FALSE, DynamicQuery.PREDICATE_EQUALS)); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindTModelByIdentifierQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindTModelByIdentifierQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindTModelByIdentifierQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindTModelByIdentifierQuery.java index 3c13cfc1a..c3c7300fd 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindTModelByIdentifierQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindTModelByIdentifierQuery.java @@ -1,58 +1,58 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; -import javax.persistence.EntityManager; - -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.api_v3.IdentifierBag; - -/** - * Returns the list of tModel keys possessing the keyedReferences in the passed identifier bag. - * Output is restricted by list of tModel keys passed in. If null, all tModels are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * From specification: - * "This is a list of identifier references in the form of keyedReference elements. The returned - * tModelList contains tModelInfo elements whose associated tModels match any of the identifiers passed (logical OR by default). - * Specifying the appropriate findQualifiers can override this behavior." - * - * @author Jeff Faath - */ -public class FindTModelByIdentifierQuery { - - private static final String ENTITY_NAME_CHILD = "TmodelIdentifier"; - - private static final FindEntityByIdentifierQuery findQuery; - - static { - findQuery = new FindEntityByIdentifierQuery(TModelQuery.ENTITY_NAME, - TModelQuery.ENTITY_ALIAS, - TModelQuery.KEY_NAME, - TModelQuery.ENTITY_FIELD, - ENTITY_NAME_CHILD, - TModelQuery.SIGNATURE_PRESENT); - } - - public static List select(EntityManager em, FindQualifiers fq, IdentifierBag identifiers, List keysIn) { - return findQuery.select(em, fq, identifiers, keysIn, new DynamicQuery.Parameter(TModelQuery.ENTITY_ALIAS + ".deleted", Boolean.FALSE, DynamicQuery.PREDICATE_EQUALS)); - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; +import javax.persistence.EntityManager; + +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.api_v3.IdentifierBag; + +/** + * Returns the list of tModel keys possessing the keyedReferences in the passed identifier bag. + * Output is restricted by list of tModel keys passed in. If null, all tModels are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * From specification: + * "This is a list of identifier references in the form of keyedReference elements. The returned + * tModelList contains tModelInfo elements whose associated tModels match any of the identifiers passed (logical OR by default). + * Specifying the appropriate findQualifiers can override this behavior." + * + * @author Jeff Faath + */ +public class FindTModelByIdentifierQuery { + + private static final String ENTITY_NAME_CHILD = "TmodelIdentifier"; + + private static final FindEntityByIdentifierQuery findQuery; + + static { + findQuery = new FindEntityByIdentifierQuery(TModelQuery.ENTITY_NAME, + TModelQuery.ENTITY_ALIAS, + TModelQuery.KEY_NAME, + TModelQuery.ENTITY_FIELD, + ENTITY_NAME_CHILD, + TModelQuery.SIGNATURE_PRESENT); + } + + public static List select(EntityManager em, FindQualifiers fq, IdentifierBag identifiers, List keysIn) { + return findQuery.select(em, fq, identifiers, keysIn, new DynamicQuery.Parameter(TModelQuery.ENTITY_ALIAS + ".deleted", Boolean.FALSE, DynamicQuery.PREDICATE_EQUALS)); + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindTModelByNameQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindTModelByNameQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindTModelByNameQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindTModelByNameQuery.java index 40bfb2d70..650de8c08 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindTModelByNameQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindTModelByNameQuery.java @@ -1,105 +1,105 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; - -import javax.persistence.EntityManager; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.uddi.api_v3.Name; - -/** - * - * Returns the list of tmodel keys possessing the passed Name argument. - * Output is restricted by list of tModel keys passed in. If null, all tModels are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * - * From specification: - * "This string value represents the name of the tModel elements to be found. Since tModel data only has a single - * name, only a single name may be passed. The argument must match exactly since "exactMatch" is the default behavior, - * but if the "approximateMatch" findQualifier is used together with the appropriate wildcard character, then matching - * is done according to wildcard rules. See Section 5.1.6 About Wildcards for additional information. The name MAY be - * marked with an xml:lang adornment. If a language markup is specified, the search results report a match only on those - * entries that match both the name value and language criteria. The match on language is a leftmost case-insensitive - * comparison of the characters supplied. This allows one to find all tModels whose name begins with an "A" and are expressed - * in any dialect of French, for example. Values which can be passed in the language criteria adornment MUST obey the rules - * governing the xml:lang data type as defined in Section 3.3.2.3 name." - * - * @author Jeff Faath - */ -public class FindTModelByNameQuery extends TModelQuery { - - @SuppressWarnings("unused") - private static Log log = LogFactory.getLog(FindTModelByNameQuery.class); - - public static List select(EntityManager em, FindQualifiers fq, Name name, List keysIn, DynamicQuery.Parameter... restrictions) { - // If keysIn is not null and empty, then search is over. - if ((keysIn != null) && (keysIn.isEmpty())) - return keysIn; - - if (name == null) - return keysIn; - - DynamicQuery dynamicQry = new DynamicQuery(selectSQL); - appendConditions(dynamicQry, fq, name); - // Since this is a tModel, don't need to search the lazily deleted ones. - dynamicQry.AND().pad().appendGroupedAnd(new DynamicQuery.Parameter(ENTITY_ALIAS + ".deleted", false, DynamicQuery.PREDICATE_EQUALS)); - if (restrictions != null && restrictions.length > 0) - dynamicQry.AND().pad().appendGroupedAnd(restrictions); - - return getQueryResult(em, dynamicQry, keysIn, ENTITY_ALIAS + "." + KEY_NAME); - } - - public static void appendConditions(DynamicQuery qry, FindQualifiers fq, Name name) { - String namePredicate = DynamicQuery.PREDICATE_EQUALS; - if (fq!=null && fq.isApproximateMatch()) { - namePredicate = DynamicQuery.PREDICATE_LIKE; - } - - qry.WHERE().pad().openParen().pad(); - - String nameTerm = ENTITY_ALIAS + ".name"; - String nameValue = name.getValue(); - if (fq!=null && fq.isCaseInsensitiveMatch()) { - nameTerm = "upper(" + ENTITY_ALIAS + ".name)"; - nameValue = name.getValue().toUpperCase(); - } - // JUDDI-235: wildcards are provided by user (only commenting in case a new interpretation arises) - //if (fq.isApproximateMatch()) - // nameValue = nameValue.endsWith(DynamicQuery.WILDCARD)?nameValue:nameValue + DynamicQuery.WILDCARD; - - if (name.getLang() == null || name.getLang().length() == 0 ) { - qry.appendGroupedAnd(new DynamicQuery.Parameter(nameTerm, nameValue, namePredicate)); - } - else { - String langValue = name.getLang().endsWith(DynamicQuery.WILDCARD)?name.getLang().toUpperCase():name.getLang().toUpperCase() + DynamicQuery.WILDCARD; - qry.appendGroupedAnd(new DynamicQuery.Parameter(nameTerm, nameValue, namePredicate), - new DynamicQuery.Parameter("upper(" + ENTITY_ALIAS + ".langCode)", langValue, DynamicQuery.PREDICATE_LIKE)); - } - - qry.closeParen().pad(); - if (fq!=null && fq.isSignaturePresent()) { - qry.AND().pad().openParen().pad().append(TModelQuery.SIGNATURE_PRESENT).pad().closeParen().pad(); - } - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; + +import javax.persistence.EntityManager; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.uddi.api_v3.Name; + +/** + * + * Returns the list of tmodel keys possessing the passed Name argument. + * Output is restricted by list of tModel keys passed in. If null, all tModels are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * + * From specification: + * "This string value represents the name of the tModel elements to be found. Since tModel data only has a single + * name, only a single name may be passed. The argument must match exactly since "exactMatch" is the default behavior, + * but if the "approximateMatch" findQualifier is used together with the appropriate wildcard character, then matching + * is done according to wildcard rules. See Section 5.1.6 About Wildcards for additional information. The name MAY be + * marked with an xml:lang adornment. If a language markup is specified, the search results report a match only on those + * entries that match both the name value and language criteria. The match on language is a leftmost case-insensitive + * comparison of the characters supplied. This allows one to find all tModels whose name begins with an "A" and are expressed + * in any dialect of French, for example. Values which can be passed in the language criteria adornment MUST obey the rules + * governing the xml:lang data type as defined in Section 3.3.2.3 name." + * + * @author Jeff Faath + */ +public class FindTModelByNameQuery extends TModelQuery { + + @SuppressWarnings("unused") + private static Log log = LogFactory.getLog(FindTModelByNameQuery.class); + + public static List select(EntityManager em, FindQualifiers fq, Name name, List keysIn, DynamicQuery.Parameter... restrictions) { + // If keysIn is not null and empty, then search is over. + if ((keysIn != null) && (keysIn.isEmpty())) + return keysIn; + + if (name == null) + return keysIn; + + DynamicQuery dynamicQry = new DynamicQuery(selectSQL); + appendConditions(dynamicQry, fq, name); + // Since this is a tModel, don't need to search the lazily deleted ones. + dynamicQry.AND().pad().appendGroupedAnd(new DynamicQuery.Parameter(ENTITY_ALIAS + ".deleted", false, DynamicQuery.PREDICATE_EQUALS)); + if (restrictions != null && restrictions.length > 0) + dynamicQry.AND().pad().appendGroupedAnd(restrictions); + + return getQueryResult(em, dynamicQry, keysIn, ENTITY_ALIAS + "." + KEY_NAME); + } + + public static void appendConditions(DynamicQuery qry, FindQualifiers fq, Name name) { + String namePredicate = DynamicQuery.PREDICATE_EQUALS; + if (fq!=null && fq.isApproximateMatch()) { + namePredicate = DynamicQuery.PREDICATE_LIKE; + } + + qry.WHERE().pad().openParen().pad(); + + String nameTerm = ENTITY_ALIAS + ".name"; + String nameValue = name.getValue(); + if (fq!=null && fq.isCaseInsensitiveMatch()) { + nameTerm = "upper(" + ENTITY_ALIAS + ".name)"; + nameValue = name.getValue().toUpperCase(); + } + // JUDDI-235: wildcards are provided by user (only commenting in case a new interpretation arises) + //if (fq.isApproximateMatch()) + // nameValue = nameValue.endsWith(DynamicQuery.WILDCARD)?nameValue:nameValue + DynamicQuery.WILDCARD; + + if (name.getLang() == null || name.getLang().length() == 0 ) { + qry.appendGroupedAnd(new DynamicQuery.Parameter(nameTerm, nameValue, namePredicate)); + } + else { + String langValue = name.getLang().endsWith(DynamicQuery.WILDCARD)?name.getLang().toUpperCase():name.getLang().toUpperCase() + DynamicQuery.WILDCARD; + qry.appendGroupedAnd(new DynamicQuery.Parameter(nameTerm, nameValue, namePredicate), + new DynamicQuery.Parameter("upper(" + ENTITY_ALIAS + ".langCode)", langValue, DynamicQuery.PREDICATE_LIKE)); + } + + qry.closeParen().pad(); + if (fq!=null && fq.isSignaturePresent()) { + qry.AND().pad().openParen().pad().append(TModelQuery.SIGNATURE_PRESENT).pad().closeParen().pad(); + } + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/FindTModelByPublisherQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindTModelByPublisherQuery.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/query/FindTModelByPublisherQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindTModelByPublisherQuery.java index fd7954c71..7ac9b402f 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/FindTModelByPublisherQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/FindTModelByPublisherQuery.java @@ -1,51 +1,51 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -import java.util.List; -import javax.persistence.EntityManager; - -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.apache.juddi.model.UddiEntityPublisher; - -/** - * Returns the list of tModel keys possessing the publisherId in the passed UddiEntityPublisher. - * Output is restricted by list of tModel keys passed in. If null, all tModels are searched. - * Output is produced by building the appropriate JPA query based on input and find qualifiers. - * * - * @author Jeff Faath - */ -public class FindTModelByPublisherQuery { - - - private static final FindEntityByPublisherQuery findQuery; - - static { - findQuery = new FindEntityByPublisherQuery( - TModelQuery.ENTITY_NAME, - TModelQuery.ENTITY_ALIAS, - TModelQuery.KEY_NAME, - TModelQuery.SIGNATURE_PRESENT); - } - - public static List select(EntityManager em, FindQualifiers fq, UddiEntityPublisher publisher, List keysIn, DynamicQuery.Parameter... restrictions) { - return findQuery.select(em, fq, publisher, keysIn, restrictions); - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +import java.util.List; +import javax.persistence.EntityManager; + +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.apache.juddi.model.UddiEntityPublisher; + +/** + * Returns the list of tModel keys possessing the publisherId in the passed UddiEntityPublisher. + * Output is restricted by list of tModel keys passed in. If null, all tModels are searched. + * Output is produced by building the appropriate JPA query based on input and find qualifiers. + * * + * @author Jeff Faath + */ +public class FindTModelByPublisherQuery { + + + private static final FindEntityByPublisherQuery findQuery; + + static { + findQuery = new FindEntityByPublisherQuery( + TModelQuery.ENTITY_NAME, + TModelQuery.ENTITY_ALIAS, + TModelQuery.KEY_NAME, + TModelQuery.SIGNATURE_PRESENT); + } + + public static List select(EntityManager em, FindQualifiers fq, UddiEntityPublisher publisher, List keysIn, DynamicQuery.Parameter... restrictions) { + return findQuery.select(em, fq, publisher, keysIn, restrictions); + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/PublisherAssertionQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/PublisherAssertionQuery.java similarity index 96% rename from juddi-core/src/main/java/org/apache/juddi/query/PublisherAssertionQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/PublisherAssertionQuery.java index 8817cd8b9..7120916c0 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/PublisherAssertionQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/PublisherAssertionQuery.java @@ -1,49 +1,49 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -/** - * @author Jeff Faath - */ -public class PublisherAssertionQuery extends EntityQuery { - - public static final String ENTITY_NAME = "PublisherAssertion"; - public static final String ENTITY_ALIAS = "pa"; - public static final String FROM_KEY_NAME = "businessEntityByFromKey." + KEY_NAME; - public static final String TO_KEY_NAME = "businessEntityByToKey." + KEY_NAME; - - protected static final String selectSQL; - protected static final String deleteSQL; - - static { - StringBuilder sql = new StringBuilder(200); - sql.append("select distinct " + ENTITY_ALIAS + " from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); - selectSQL = sql.toString(); - } - - static { - StringBuilder sql = new StringBuilder(200); - sql.append("delete from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); - deleteSQL = sql.toString(); - } - - public static String getSelectSQL() { - return selectSQL; - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +/** + * @author Jeff Faath + */ +public class PublisherAssertionQuery extends EntityQuery { + + public static final String ENTITY_NAME = "PublisherAssertion"; + public static final String ENTITY_ALIAS = "pa"; + public static final String FROM_KEY_NAME = "businessEntityByFromKey." + KEY_NAME; + public static final String TO_KEY_NAME = "businessEntityByToKey." + KEY_NAME; + + protected static final String selectSQL; + protected static final String deleteSQL; + + static { + StringBuilder sql = new StringBuilder(200); + sql.append("select distinct " + ENTITY_ALIAS + " from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); + selectSQL = sql.toString(); + } + + static { + StringBuilder sql = new StringBuilder(200); + sql.append("delete from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); + deleteSQL = sql.toString(); + } + + public static String getSelectSQL() { + return selectSQL; + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/SubscriptionQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/SubscriptionQuery.java similarity index 96% rename from juddi-core/src/main/java/org/apache/juddi/query/SubscriptionQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/SubscriptionQuery.java index 2f5b02c4a..30bb13644 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/SubscriptionQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/SubscriptionQuery.java @@ -1,40 +1,40 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -/** - * @author Jeff Faath - */ -public class SubscriptionQuery extends EntityQuery { - - public static final String ENTITY_NAME = "Subscription"; - public static final String ENTITY_ALIAS = "ss"; - - protected static final String selectSQL; - - static { - StringBuilder sql = new StringBuilder(200); - sql.append("select "+ ENTITY_ALIAS + " from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); - selectSQL = sql.toString(); - } - - public static String getSelectSQL() { - return selectSQL; - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +/** + * @author Jeff Faath + */ +public class SubscriptionQuery extends EntityQuery { + + public static final String ENTITY_NAME = "Subscription"; + public static final String ENTITY_ALIAS = "ss"; + + protected static final String selectSQL; + + static { + StringBuilder sql = new StringBuilder(200); + sql.append("select "+ ENTITY_ALIAS + " from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); + selectSQL = sql.toString(); + } + + public static String getSelectSQL() { + return selectSQL; + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/TModelQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/TModelQuery.java similarity index 96% rename from juddi-core/src/main/java/org/apache/juddi/query/TModelQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/TModelQuery.java index bb4a4a5dc..63ef20501 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/TModelQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/TModelQuery.java @@ -1,42 +1,42 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query; - -/** - * @author Jeff Faath - */ -public class TModelQuery extends EntityQuery { - - public static final String ENTITY_NAME = "Tmodel"; - public static final String ENTITY_ALIAS = "t"; - public static final String ENTITY_FIELD = "tmodel"; - public static final String SIGNATURE_PRESENT = ENTITY_ALIAS + "." + SIGNATURE_FIELD + " IS NOT EMPTY "; - - protected static final String selectSQL; - - static { - StringBuilder sql = new StringBuilder(200); - sql.append("select distinct "+ ENTITY_ALIAS + "." + KEY_NAME + " from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); - selectSQL = sql.toString(); - } - - public static String getSelectSQL() { - return selectSQL; - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query; + +/** + * @author Jeff Faath + */ +public class TModelQuery extends EntityQuery { + + public static final String ENTITY_NAME = "Tmodel"; + public static final String ENTITY_ALIAS = "t"; + public static final String ENTITY_FIELD = "tmodel"; + public static final String SIGNATURE_PRESENT = ENTITY_ALIAS + "." + SIGNATURE_FIELD + " IS NOT EMPTY "; + + protected static final String selectSQL; + + static { + StringBuilder sql = new StringBuilder(200); + sql.append("select distinct "+ ENTITY_ALIAS + "." + KEY_NAME + " from " + ENTITY_NAME + " " + ENTITY_ALIAS + " "); + selectSQL = sql.toString(); + } + + public static String getSelectSQL() { + return selectSQL; + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/package-info.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/package-info.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/query/package-info.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/package-info.java diff --git a/juddi-core/src/main/java/org/apache/juddi/query/util/DynamicQuery.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/util/DynamicQuery.java similarity index 95% rename from juddi-core/src/main/java/org/apache/juddi/query/util/DynamicQuery.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/util/DynamicQuery.java index f6cc68ae1..acc7f3f9d 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/util/DynamicQuery.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/util/DynamicQuery.java @@ -1,253 +1,253 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query.util; - -import java.util.StringTokenizer; -import java.util.Vector; -import java.util.List; -import javax.persistence.Query; -import javax.persistence.EntityManager; - -/** - * @author Jeff Faath - * @author Steve Viens (steve@viens.net) - */ -public class DynamicQuery { - public static final String CLAUSE_WHERE = "where"; - public static final String CLAUSE_GROUPBY = "group by"; - public static final String CLAUSE_ORDERBY = "order by"; - public static final String CLAUSE_HAVING = "having"; - public static final String OPERATOR_OR = "or"; - public static final String OPERATOR_AND = "and"; - public static final String PREDICATE_EQUALS = "="; - public static final String PREDICATE_NOTEQUALS = "<>"; - public static final String PREDICATE_LIKE = "like"; - public static final String PREDICATE_IN = "in"; - public static final String PREDICATE_GREATERTHAN = ">"; - public static final String PREDICATE_LESSTHAN = "<"; - public static final String SORT_ASC = "asc"; - public static final String SORT_DESC = "desc"; - public static final String WILDCARD = "%"; - - private Vector values = null; - private StringBuffer sql = null; - - public DynamicQuery() { - this.values = new Vector(); - this.sql = new StringBuffer(); - } - - public DynamicQuery(String sql) { - this.values = new Vector(); - this.sql = new StringBuffer(sql); - } - - public DynamicQuery append(String sql) { - this.sql.append(sql); - return this; - } - - public DynamicQuery pad() { - this.sql.append(" "); - return this; - } - - public DynamicQuery openParen() { - this.sql.append("("); - return this; - } - - public DynamicQuery closeParen() { - this.sql.append(")"); - return this; - } - - public DynamicQuery param() { - this.sql.append("?"); - return this; - } - - public DynamicQuery comma() { - this.sql.append(","); - return this; - } - - public DynamicQuery AND() { - this.sql.append(OPERATOR_AND); - return this; - } - - public DynamicQuery OR() { - this.sql.append(OPERATOR_OR); - return this; - } - - public DynamicQuery WHERE() { - this.sql.append(CLAUSE_WHERE); - return this; - } - - public DynamicQuery IN() { - this.sql.append(PREDICATE_IN); - return this; - } - - public DynamicQuery GROUPBY() { - this.sql.append(CLAUSE_GROUPBY); - return this; - } - - public DynamicQuery ORDERBY() { - this.sql.append(CLAUSE_ORDERBY); - return this; - } - - public DynamicQuery HAVING() { - this.sql.append(CLAUSE_HAVING); - return this; - } - - public DynamicQuery appendGroupedAnd(Parameter... params) { - return appendCondition(OPERATOR_AND, params); - } - - public DynamicQuery appendGroupedOr(Parameter... params) { - return appendCondition(OPERATOR_OR, params); - } - - public DynamicQuery appendCondition(String operator, Parameter... params) { - if (params == null || operator == null) - return this; - - openParen(); - for (int i = 0; i < params.length; i++) { - if (params[i] != null) { - append(params[i].getName()).pad().append(params[i].getPredicate()).pad().param(); - addValue(params[i].getValue()); - - if (i + 1 < params.length) { - pad().append(operator).pad(); - } - } - } - closeParen().pad(); - return this; - - } - - public DynamicQuery appendInListWithAnd(String term, List list) { - if (list == null || list.size() == 0) - return this; - - AND().pad(); - - return appendInList(term, list); - } - - public DynamicQuery appendInList(String term, List list) { - if (list == null || list.size() == 0) - return this; - - append(term).pad().IN().pad().openParen().pad(); - int count = 0; - for (Object item : list) { - param(); - addValue(item); - - if (count + 1 < list.size()) - comma().pad(); - - count++; - } - closeParen().pad(); - return this; - } - - public void addValue(Object obj) { - this.values.addElement(obj); - } - - public Query buildJPAQuery(EntityManager em) { - StringTokenizer tokenizer = new StringTokenizer(sql.toString(),"?"); - StringBuffer sqlBuffer = new StringBuffer(); - int numberOfTokens = tokenizer.countTokens(); - for (int i=1; iJeff Faath + * @author Steve Viens (steve@viens.net) + */ +public class DynamicQuery { + public static final String CLAUSE_WHERE = "where"; + public static final String CLAUSE_GROUPBY = "group by"; + public static final String CLAUSE_ORDERBY = "order by"; + public static final String CLAUSE_HAVING = "having"; + public static final String OPERATOR_OR = "or"; + public static final String OPERATOR_AND = "and"; + public static final String PREDICATE_EQUALS = "="; + public static final String PREDICATE_NOTEQUALS = "<>"; + public static final String PREDICATE_LIKE = "like"; + public static final String PREDICATE_IN = "in"; + public static final String PREDICATE_GREATERTHAN = ">"; + public static final String PREDICATE_LESSTHAN = "<"; + public static final String SORT_ASC = "asc"; + public static final String SORT_DESC = "desc"; + public static final String WILDCARD = "%"; + + private Vector values = null; + private StringBuffer sql = null; + + public DynamicQuery() { + this.values = new Vector(); + this.sql = new StringBuffer(); + } + + public DynamicQuery(String sql) { + this.values = new Vector(); + this.sql = new StringBuffer(sql); + } + + public DynamicQuery append(String sql) { + this.sql.append(sql); + return this; + } + + public DynamicQuery pad() { + this.sql.append(" "); + return this; + } + + public DynamicQuery openParen() { + this.sql.append("("); + return this; + } + + public DynamicQuery closeParen() { + this.sql.append(")"); + return this; + } + + public DynamicQuery param() { + this.sql.append("?"); + return this; + } + + public DynamicQuery comma() { + this.sql.append(","); + return this; + } + + public DynamicQuery AND() { + this.sql.append(OPERATOR_AND); + return this; + } + + public DynamicQuery OR() { + this.sql.append(OPERATOR_OR); + return this; + } + + public DynamicQuery WHERE() { + this.sql.append(CLAUSE_WHERE); + return this; + } + + public DynamicQuery IN() { + this.sql.append(PREDICATE_IN); + return this; + } + + public DynamicQuery GROUPBY() { + this.sql.append(CLAUSE_GROUPBY); + return this; + } + + public DynamicQuery ORDERBY() { + this.sql.append(CLAUSE_ORDERBY); + return this; + } + + public DynamicQuery HAVING() { + this.sql.append(CLAUSE_HAVING); + return this; + } + + public DynamicQuery appendGroupedAnd(Parameter... params) { + return appendCondition(OPERATOR_AND, params); + } + + public DynamicQuery appendGroupedOr(Parameter... params) { + return appendCondition(OPERATOR_OR, params); + } + + public DynamicQuery appendCondition(String operator, Parameter... params) { + if (params == null || operator == null) + return this; + + openParen(); + for (int i = 0; i < params.length; i++) { + if (params[i] != null) { + append(params[i].getName()).pad().append(params[i].getPredicate()).pad().param(); + addValue(params[i].getValue()); + + if (i + 1 < params.length) { + pad().append(operator).pad(); + } + } + } + closeParen().pad(); + return this; + + } + + public DynamicQuery appendInListWithAnd(String term, List list) { + if (list == null || list.size() == 0) + return this; + + AND().pad(); + + return appendInList(term, list); + } + + public DynamicQuery appendInList(String term, List list) { + if (list == null || list.size() == 0) + return this; + + append(term).pad().IN().pad().openParen().pad(); + int count = 0; + for (Object item : list) { + param(); + addValue(item); + + if (count + 1 < list.size()) + comma().pad(); + + count++; + } + closeParen().pad(); + return this; + } + + public void addValue(Object obj) { + this.values.addElement(obj); + } + + public Query buildJPAQuery(EntityManager em) { + StringTokenizer tokenizer = new StringTokenizer(sql.toString(),"?"); + StringBuffer sqlBuffer = new StringBuffer(); + int numberOfTokens = tokenizer.countTokens(); + for (int i=1; iJeff Faath - */ -public class FindQualifiers { - - public static final String AND_ALL_KEYS = "andAllKeys"; - public static final String AND_ALL_KEYS_TMODEL = "uddi:uddi.org:findqualifier:andallkeys"; - - public static final String APPROXIMATE_MATCH = "approximateMatch"; - public static final String APPROXIMATE_MATCH_TMODEL = "uddi:uddi.org:findqualifier:approximatematch"; - - public static final String BINARY_SORT = "binarySort"; - public static final String BINARY_SORT_TMODEL = "uddi:uddi.org:sortorder:binarysort"; - - public static final String BINDING_SUBSET = "bindingSubset"; - public static final String BINDING_SUBSET_TMODEL = "uddi:uddi.org:findqualifier:bindingsubset"; - - public static final String CASE_INSENSITIVE_SORT = "caseInsensitiveSort"; - public static final String CASE_INSENSITIVE_SORT_TMODEL = "uddi:uddi.org:findqualifier:caseinsensitivesort"; - - public static final String CASE_INSENSITIVE_MATCH = "caseInsensitiveMatch"; - public static final String CASE_INSENSITIVE_MATCH_TMODEL = "uddi:uddi.org:findqualifier:caseinsensitivematch"; - - public static final String CASE_SENSITIVE_SORT = "caseSensitiveSort"; - public static final String CASE_SENSITIVE_SORT_TMODEL = "uddi:uddi.org:findqualifier:casesensitivesort"; - - public static final String CASE_SENSITIVE_MATCH = "caseSensitiveMatch"; - public static final String CASE_SENSITIVE_MATCH_TMODEL = "uddi:uddi.org:findqualifier:casesensitivematch"; - - public static final String COMBINE_CATEGORY_BAGS = "combineCategoryBags"; - public static final String COMBINE_CATEGORY_BAGS_TMODEL = "uddi:uddi.org:findqualifier:combinecategorybags"; - - public static final String DIACRITIC_INSENSITIVE_MATCH = "diacriticInsensitiveMatch"; - public static final String DIACRITIC_INSENSITIVE_MATCH_TMODEL = "uddi:uddi.org:findqualifier:diacriticsinsensitivematch"; - - public static final String DIACRITIC_SENSITIVE_MATCH = "diacriticSensitiveMatch"; - public static final String DIACRITIC_SENSITIVE_MATCH_TMODEL = "uddi:uddi.org:findqualifier:diacriticssensitivematch"; - - public static final String EXACT_MATCH = "exactMatch"; - public static final String EXACT_MATCH_TMODEL = "uddi:uddi.org:findqualifier:exactmatch"; - - public static final String SIGNATURE_PRESENT = "signaturePresent"; - public static final String SIGNATURE_PRESENT_TMODEL = "uddi:uddi.org:findqualifier:signaturepresent"; - - public static final String OR_ALL_KEYS = "orAllKeys"; - public static final String OR_ALL_KEYS_TMODEL = "uddi:uddi.org:findqualifier:orallkeys"; - - public static final String OR_LIKE_KEYS = "orLikeKeys"; - public static final String OR_LIKE_KEYS_TMODEL = "uddi:uddi.org:findqualifier:orlikekeys"; - - public static final String SERVICE_SUBSET = "serviceSubset"; - public static final String SERVICE_SUBSET_TMODEL = "uddi:uddi.org:findqualifier:servicesubset"; - - public static final String SORT_BY_NAME_ASC = "sortByNameAsc"; - public static final String SORT_BY_NAME_ASC_TMODEL = "uddi:uddi.org:findqualifier:sortbynameasc"; - - public static final String SORT_BY_NAME_DESC = "sortByNameDesc"; - public static final String SORT_BY_NAME_DESC_TMODEL = "uddi:uddi.org:findqualifier:sortbynamedesc"; - - public static final String SORT_BY_DATE_ASC = "sortByDateAsc"; - public static final String SORT_BY_DATE_ASC_TMODEL = "uddi:uddi.org:findqualifier:sortbydateasc"; - - public static final String SORT_BY_DATE_DESC = "sortByDateDesc"; - public static final String SORT_BY_DATE_DESC_TMODEL = "uddi:uddi.org:findqualifier:sortbydatedesc"; - - public static final String SUPPRESS_PROJECTED_SERVICES = "suppressProjectedServices"; - public static final String SUPPRESS_PROJECTED_SERVICES_TMODEL = "uddi:uddi.org:findqualifier:suppressprojectedservices"; - - public static final String UTS_10 = "UTS-10"; - public static final String UTS_10_TMODEL = "uddi:uddi.org:sortorder:uts-10"; - - private boolean andAllKeys = false; - private boolean approximateMatch = false; - private boolean binarySort = false; - private boolean bindingSubset = false; - private boolean caseInsensitiveSort = false; - private boolean caseInsensitiveMatch = false; - private boolean caseSensitiveSort = false; - private boolean caseSensitiveMatch = false; - private boolean combineCategoryBags = false; - private boolean diacriticInsensitiveMatch = false; - private boolean diacriticSensitiveMatch = false; - private boolean exactMatch = false; - private boolean signaturePresent = false; - private boolean orAllKeys = false; - private boolean orLikeKeys = false; - private boolean serviceSubset = false; - private boolean sortByNameAsc = false; - private boolean sortByNameDesc = false; - private boolean sortByDateAsc = false; - private boolean sortByDateDesc = false; - private boolean suppressProjectedServices = false; - private boolean uts10 = false; - - public FindQualifiers() { - // These are the defaults as defined by the UDDI specification. - this.setExactMatch(true); - this.setCaseSensitiveMatch(true); - this.setCaseSensitiveSort(true); - this.setDiacriticSensitiveMatch(true); - - } - - public void mapApiFindQualifiers(org.uddi.api_v3.FindQualifiers apiFindQualifiers) - throws DispositionReportFaultMessage { - if (apiFindQualifiers == null) - return; - - List fqList = apiFindQualifiers.getFindQualifier(); - if (fqList != null) { - for (String fq : fqList) { - if (fq.equalsIgnoreCase(AND_ALL_KEYS) || fq.equalsIgnoreCase(AND_ALL_KEYS_TMODEL)) - this.setAndAllKeys(true); - else if (fq.equalsIgnoreCase(APPROXIMATE_MATCH) || fq.equalsIgnoreCase(APPROXIMATE_MATCH_TMODEL)) - this.setApproximateMatch(true); - else if (fq.equalsIgnoreCase(BINARY_SORT) || fq.equalsIgnoreCase(BINARY_SORT_TMODEL)) - this.setBinarySort(true); - else if (fq.equalsIgnoreCase(BINDING_SUBSET) || fq.equalsIgnoreCase(BINDING_SUBSET_TMODEL)) - this.setBindingSubset(true); - else if (fq.equalsIgnoreCase(CASE_INSENSITIVE_SORT) || fq.equalsIgnoreCase(CASE_INSENSITIVE_SORT_TMODEL)) - this.setCaseInsensitiveSort(true); - else if (fq.equalsIgnoreCase(CASE_INSENSITIVE_MATCH) || fq.equalsIgnoreCase(CASE_INSENSITIVE_MATCH_TMODEL)) - this.setCaseInsensitiveMatch(true); - else if (fq.equalsIgnoreCase(CASE_SENSITIVE_SORT) || fq.equalsIgnoreCase(CASE_SENSITIVE_SORT_TMODEL)) - this.setCaseSensitiveSort(true); - else if (fq.equalsIgnoreCase(CASE_SENSITIVE_MATCH) || fq.equalsIgnoreCase(CASE_SENSITIVE_MATCH_TMODEL)) - this.setCaseSensitiveMatch(true); - else if (fq.equalsIgnoreCase(COMBINE_CATEGORY_BAGS) || fq.equalsIgnoreCase(COMBINE_CATEGORY_BAGS_TMODEL)) - this.setCombineCategoryBags(true); - else if (fq.equalsIgnoreCase(DIACRITIC_INSENSITIVE_MATCH) || fq.equalsIgnoreCase(DIACRITIC_INSENSITIVE_MATCH_TMODEL)) - this.setDiacriticInsensitiveMatch(true); - else if (fq.equalsIgnoreCase(DIACRITIC_SENSITIVE_MATCH) || fq.equalsIgnoreCase(DIACRITIC_SENSITIVE_MATCH_TMODEL)) - this.setDiacriticSensitiveMatch(true); - else if (fq.equalsIgnoreCase(EXACT_MATCH) || fq.equalsIgnoreCase(EXACT_MATCH_TMODEL)) - this.setExactMatch(true); - else if (fq.equalsIgnoreCase(SIGNATURE_PRESENT) || fq.equalsIgnoreCase(SIGNATURE_PRESENT_TMODEL)) - this.setSignaturePresent(true); - else if (fq.equalsIgnoreCase(OR_ALL_KEYS) || fq.equalsIgnoreCase(OR_ALL_KEYS_TMODEL)) - this.setOrAllKeys(true); - else if (fq.equalsIgnoreCase(OR_LIKE_KEYS) || fq.equalsIgnoreCase(OR_LIKE_KEYS_TMODEL)) - this.setOrLikeKeys(true); - else if (fq.equalsIgnoreCase(SERVICE_SUBSET) || fq.equalsIgnoreCase(SERVICE_SUBSET_TMODEL)) - this.setServiceSubset(true); - else if (fq.equalsIgnoreCase(SORT_BY_NAME_ASC) || fq.equalsIgnoreCase(SORT_BY_NAME_ASC_TMODEL)) - this.setSortByNameAsc(true); - else if (fq.equalsIgnoreCase(SORT_BY_NAME_DESC) || fq.equalsIgnoreCase(SORT_BY_NAME_DESC_TMODEL)) - this.setSortByNameDesc(true); - else if (fq.equalsIgnoreCase(SORT_BY_DATE_ASC) || fq.equalsIgnoreCase(SORT_BY_DATE_ASC_TMODEL)) - this.setSortByDateAsc(true); - else if (fq.equalsIgnoreCase(SORT_BY_DATE_DESC) || fq.equalsIgnoreCase(SORT_BY_DATE_DESC_TMODEL)) - this.setSortByDateDesc(true); - else if (fq.equalsIgnoreCase(SUPPRESS_PROJECTED_SERVICES) || fq.equalsIgnoreCase(SUPPRESS_PROJECTED_SERVICES_TMODEL)) - this.setSuppressProjectedServices(true); - else if (fq.equalsIgnoreCase(UTS_10) || fq.equalsIgnoreCase(UTS_10_TMODEL)) - this.setUts10(true); - else - throw new UnsupportedException(new ErrorMessage("errors.Unsupported.findQualifier", fq)); - } - } - } - - public boolean isAndAllKeys() { - return andAllKeys; - } - public void setAndAllKeys(boolean andAllKeys) { - this.andAllKeys = andAllKeys; - this.orAllKeys = !andAllKeys; - this.orLikeKeys = !andAllKeys; - } - - public boolean isApproximateMatch() { - return approximateMatch; - } - public void setApproximateMatch(boolean approximateMatch) { - this.approximateMatch = approximateMatch; - this.exactMatch = !approximateMatch; - } - - public boolean isBinarySort() { - return binarySort; - } - public void setBinarySort(boolean binarySort) { - this.binarySort = binarySort; - this.uts10 = !binarySort; - } - - public boolean isBindingSubset() { - return bindingSubset; - } - public void setBindingSubset(boolean bindingSubset) { - this.bindingSubset = bindingSubset; - this.combineCategoryBags = !bindingSubset; - this.bindingSubset = !bindingSubset; - } - - public boolean isCaseInsensitiveSort() { - return caseInsensitiveSort; - } - public void setCaseInsensitiveSort(boolean caseInsensitiveSort) { - this.caseInsensitiveSort = caseInsensitiveSort; - this.caseSensitiveSort = !caseInsensitiveSort; - } - - public boolean isCaseInsensitiveMatch() { - return caseInsensitiveMatch; - } - public void setCaseInsensitiveMatch(boolean caseInsensitiveMatch) { - this.caseInsensitiveMatch = caseInsensitiveMatch; - this.caseSensitiveMatch = !caseInsensitiveMatch; - this.exactMatch = !caseInsensitiveMatch; - } - - public boolean isCaseSensitiveSort() { - return caseSensitiveSort; - } - public void setCaseSensitiveSort(boolean caseSensitiveSort) { - this.caseSensitiveSort = caseSensitiveSort; - this.caseInsensitiveSort = !caseSensitiveSort; - } - - public boolean isCaseSensitiveMatch() { - return caseSensitiveMatch; - } - public void setCaseSensitiveMatch(boolean caseSensitiveMatch) { - this.caseSensitiveMatch = caseSensitiveMatch; - this.caseInsensitiveMatch = !caseSensitiveMatch; - } - - public boolean isCombineCategoryBags() { - return combineCategoryBags; - } - public void setCombineCategoryBags(boolean combineCategoryBags) { - this.combineCategoryBags = combineCategoryBags; - this.serviceSubset = !combineCategoryBags; - this.bindingSubset = !combineCategoryBags; - } - - public boolean isDiacriticInsensitiveMatch() { - return diacriticInsensitiveMatch; - } - public void setDiacriticInsensitiveMatch(boolean diacriticInsensitiveMatch) { - this.diacriticInsensitiveMatch = diacriticInsensitiveMatch; - this.diacriticSensitiveMatch = !diacriticInsensitiveMatch; - } - - public boolean isDiacriticSensitiveMatch() { - return diacriticSensitiveMatch; - } - public void setDiacriticSensitiveMatch(boolean diacriticSensitiveMatch) { - this.diacriticSensitiveMatch = diacriticSensitiveMatch; - this.diacriticInsensitiveMatch = !diacriticSensitiveMatch; - } - - public boolean isExactMatch() { - return exactMatch; - } - public void setExactMatch(boolean exactMatch) { - this.exactMatch = exactMatch; - this.approximateMatch = !exactMatch; - this.caseInsensitiveMatch = !exactMatch; - } - - public boolean isSignaturePresent() { - return signaturePresent; - } - public void setSignaturePresent(boolean signaturePresent) { - this.signaturePresent = signaturePresent; - } - - public boolean isOrAllKeys() { - return orAllKeys; - } - public void setOrAllKeys(boolean orAllKeys) { - this.orAllKeys = orAllKeys; - this.andAllKeys = !orAllKeys; - this.orLikeKeys = !orAllKeys; - } - - public boolean isOrLikeKeys() { - return orLikeKeys; - } - public void setOrLikeKeys(boolean orLikeKeys) { - this.orLikeKeys = orLikeKeys; - this.andAllKeys = !orLikeKeys; - this.orAllKeys = !orLikeKeys; - } - - public boolean isServiceSubset() { - return serviceSubset; - } - public void setServiceSubset(boolean serviceSubset) { - this.serviceSubset = serviceSubset; - this.combineCategoryBags = !serviceSubset; - this.bindingSubset = !serviceSubset; - } - - public boolean isSortByNameAsc() { - return sortByNameAsc; - } - public void setSortByNameAsc(boolean sortByNameAsc) { - this.sortByNameAsc = sortByNameAsc; - this.sortByNameDesc = !sortByNameAsc; - } - - public boolean isSortByNameDesc() { - return sortByNameDesc; - } - public void setSortByNameDesc(boolean sortByNameDesc) { - this.sortByNameDesc = sortByNameDesc; - this.sortByNameAsc = !sortByNameDesc; - } - - public boolean isSortByDateAsc() { - return sortByDateAsc; - } - public void setSortByDateAsc(boolean sortByDateAsc) { - this.sortByDateAsc = sortByDateAsc; - this.sortByDateDesc = !sortByDateAsc; - } - - public boolean isSortByDateDesc() { - return sortByDateDesc; - } - public void setSortByDateDesc(boolean sortByDateDesc) { - this.sortByDateDesc = sortByDateDesc; - this.sortByDateAsc = !sortByDateDesc; - } - - public boolean isSuppressProjectedServices() { - return suppressProjectedServices; - } - public void setSuppressProjectedServices(boolean suppressProjectedServices) { - this.suppressProjectedServices = suppressProjectedServices; - } - - public boolean isUts10() { - return uts10; - } - public void setUts10(boolean uts10) { - this.uts10 = uts10; - this.binarySort = !uts10; - } - - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query.util; + +import java.util.List; + +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.UnsupportedException; +import org.uddi.v3_service.DispositionReportFaultMessage; + +/** + * @author Jeff Faath + */ +public class FindQualifiers { + + public static final String AND_ALL_KEYS = "andAllKeys"; + public static final String AND_ALL_KEYS_TMODEL = "uddi:uddi.org:findqualifier:andallkeys"; + + public static final String APPROXIMATE_MATCH = "approximateMatch"; + public static final String APPROXIMATE_MATCH_TMODEL = "uddi:uddi.org:findqualifier:approximatematch"; + + public static final String BINARY_SORT = "binarySort"; + public static final String BINARY_SORT_TMODEL = "uddi:uddi.org:sortorder:binarysort"; + + public static final String BINDING_SUBSET = "bindingSubset"; + public static final String BINDING_SUBSET_TMODEL = "uddi:uddi.org:findqualifier:bindingsubset"; + + public static final String CASE_INSENSITIVE_SORT = "caseInsensitiveSort"; + public static final String CASE_INSENSITIVE_SORT_TMODEL = "uddi:uddi.org:findqualifier:caseinsensitivesort"; + + public static final String CASE_INSENSITIVE_MATCH = "caseInsensitiveMatch"; + public static final String CASE_INSENSITIVE_MATCH_TMODEL = "uddi:uddi.org:findqualifier:caseinsensitivematch"; + + public static final String CASE_SENSITIVE_SORT = "caseSensitiveSort"; + public static final String CASE_SENSITIVE_SORT_TMODEL = "uddi:uddi.org:findqualifier:casesensitivesort"; + + public static final String CASE_SENSITIVE_MATCH = "caseSensitiveMatch"; + public static final String CASE_SENSITIVE_MATCH_TMODEL = "uddi:uddi.org:findqualifier:casesensitivematch"; + + public static final String COMBINE_CATEGORY_BAGS = "combineCategoryBags"; + public static final String COMBINE_CATEGORY_BAGS_TMODEL = "uddi:uddi.org:findqualifier:combinecategorybags"; + + public static final String DIACRITIC_INSENSITIVE_MATCH = "diacriticInsensitiveMatch"; + public static final String DIACRITIC_INSENSITIVE_MATCH_TMODEL = "uddi:uddi.org:findqualifier:diacriticsinsensitivematch"; + + public static final String DIACRITIC_SENSITIVE_MATCH = "diacriticSensitiveMatch"; + public static final String DIACRITIC_SENSITIVE_MATCH_TMODEL = "uddi:uddi.org:findqualifier:diacriticssensitivematch"; + + public static final String EXACT_MATCH = "exactMatch"; + public static final String EXACT_MATCH_TMODEL = "uddi:uddi.org:findqualifier:exactmatch"; + + public static final String SIGNATURE_PRESENT = "signaturePresent"; + public static final String SIGNATURE_PRESENT_TMODEL = "uddi:uddi.org:findqualifier:signaturepresent"; + + public static final String OR_ALL_KEYS = "orAllKeys"; + public static final String OR_ALL_KEYS_TMODEL = "uddi:uddi.org:findqualifier:orallkeys"; + + public static final String OR_LIKE_KEYS = "orLikeKeys"; + public static final String OR_LIKE_KEYS_TMODEL = "uddi:uddi.org:findqualifier:orlikekeys"; + + public static final String SERVICE_SUBSET = "serviceSubset"; + public static final String SERVICE_SUBSET_TMODEL = "uddi:uddi.org:findqualifier:servicesubset"; + + public static final String SORT_BY_NAME_ASC = "sortByNameAsc"; + public static final String SORT_BY_NAME_ASC_TMODEL = "uddi:uddi.org:findqualifier:sortbynameasc"; + + public static final String SORT_BY_NAME_DESC = "sortByNameDesc"; + public static final String SORT_BY_NAME_DESC_TMODEL = "uddi:uddi.org:findqualifier:sortbynamedesc"; + + public static final String SORT_BY_DATE_ASC = "sortByDateAsc"; + public static final String SORT_BY_DATE_ASC_TMODEL = "uddi:uddi.org:findqualifier:sortbydateasc"; + + public static final String SORT_BY_DATE_DESC = "sortByDateDesc"; + public static final String SORT_BY_DATE_DESC_TMODEL = "uddi:uddi.org:findqualifier:sortbydatedesc"; + + public static final String SUPPRESS_PROJECTED_SERVICES = "suppressProjectedServices"; + public static final String SUPPRESS_PROJECTED_SERVICES_TMODEL = "uddi:uddi.org:findqualifier:suppressprojectedservices"; + + public static final String UTS_10 = "UTS-10"; + public static final String UTS_10_TMODEL = "uddi:uddi.org:sortorder:uts-10"; + + private boolean andAllKeys = false; + private boolean approximateMatch = false; + private boolean binarySort = false; + private boolean bindingSubset = false; + private boolean caseInsensitiveSort = false; + private boolean caseInsensitiveMatch = false; + private boolean caseSensitiveSort = false; + private boolean caseSensitiveMatch = false; + private boolean combineCategoryBags = false; + private boolean diacriticInsensitiveMatch = false; + private boolean diacriticSensitiveMatch = false; + private boolean exactMatch = false; + private boolean signaturePresent = false; + private boolean orAllKeys = false; + private boolean orLikeKeys = false; + private boolean serviceSubset = false; + private boolean sortByNameAsc = false; + private boolean sortByNameDesc = false; + private boolean sortByDateAsc = false; + private boolean sortByDateDesc = false; + private boolean suppressProjectedServices = false; + private boolean uts10 = false; + + public FindQualifiers() { + // These are the defaults as defined by the UDDI specification. + this.setExactMatch(true); + this.setCaseSensitiveMatch(true); + this.setCaseSensitiveSort(true); + this.setDiacriticSensitiveMatch(true); + + } + + public void mapApiFindQualifiers(org.uddi.api_v3.FindQualifiers apiFindQualifiers) + throws DispositionReportFaultMessage { + if (apiFindQualifiers == null) + return; + + List fqList = apiFindQualifiers.getFindQualifier(); + if (fqList != null) { + for (String fq : fqList) { + if (fq.equalsIgnoreCase(AND_ALL_KEYS) || fq.equalsIgnoreCase(AND_ALL_KEYS_TMODEL)) + this.setAndAllKeys(true); + else if (fq.equalsIgnoreCase(APPROXIMATE_MATCH) || fq.equalsIgnoreCase(APPROXIMATE_MATCH_TMODEL)) + this.setApproximateMatch(true); + else if (fq.equalsIgnoreCase(BINARY_SORT) || fq.equalsIgnoreCase(BINARY_SORT_TMODEL)) + this.setBinarySort(true); + else if (fq.equalsIgnoreCase(BINDING_SUBSET) || fq.equalsIgnoreCase(BINDING_SUBSET_TMODEL)) + this.setBindingSubset(true); + else if (fq.equalsIgnoreCase(CASE_INSENSITIVE_SORT) || fq.equalsIgnoreCase(CASE_INSENSITIVE_SORT_TMODEL)) + this.setCaseInsensitiveSort(true); + else if (fq.equalsIgnoreCase(CASE_INSENSITIVE_MATCH) || fq.equalsIgnoreCase(CASE_INSENSITIVE_MATCH_TMODEL)) + this.setCaseInsensitiveMatch(true); + else if (fq.equalsIgnoreCase(CASE_SENSITIVE_SORT) || fq.equalsIgnoreCase(CASE_SENSITIVE_SORT_TMODEL)) + this.setCaseSensitiveSort(true); + else if (fq.equalsIgnoreCase(CASE_SENSITIVE_MATCH) || fq.equalsIgnoreCase(CASE_SENSITIVE_MATCH_TMODEL)) + this.setCaseSensitiveMatch(true); + else if (fq.equalsIgnoreCase(COMBINE_CATEGORY_BAGS) || fq.equalsIgnoreCase(COMBINE_CATEGORY_BAGS_TMODEL)) + this.setCombineCategoryBags(true); + else if (fq.equalsIgnoreCase(DIACRITIC_INSENSITIVE_MATCH) || fq.equalsIgnoreCase(DIACRITIC_INSENSITIVE_MATCH_TMODEL)) + this.setDiacriticInsensitiveMatch(true); + else if (fq.equalsIgnoreCase(DIACRITIC_SENSITIVE_MATCH) || fq.equalsIgnoreCase(DIACRITIC_SENSITIVE_MATCH_TMODEL)) + this.setDiacriticSensitiveMatch(true); + else if (fq.equalsIgnoreCase(EXACT_MATCH) || fq.equalsIgnoreCase(EXACT_MATCH_TMODEL)) + this.setExactMatch(true); + else if (fq.equalsIgnoreCase(SIGNATURE_PRESENT) || fq.equalsIgnoreCase(SIGNATURE_PRESENT_TMODEL)) + this.setSignaturePresent(true); + else if (fq.equalsIgnoreCase(OR_ALL_KEYS) || fq.equalsIgnoreCase(OR_ALL_KEYS_TMODEL)) + this.setOrAllKeys(true); + else if (fq.equalsIgnoreCase(OR_LIKE_KEYS) || fq.equalsIgnoreCase(OR_LIKE_KEYS_TMODEL)) + this.setOrLikeKeys(true); + else if (fq.equalsIgnoreCase(SERVICE_SUBSET) || fq.equalsIgnoreCase(SERVICE_SUBSET_TMODEL)) + this.setServiceSubset(true); + else if (fq.equalsIgnoreCase(SORT_BY_NAME_ASC) || fq.equalsIgnoreCase(SORT_BY_NAME_ASC_TMODEL)) + this.setSortByNameAsc(true); + else if (fq.equalsIgnoreCase(SORT_BY_NAME_DESC) || fq.equalsIgnoreCase(SORT_BY_NAME_DESC_TMODEL)) + this.setSortByNameDesc(true); + else if (fq.equalsIgnoreCase(SORT_BY_DATE_ASC) || fq.equalsIgnoreCase(SORT_BY_DATE_ASC_TMODEL)) + this.setSortByDateAsc(true); + else if (fq.equalsIgnoreCase(SORT_BY_DATE_DESC) || fq.equalsIgnoreCase(SORT_BY_DATE_DESC_TMODEL)) + this.setSortByDateDesc(true); + else if (fq.equalsIgnoreCase(SUPPRESS_PROJECTED_SERVICES) || fq.equalsIgnoreCase(SUPPRESS_PROJECTED_SERVICES_TMODEL)) + this.setSuppressProjectedServices(true); + else if (fq.equalsIgnoreCase(UTS_10) || fq.equalsIgnoreCase(UTS_10_TMODEL)) + this.setUts10(true); + else + throw new UnsupportedException(new ErrorMessage("errors.Unsupported.findQualifier", fq)); + } + } + } + + public boolean isAndAllKeys() { + return andAllKeys; + } + public void setAndAllKeys(boolean andAllKeys) { + this.andAllKeys = andAllKeys; + this.orAllKeys = !andAllKeys; + this.orLikeKeys = !andAllKeys; + } + + public boolean isApproximateMatch() { + return approximateMatch; + } + public void setApproximateMatch(boolean approximateMatch) { + this.approximateMatch = approximateMatch; + this.exactMatch = !approximateMatch; + } + + public boolean isBinarySort() { + return binarySort; + } + public void setBinarySort(boolean binarySort) { + this.binarySort = binarySort; + this.uts10 = !binarySort; + } + + public boolean isBindingSubset() { + return bindingSubset; + } + public void setBindingSubset(boolean bindingSubset) { + this.bindingSubset = bindingSubset; + this.combineCategoryBags = !bindingSubset; + this.bindingSubset = !bindingSubset; + } + + public boolean isCaseInsensitiveSort() { + return caseInsensitiveSort; + } + public void setCaseInsensitiveSort(boolean caseInsensitiveSort) { + this.caseInsensitiveSort = caseInsensitiveSort; + this.caseSensitiveSort = !caseInsensitiveSort; + } + + public boolean isCaseInsensitiveMatch() { + return caseInsensitiveMatch; + } + public void setCaseInsensitiveMatch(boolean caseInsensitiveMatch) { + this.caseInsensitiveMatch = caseInsensitiveMatch; + this.caseSensitiveMatch = !caseInsensitiveMatch; + this.exactMatch = !caseInsensitiveMatch; + } + + public boolean isCaseSensitiveSort() { + return caseSensitiveSort; + } + public void setCaseSensitiveSort(boolean caseSensitiveSort) { + this.caseSensitiveSort = caseSensitiveSort; + this.caseInsensitiveSort = !caseSensitiveSort; + } + + public boolean isCaseSensitiveMatch() { + return caseSensitiveMatch; + } + public void setCaseSensitiveMatch(boolean caseSensitiveMatch) { + this.caseSensitiveMatch = caseSensitiveMatch; + this.caseInsensitiveMatch = !caseSensitiveMatch; + } + + public boolean isCombineCategoryBags() { + return combineCategoryBags; + } + public void setCombineCategoryBags(boolean combineCategoryBags) { + this.combineCategoryBags = combineCategoryBags; + this.serviceSubset = !combineCategoryBags; + this.bindingSubset = !combineCategoryBags; + } + + public boolean isDiacriticInsensitiveMatch() { + return diacriticInsensitiveMatch; + } + public void setDiacriticInsensitiveMatch(boolean diacriticInsensitiveMatch) { + this.diacriticInsensitiveMatch = diacriticInsensitiveMatch; + this.diacriticSensitiveMatch = !diacriticInsensitiveMatch; + } + + public boolean isDiacriticSensitiveMatch() { + return diacriticSensitiveMatch; + } + public void setDiacriticSensitiveMatch(boolean diacriticSensitiveMatch) { + this.diacriticSensitiveMatch = diacriticSensitiveMatch; + this.diacriticInsensitiveMatch = !diacriticSensitiveMatch; + } + + public boolean isExactMatch() { + return exactMatch; + } + public void setExactMatch(boolean exactMatch) { + this.exactMatch = exactMatch; + this.approximateMatch = !exactMatch; + this.caseInsensitiveMatch = !exactMatch; + } + + public boolean isSignaturePresent() { + return signaturePresent; + } + public void setSignaturePresent(boolean signaturePresent) { + this.signaturePresent = signaturePresent; + } + + public boolean isOrAllKeys() { + return orAllKeys; + } + public void setOrAllKeys(boolean orAllKeys) { + this.orAllKeys = orAllKeys; + this.andAllKeys = !orAllKeys; + this.orLikeKeys = !orAllKeys; + } + + public boolean isOrLikeKeys() { + return orLikeKeys; + } + public void setOrLikeKeys(boolean orLikeKeys) { + this.orLikeKeys = orLikeKeys; + this.andAllKeys = !orLikeKeys; + this.orAllKeys = !orLikeKeys; + } + + public boolean isServiceSubset() { + return serviceSubset; + } + public void setServiceSubset(boolean serviceSubset) { + this.serviceSubset = serviceSubset; + this.combineCategoryBags = !serviceSubset; + this.bindingSubset = !serviceSubset; + } + + public boolean isSortByNameAsc() { + return sortByNameAsc; + } + public void setSortByNameAsc(boolean sortByNameAsc) { + this.sortByNameAsc = sortByNameAsc; + this.sortByNameDesc = !sortByNameAsc; + } + + public boolean isSortByNameDesc() { + return sortByNameDesc; + } + public void setSortByNameDesc(boolean sortByNameDesc) { + this.sortByNameDesc = sortByNameDesc; + this.sortByNameAsc = !sortByNameDesc; + } + + public boolean isSortByDateAsc() { + return sortByDateAsc; + } + public void setSortByDateAsc(boolean sortByDateAsc) { + this.sortByDateAsc = sortByDateAsc; + this.sortByDateDesc = !sortByDateAsc; + } + + public boolean isSortByDateDesc() { + return sortByDateDesc; + } + public void setSortByDateDesc(boolean sortByDateDesc) { + this.sortByDateDesc = sortByDateDesc; + this.sortByDateAsc = !sortByDateDesc; + } + + public boolean isSuppressProjectedServices() { + return suppressProjectedServices; + } + public void setSuppressProjectedServices(boolean suppressProjectedServices) { + this.suppressProjectedServices = suppressProjectedServices; + } + + public boolean isUts10() { + return uts10; + } + public void setUts10(boolean uts10) { + this.uts10 = uts10; + this.binarySort = !uts10; + } + + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/util/KeyedRefGroupTModelComparator.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/util/KeyedRefGroupTModelComparator.java similarity index 96% rename from juddi-core/src/main/java/org/apache/juddi/query/util/KeyedRefGroupTModelComparator.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/util/KeyedRefGroupTModelComparator.java index 713fbe4b9..dbc6acd8c 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/util/KeyedRefGroupTModelComparator.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/util/KeyedRefGroupTModelComparator.java @@ -1,48 +1,48 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query.util; - -import java.io.Serializable; -import java.util.Comparator; -import org.uddi.api_v3.KeyedReferenceGroup; - -/** - * @author Jeff Faath - */ -public class KeyedRefGroupTModelComparator implements Comparator, Serializable { - private static final long serialVersionUID = 1L; - - public int compare(KeyedReferenceGroup krg1, KeyedReferenceGroup krg2) { - if (krg1 == null && krg2 == null) - return 0; - if (krg1 == null) - return -1; - if (krg2 == null) - return 1; - - if (krg1.getTModelKey() == null && krg2.getTModelKey() == null) - return 0; - if (krg1.getTModelKey() == null) - return -1; - if (krg2.getTModelKey() == null) - return 1; - - return krg1.getTModelKey().compareTo(krg2.getTModelKey()); - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query.util; + +import java.io.Serializable; +import java.util.Comparator; +import org.uddi.api_v3.KeyedReferenceGroup; + +/** + * @author Jeff Faath + */ +public class KeyedRefGroupTModelComparator implements Comparator, Serializable { + private static final long serialVersionUID = 1L; + + public int compare(KeyedReferenceGroup krg1, KeyedReferenceGroup krg2) { + if (krg1 == null && krg2 == null) + return 0; + if (krg1 == null) + return -1; + if (krg2 == null) + return 1; + + if (krg1.getTModelKey() == null && krg2.getTModelKey() == null) + return 0; + if (krg1.getTModelKey() == null) + return -1; + if (krg2.getTModelKey() == null) + return 1; + + return krg1.getTModelKey().compareTo(krg2.getTModelKey()); + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/query/util/KeyedRefTModelComparator.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/util/KeyedRefTModelComparator.java similarity index 96% rename from juddi-core/src/main/java/org/apache/juddi/query/util/KeyedRefTModelComparator.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/query/util/KeyedRefTModelComparator.java index 67669dd34..2f959f8eb 100644 --- a/juddi-core/src/main/java/org/apache/juddi/query/util/KeyedRefTModelComparator.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/query/util/KeyedRefTModelComparator.java @@ -1,48 +1,48 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.query.util; - -import java.io.Serializable; -import java.util.Comparator; -import org.uddi.api_v3.KeyedReference; - -/** - * @author Jeff Faath - */ -public class KeyedRefTModelComparator implements Comparator, Serializable { - private static final long serialVersionUID = 1L; - - public int compare(KeyedReference kr1, KeyedReference kr2) { - if (kr1 == null && kr2 == null) - return 0; - if (kr1 == null) - return -1; - if (kr2 == null) - return 1; - - if (kr1.getTModelKey() == null && kr2.getTModelKey() == null) - return 0; - if (kr1.getTModelKey() == null) - return -1; - if (kr2.getTModelKey() == null) - return 1; - - return kr1.getTModelKey().compareTo(kr2.getTModelKey()); - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.query.util; + +import java.io.Serializable; +import java.util.Comparator; +import org.uddi.api_v3.KeyedReference; + +/** + * @author Jeff Faath + */ +public class KeyedRefTModelComparator implements Comparator, Serializable { + private static final long serialVersionUID = 1L; + + public int compare(KeyedReference kr1, KeyedReference kr2) { + if (kr1 == null && kr2 == null) + return 0; + if (kr1 == null) + return -1; + if (kr2 == null) + return 1; + + if (kr1.getTModelKey() == null && kr2.getTModelKey() == null) + return 0; + if (kr1.getTModelKey() == null) + return -1; + if (kr2.getTModelKey() == null) + return 1; + + return kr1.getTModelKey().compareTo(kr2.getTModelKey()); + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/replication/ReplicationNotifier.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/replication/ReplicationNotifier.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/replication/ReplicationNotifier.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/replication/ReplicationNotifier.java diff --git a/juddi-core/src/main/java/org/apache/juddi/subscription/NotificationList.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/NotificationList.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/subscription/NotificationList.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/NotificationList.java diff --git a/juddi-core/src/main/java/org/apache/juddi/subscription/SubscriptionNotifier.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/SubscriptionNotifier.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/subscription/SubscriptionNotifier.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/SubscriptionNotifier.java diff --git a/juddi-core/src/main/java/org/apache/juddi/subscription/TypeConvertor.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/TypeConvertor.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/subscription/TypeConvertor.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/TypeConvertor.java diff --git a/juddi-core/src/main/java/org/apache/juddi/subscription/notify/HTTPNotifier.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/notify/HTTPNotifier.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/subscription/notify/HTTPNotifier.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/notify/HTTPNotifier.java diff --git a/juddi-core/src/main/java/org/apache/juddi/subscription/notify/Notifier.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/notify/Notifier.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/subscription/notify/Notifier.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/notify/Notifier.java diff --git a/juddi-core/src/main/java/org/apache/juddi/subscription/notify/NotifierFactory.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/notify/NotifierFactory.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/subscription/notify/NotifierFactory.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/notify/NotifierFactory.java diff --git a/juddi-core/src/main/java/org/apache/juddi/subscription/notify/SMTPNotifier.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/notify/SMTPNotifier.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/subscription/notify/SMTPNotifier.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/notify/SMTPNotifier.java diff --git a/juddi-core/src/main/java/org/apache/juddi/subscription/notify/TemporaryMailContainer.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/notify/TemporaryMailContainer.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/subscription/notify/TemporaryMailContainer.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/notify/TemporaryMailContainer.java diff --git a/juddi-core/src/main/java/org/apache/juddi/subscription/notify/USERFRIENDLYSMTPNotifier.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/notify/USERFRIENDLYSMTPNotifier.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/subscription/notify/USERFRIENDLYSMTPNotifier.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/notify/USERFRIENDLYSMTPNotifier.java diff --git a/juddi-core/src/main/java/org/apache/juddi/subscription/notify/package-info.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/notify/package-info.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/subscription/notify/package-info.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/notify/package-info.java diff --git a/juddi-core/src/main/java/org/apache/juddi/subscription/package-info.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/package-info.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/subscription/package-info.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/subscription/package-info.java diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/auth/Authenticator.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/Authenticator.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/auth/Authenticator.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/Authenticator.java index 35bb1b391..73941cf51 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/auth/Authenticator.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/Authenticator.java @@ -1,61 +1,61 @@ -/* - * Copyright 2001-2009 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.auth; - -import javax.xml.ws.WebServiceContext; -import org.apache.juddi.model.UddiEntityPublisher; -import org.apache.juddi.v3.error.AuthenticationException; -import org.apache.juddi.v3.error.FatalErrorException; - -/** - * Authenticator interface. Any class implementing this interface can be invoked by - * the AuthenticatorFactory to handle authentication of the user executing a UDDI request. - * - * This occurs in two steps: - * - * 1) Authenticating the user based the passed credentials - * 2) Identifying the user by associating either the authorizationKey or user Id with publisher information - * - * @author Steve Viens (sviens@apache.org) - * @author Jeff Faath - */ -public interface Authenticator { - - /** - * This function is called from the Security API's GetAuthToken(). - * - * @param authorizedName - userId of the user making the registry request - * @param cred - some authentical creditial (i.e. a password) which can be used to - * authenticate the user. - * - * @return The publisherID for this user - * @throws org.apache.juddi.v3.error.AuthenticationException - * @throws org.apache.juddi.v3.error.FatalErrorException - */ - String authenticate(String authorizedName, String cred) throws AuthenticationException, FatalErrorException; - - /* - * Either input parameter can be used to populate the publisher object - * - * @param authInfo - the authorization token - * @param authorizedName - the authorized Name - * @param ctx - WebServiceContext, used for HTTP based authentication if desired (since 3.2.1) - * @return - The entity publisher - */ - UddiEntityPublisher identify(String authInfo, String authorizedName, WebServiceContext ctx) throws AuthenticationException, FatalErrorException; -} +/* + * Copyright 2001-2009 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.auth; + +import javax.xml.ws.WebServiceContext; +import org.apache.juddi.model.UddiEntityPublisher; +import org.apache.juddi.v3.error.AuthenticationException; +import org.apache.juddi.v3.error.FatalErrorException; + +/** + * Authenticator interface. Any class implementing this interface can be invoked by + * the AuthenticatorFactory to handle authentication of the user executing a UDDI request. + * + * This occurs in two steps: + * + * 1) Authenticating the user based the passed credentials + * 2) Identifying the user by associating either the authorizationKey or user Id with publisher information + * + * @author Steve Viens (sviens@apache.org) + * @author Jeff Faath + */ +public interface Authenticator { + + /** + * This function is called from the Security API's GetAuthToken(). + * + * @param authorizedName - userId of the user making the registry request + * @param cred - some authentical creditial (i.e. a password) which can be used to + * authenticate the user. + * + * @return The publisherID for this user + * @throws org.apache.juddi.v3.error.AuthenticationException + * @throws org.apache.juddi.v3.error.FatalErrorException + */ + String authenticate(String authorizedName, String cred) throws AuthenticationException, FatalErrorException; + + /* + * Either input parameter can be used to populate the publisher object + * + * @param authInfo - the authorization token + * @param authorizedName - the authorized Name + * @param ctx - WebServiceContext, used for HTTP based authentication if desired (since 3.2.1) + * @return - The entity publisher + */ + UddiEntityPublisher identify(String authInfo, String authorizedName, WebServiceContext ctx) throws AuthenticationException, FatalErrorException; +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/auth/AuthenticatorFactory.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/AuthenticatorFactory.java similarity index 96% rename from juddi-core/src/main/java/org/apache/juddi/v3/auth/AuthenticatorFactory.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/AuthenticatorFactory.java index c7637f8ea..595aa4e90 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/auth/AuthenticatorFactory.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/AuthenticatorFactory.java @@ -1,99 +1,99 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.auth; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.ClassUtil; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.Property; - - -/** - * @author Steve Viens (sviens@apache.org) - * @author Jeff Faath - */ -public class AuthenticatorFactory { - private static Log log = LogFactory.getLog(AuthenticatorFactory.class); - - // Default authenticator implementation - private static final String DEFAULT_IMPL = "org.apache.juddi.v3.auth.JUDDIAuthenticator"; - - // the shared Authenticator instance - private static Authenticator auth = null; - - - /** - * Returns a new instance of a AuthenticatorFactory. - * - * @return Authenticator - */ - public static synchronized Authenticator getAuthenticator() { - if (auth == null) - auth = createAuthenticator(); - return auth; - } - - /** - * Returns a new instance of a Authenticator. - * - * @return Authenticator - */ - private static synchronized Authenticator createAuthenticator() { - if (auth != null) - return auth; - - String className = DEFAULT_IMPL; - try { - // grab class name of the Authenticator implementation to create - className = AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR, DEFAULT_IMPL); - } - catch(ConfigurationException ce) { - log.error("Configuration exception occurred retrieving: " + Property.JUDDI_AUTHENTICATOR); - } - - // write the Authenticator implementation name to the log - log.debug("Authenticator Implementation = " + className); - - Class authClass = null; - try { - // Use Loader to locate & load the Authenticator implementation - authClass = ClassUtil.forName(className, AuthenticatorFactory.class); - } - catch(ClassNotFoundException e) { - log.error("The specified Authenticator class '" + className + "' was not found in classpath."); - log.error(e); - } - - try { - if (authClass!=null) { - // try to instantiate the Authenticator implementation - auth = (Authenticator)authClass.newInstance(); - } else { - log.error("Could not load " + className + " authClass is null"); - } - } - catch(Exception e) { - log.error("Exception while attempting to instantiate the implementation of Authenticator: " + className + "\n" + e.getMessage()); - log.error(e); - } - - return auth; - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.auth; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.ClassUtil; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.Property; + + +/** + * @author Steve Viens (sviens@apache.org) + * @author Jeff Faath + */ +public class AuthenticatorFactory { + private static Log log = LogFactory.getLog(AuthenticatorFactory.class); + + // Default authenticator implementation + private static final String DEFAULT_IMPL = "org.apache.juddi.v3.auth.JUDDIAuthenticator"; + + // the shared Authenticator instance + private static Authenticator auth = null; + + + /** + * Returns a new instance of a AuthenticatorFactory. + * + * @return Authenticator + */ + public static synchronized Authenticator getAuthenticator() { + if (auth == null) + auth = createAuthenticator(); + return auth; + } + + /** + * Returns a new instance of a Authenticator. + * + * @return Authenticator + */ + private static synchronized Authenticator createAuthenticator() { + if (auth != null) + return auth; + + String className = DEFAULT_IMPL; + try { + // grab class name of the Authenticator implementation to create + className = AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR, DEFAULT_IMPL); + } + catch(ConfigurationException ce) { + log.error("Configuration exception occurred retrieving: " + Property.JUDDI_AUTHENTICATOR); + } + + // write the Authenticator implementation name to the log + log.debug("Authenticator Implementation = " + className); + + Class authClass = null; + try { + // Use Loader to locate & load the Authenticator implementation + authClass = ClassUtil.forName(className, AuthenticatorFactory.class); + } + catch(ClassNotFoundException e) { + log.error("The specified Authenticator class '" + className + "' was not found in classpath."); + log.error(e); + } + + try { + if (authClass!=null) { + // try to instantiate the Authenticator implementation + auth = (Authenticator)authClass.newInstance(); + } else { + log.error("Could not load " + className + " authClass is null"); + } + } + catch(Exception e) { + log.error("Exception while attempting to instantiate the implementation of Authenticator: " + className + "\n" + e.getMessage()); + log.error(e); + } + + return auth; + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/auth/CryptedXMLDocAuthenticator.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/CryptedXMLDocAuthenticator.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/auth/CryptedXMLDocAuthenticator.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/CryptedXMLDocAuthenticator.java index b58177327..ce226a087 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/auth/CryptedXMLDocAuthenticator.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/CryptedXMLDocAuthenticator.java @@ -1,201 +1,201 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.auth; - -import java.io.IOException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; - -import javax.crypto.BadPaddingException; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.persistence.EntityManager; -import javax.persistence.EntityTransaction; -import javax.xml.bind.JAXBException; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.PersistenceManager; -import org.apache.juddi.config.Property; -import org.apache.juddi.v3.client.cryptor.Cryptor; -import org.apache.juddi.cryptor.CryptorFactory; -import org.apache.juddi.model.Publisher; -import static org.apache.juddi.v3.auth.XMLDocAuthenticator.log; -import org.apache.juddi.v3.error.AuthenticationException; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.FatalErrorException; -import org.apache.juddi.v3.error.RegistryException; -import org.apache.juddi.v3.error.UnknownUserException; - -/** - * @author Anou Manavalan - */ -public class CryptedXMLDocAuthenticator extends XMLDocAuthenticator { - - private Log logger = LogFactory.getLog(this.getClass()); - /** - * @throws IOException - * @throws JAXBException - * @throws ConfigurationException - * - */ - public CryptedXMLDocAuthenticator() throws JAXBException, IOException, ConfigurationException { - super(); - } - - private CryptedXMLDocAuthenticator(boolean b) { - super(b); - } - @Override - protected String getFilename() throws ConfigurationException { - return AppConfig.getConfiguration().getString(Property.JUDDI_USERSFILE, Property.DEFAULT_ENCRYPTED_XML_USERSFILE); - } - /** - * - * @return user id - * @throws org.apache.juddi.v3.error.AuthenticationException - * @throws org.apache.juddi.v3.error.FatalErrorException - */ - public String authenticate(String userID, String credential) - throws AuthenticationException, FatalErrorException { - preProcess(userID, credential); - String encryptedCredential = encrypt(credential); - return postProcess(userID, encryptedCredential); - } - /** - * - */ - private String encrypt(String str) throws FatalErrorException { - try { - Cryptor cryptor = (Cryptor) CryptorFactory.getCryptor(); - return cryptor.encrypt(str); - } catch (InvalidKeyException e) { - logger.error("Invalid Key Exception in crypting the password", e); - throw new FatalErrorException(new ErrorMessage( - "errors.auth.cryptor.InvalidKey", e.getMessage())); - } catch (NoSuchPaddingException e) { - logger.error("Padding Exception in crypting the password", e); - throw new FatalErrorException(new ErrorMessage( - "errors.auth.cryptor.Padding", e.getMessage())); - } catch (NoSuchAlgorithmException e) { - logger.error("Algorithm Exception in crypting the password", e); - throw new FatalErrorException(new ErrorMessage( - "errors.auth.cryptor.Algorithm", e.getMessage())); - } catch (InvalidAlgorithmParameterException e) { - logger.error("Algorithm parameter Exception in crypting the password", - e); - throw new FatalErrorException(new ErrorMessage( - "errors.auth.cryptor.AlgorithmParam", e.getMessage())); - } catch (IllegalBlockSizeException e) { - logger.error("Block size Exception in crypting the password", e); - throw new FatalErrorException(new ErrorMessage( - "errors.auth.cryptor.BlockSize", e.getMessage())); - } catch (BadPaddingException e) { - logger.error("Bad Padding Exception in crypting the password", e); - throw new FatalErrorException(new ErrorMessage( - "errors.auth.cryptor.BadPadding", e.getMessage())); - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw new FatalErrorException(new ErrorMessage( - "errors.auth.cryptor.BlockSize", e.getMessage())); - } - } - /** - * @param userID - * @param credential - * @throws RegistryException - */ - private void preProcess(String userID, String credential) - throws AuthenticationException { - // a userID must be specified. - if (userID == null) { - throw new UnknownUserException(new ErrorMessage( - "errors.auth.InvalidUserId")); - } - // credential (password) must be specified. - if (credential == null) { - throw new UnknownUserException(new ErrorMessage( - "errors.auth.InvalidCredentials")); - } - } - /** - * @param userID - * @param encryptedCredential - * @return user id - * @throws AuthenticationException - */ - private String postProcess(String userID, String encryptedCredential) - throws AuthenticationException { - if (userTable.containsKey(userID)) { - User user = (User) userTable.get(userID); - if ((user.getPassword() == null) - || (!encryptedCredential.equals(user.getPassword()))) { - throw new UnknownUserException(new ErrorMessage( - "errors.auth.InvalidCredentials", userID)); - } - } else { - throw new UnknownUserException(new ErrorMessage( - "errors.auth.InvalidUserId", userID)); - } - int MaxBindingsPerService = -1; - int MaxServicesPerBusiness = -1; - int MaxTmodels = -1; - int MaxBusinesses = -1; - try { - MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE, -1); - MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS, -1); - MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1); - MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1); - } catch (Exception ex) { - MaxBindingsPerService = -1; - MaxServicesPerBusiness = -1; - MaxTmodels = -1; - MaxBusinesses = -1; - log.error("config exception! " + userID, ex); - } - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - Publisher publisher = em.find(Publisher.class, userID); - if (publisher == null) { - log.warn("Publisher \"" + userID + "\" was not found in the database, adding the publisher in on the fly."); - publisher = new Publisher(); - publisher.setAuthorizedName(userID); - publisher.setIsAdmin("false"); - publisher.setIsEnabled("true"); - publisher.setMaxBindingsPerService(MaxBindingsPerService); - publisher.setMaxBusinesses(MaxBusinesses); - publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness); - publisher.setMaxTmodels(MaxTmodels); - publisher.setPublisherName("Unknown"); - em.persist(publisher); - tx.commit(); - } - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - return userID; - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.auth; + +import java.io.IOException; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; + +import javax.crypto.BadPaddingException; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.xml.bind.JAXBException; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.PersistenceManager; +import org.apache.juddi.config.Property; +import org.apache.juddi.v3.client.cryptor.Cryptor; +import org.apache.juddi.cryptor.CryptorFactory; +import org.apache.juddi.model.Publisher; +import static org.apache.juddi.v3.auth.XMLDocAuthenticator.log; +import org.apache.juddi.v3.error.AuthenticationException; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.FatalErrorException; +import org.apache.juddi.v3.error.RegistryException; +import org.apache.juddi.v3.error.UnknownUserException; + +/** + * @author Anou Manavalan + */ +public class CryptedXMLDocAuthenticator extends XMLDocAuthenticator { + + private Log logger = LogFactory.getLog(this.getClass()); + /** + * @throws IOException + * @throws JAXBException + * @throws ConfigurationException + * + */ + public CryptedXMLDocAuthenticator() throws JAXBException, IOException, ConfigurationException { + super(); + } + + private CryptedXMLDocAuthenticator(boolean b) { + super(b); + } + @Override + protected String getFilename() throws ConfigurationException { + return AppConfig.getConfiguration().getString(Property.JUDDI_USERSFILE, Property.DEFAULT_ENCRYPTED_XML_USERSFILE); + } + /** + * + * @return user id + * @throws org.apache.juddi.v3.error.AuthenticationException + * @throws org.apache.juddi.v3.error.FatalErrorException + */ + public String authenticate(String userID, String credential) + throws AuthenticationException, FatalErrorException { + preProcess(userID, credential); + String encryptedCredential = encrypt(credential); + return postProcess(userID, encryptedCredential); + } + /** + * + */ + private String encrypt(String str) throws FatalErrorException { + try { + Cryptor cryptor = (Cryptor) CryptorFactory.getCryptor(); + return cryptor.encrypt(str); + } catch (InvalidKeyException e) { + logger.error("Invalid Key Exception in crypting the password", e); + throw new FatalErrorException(new ErrorMessage( + "errors.auth.cryptor.InvalidKey", e.getMessage())); + } catch (NoSuchPaddingException e) { + logger.error("Padding Exception in crypting the password", e); + throw new FatalErrorException(new ErrorMessage( + "errors.auth.cryptor.Padding", e.getMessage())); + } catch (NoSuchAlgorithmException e) { + logger.error("Algorithm Exception in crypting the password", e); + throw new FatalErrorException(new ErrorMessage( + "errors.auth.cryptor.Algorithm", e.getMessage())); + } catch (InvalidAlgorithmParameterException e) { + logger.error("Algorithm parameter Exception in crypting the password", + e); + throw new FatalErrorException(new ErrorMessage( + "errors.auth.cryptor.AlgorithmParam", e.getMessage())); + } catch (IllegalBlockSizeException e) { + logger.error("Block size Exception in crypting the password", e); + throw new FatalErrorException(new ErrorMessage( + "errors.auth.cryptor.BlockSize", e.getMessage())); + } catch (BadPaddingException e) { + logger.error("Bad Padding Exception in crypting the password", e); + throw new FatalErrorException(new ErrorMessage( + "errors.auth.cryptor.BadPadding", e.getMessage())); + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new FatalErrorException(new ErrorMessage( + "errors.auth.cryptor.BlockSize", e.getMessage())); + } + } + /** + * @param userID + * @param credential + * @throws RegistryException + */ + private void preProcess(String userID, String credential) + throws AuthenticationException { + // a userID must be specified. + if (userID == null) { + throw new UnknownUserException(new ErrorMessage( + "errors.auth.InvalidUserId")); + } + // credential (password) must be specified. + if (credential == null) { + throw new UnknownUserException(new ErrorMessage( + "errors.auth.InvalidCredentials")); + } + } + /** + * @param userID + * @param encryptedCredential + * @return user id + * @throws AuthenticationException + */ + private String postProcess(String userID, String encryptedCredential) + throws AuthenticationException { + if (userTable.containsKey(userID)) { + User user = (User) userTable.get(userID); + if ((user.getPassword() == null) + || (!encryptedCredential.equals(user.getPassword()))) { + throw new UnknownUserException(new ErrorMessage( + "errors.auth.InvalidCredentials", userID)); + } + } else { + throw new UnknownUserException(new ErrorMessage( + "errors.auth.InvalidUserId", userID)); + } + int MaxBindingsPerService = -1; + int MaxServicesPerBusiness = -1; + int MaxTmodels = -1; + int MaxBusinesses = -1; + try { + MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE, -1); + MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS, -1); + MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1); + MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1); + } catch (Exception ex) { + MaxBindingsPerService = -1; + MaxServicesPerBusiness = -1; + MaxTmodels = -1; + MaxBusinesses = -1; + log.error("config exception! " + userID, ex); + } + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + Publisher publisher = em.find(Publisher.class, userID); + if (publisher == null) { + log.warn("Publisher \"" + userID + "\" was not found in the database, adding the publisher in on the fly."); + publisher = new Publisher(); + publisher.setAuthorizedName(userID); + publisher.setIsAdmin("false"); + publisher.setIsEnabled("true"); + publisher.setMaxBindingsPerService(MaxBindingsPerService); + publisher.setMaxBusinesses(MaxBusinesses); + publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness); + publisher.setMaxTmodels(MaxTmodels); + publisher.setPublisherName("Unknown"); + em.persist(publisher); + tx.commit(); + } + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + return userID; + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/auth/HTTPContainerAuthenticator.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/HTTPContainerAuthenticator.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/v3/auth/HTTPContainerAuthenticator.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/HTTPContainerAuthenticator.java diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/auth/HTTPHeaderAuthenticator.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/HTTPHeaderAuthenticator.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/v3/auth/HTTPHeaderAuthenticator.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/HTTPHeaderAuthenticator.java diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/auth/JUDDIAuthenticator.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/JUDDIAuthenticator.java similarity index 98% rename from juddi-core/src/main/java/org/apache/juddi/v3/auth/JUDDIAuthenticator.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/JUDDIAuthenticator.java index 832953dba..13e5ebea3 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/auth/JUDDIAuthenticator.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/JUDDIAuthenticator.java @@ -1,127 +1,127 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.auth; - -import javax.persistence.EntityManager; -import javax.persistence.EntityTransaction; -import javax.xml.ws.WebServiceContext; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.PersistenceManager; -import org.apache.juddi.config.Property; -import org.apache.juddi.model.Publisher; -import org.apache.juddi.model.UddiEntityPublisher; -import org.apache.juddi.v3.error.AuthenticationException; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.UnknownUserException; - -/** - * This is the default implementation of jUDDI's Authenticator interface. If the - * user id does not have an associated publisher, it adds the publisher. Please - * do NOT use this class in production. - * - * @author Steve Viens (sviens@apache.org) - * @author Kurt T Stam - * @author Jeff Faath - */ -public class JUDDIAuthenticator implements Authenticator { - - private Log log = LogFactory.getLog(this.getClass()); - - /** - * @return the userId that came in on the request providing the user has - * a publishing account in jUDDI. - * @param authorizedName - * @param credential - * @return authorizedName - * @throws AuthenticationException - */ - public String authenticate(String authorizedName, String credential) throws AuthenticationException { - if (authorizedName == null || "".equals(authorizedName)) { - throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); - } - log.warn("DO NOT USE JUDDI AUTHENTICATOR FOR PRODUCTION SYSTEMS - DOES NOT VALIDATE PASSWORDS, AT ALL!"); - int MaxBindingsPerService = -1; - int MaxServicesPerBusiness = -1; - int MaxTmodels = -1; - int MaxBusinesses = -1; - try { - MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE, -1); - MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS, -1); - MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1); - MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1); - } catch (Exception ex) { - MaxBindingsPerService = -1; - MaxServicesPerBusiness = -1; - MaxTmodels = -1; - MaxBusinesses = -1; - log.error("config exception! " + authorizedName, ex); - } - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - Publisher publisher = em.find(Publisher.class, authorizedName); - if (publisher == null) { - log.warn("Publisher \"" + authorizedName + "\" was not found, adding the publisher in on the fly."); - publisher = new Publisher(); - publisher.setAuthorizedName(authorizedName); - publisher.setIsAdmin("false"); - publisher.setIsEnabled("true"); - publisher.setMaxBindingsPerService(MaxBindingsPerService); - publisher.setMaxBusinesses(MaxBusinesses); - publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness); - publisher.setMaxTmodels(MaxTmodels); - publisher.setPublisherName("Unknown"); - em.persist(publisher); - tx.commit(); - } - return authorizedName; - } catch (Exception ex) { - //note: we saw an ArrayIndexOutOfBounds exception when using github actions for CI - //with hibernate on derby, root cause is still tbd - log.error("error during authentication routine, could indicate a database issue", ex); - throw ex; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - public UddiEntityPublisher identify(String authInfo, String authorizedName, WebServiceContext ctx) throws AuthenticationException { - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - Publisher publisher = em.find(Publisher.class, authorizedName); - if (publisher == null) { - throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); - } - - return publisher; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.auth; + +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.xml.ws.WebServiceContext; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.PersistenceManager; +import org.apache.juddi.config.Property; +import org.apache.juddi.model.Publisher; +import org.apache.juddi.model.UddiEntityPublisher; +import org.apache.juddi.v3.error.AuthenticationException; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.UnknownUserException; + +/** + * This is the default implementation of jUDDI's Authenticator interface. If the + * user id does not have an associated publisher, it adds the publisher. Please + * do NOT use this class in production. + * + * @author Steve Viens (sviens@apache.org) + * @author Kurt T Stam + * @author Jeff Faath + */ +public class JUDDIAuthenticator implements Authenticator { + + private Log log = LogFactory.getLog(this.getClass()); + + /** + * @return the userId that came in on the request providing the user has + * a publishing account in jUDDI. + * @param authorizedName + * @param credential + * @return authorizedName + * @throws AuthenticationException + */ + public String authenticate(String authorizedName, String credential) throws AuthenticationException { + if (authorizedName == null || "".equals(authorizedName)) { + throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); + } + log.warn("DO NOT USE JUDDI AUTHENTICATOR FOR PRODUCTION SYSTEMS - DOES NOT VALIDATE PASSWORDS, AT ALL!"); + int MaxBindingsPerService = -1; + int MaxServicesPerBusiness = -1; + int MaxTmodels = -1; + int MaxBusinesses = -1; + try { + MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE, -1); + MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS, -1); + MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1); + MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1); + } catch (Exception ex) { + MaxBindingsPerService = -1; + MaxServicesPerBusiness = -1; + MaxTmodels = -1; + MaxBusinesses = -1; + log.error("config exception! " + authorizedName, ex); + } + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + Publisher publisher = em.find(Publisher.class, authorizedName); + if (publisher == null) { + log.warn("Publisher \"" + authorizedName + "\" was not found, adding the publisher in on the fly."); + publisher = new Publisher(); + publisher.setAuthorizedName(authorizedName); + publisher.setIsAdmin("false"); + publisher.setIsEnabled("true"); + publisher.setMaxBindingsPerService(MaxBindingsPerService); + publisher.setMaxBusinesses(MaxBusinesses); + publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness); + publisher.setMaxTmodels(MaxTmodels); + publisher.setPublisherName("Unknown"); + em.persist(publisher); + tx.commit(); + } + return authorizedName; + } catch (Exception ex) { + //note: we saw an ArrayIndexOutOfBounds exception when using github actions for CI + //with hibernate on derby, root cause is still tbd + log.error("error during authentication routine, could indicate a database issue", ex); + throw ex; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + public UddiEntityPublisher identify(String authInfo, String authorizedName, WebServiceContext ctx) throws AuthenticationException { + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + Publisher publisher = em.find(Publisher.class, authorizedName); + if (publisher == null) { + throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); + } + + return publisher; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/auth/JuddiUsers.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/JuddiUsers.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/v3/auth/JuddiUsers.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/JuddiUsers.java diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/auth/LdapExpandedAuthenticator.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/LdapExpandedAuthenticator.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/v3/auth/LdapExpandedAuthenticator.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/LdapExpandedAuthenticator.java diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/auth/LdapSimpleAuthenticator.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/LdapSimpleAuthenticator.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/v3/auth/LdapSimpleAuthenticator.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/LdapSimpleAuthenticator.java diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/auth/MD5XMLDocAuthenticator.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/MD5XMLDocAuthenticator.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/auth/MD5XMLDocAuthenticator.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/MD5XMLDocAuthenticator.java index 0e65ae4a3..6669c509a 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/auth/MD5XMLDocAuthenticator.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/MD5XMLDocAuthenticator.java @@ -1,174 +1,174 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.auth; - -import java.io.IOException; -import javax.persistence.EntityManager; -import javax.persistence.EntityTransaction; -import javax.xml.bind.JAXBException; -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.PersistenceManager; -import org.apache.juddi.config.Property; -import org.apache.juddi.model.Publisher; -import org.apache.juddi.v3.error.AuthenticationException; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.FatalErrorException; -import org.apache.juddi.v3.error.RegistryException; -import org.apache.juddi.v3.error.UnknownUserException; - -/** - * Uses MD5 hashes for passwords - * @author Alex O'Ree - */ -public class MD5XMLDocAuthenticator extends XMLDocAuthenticator { - - private Log logger = LogFactory.getLog(this.getClass()); - /** - * @throws IOException - * @throws JAXBException - * @throws ConfigurationException - * - */ - public MD5XMLDocAuthenticator() throws JAXBException, IOException, ConfigurationException { - super(); - } - /** - * A private constructor used for calculating hashes only - * @param x - */ - private MD5XMLDocAuthenticator(boolean x) { - super(x); - } - @Override - protected String getFilename() throws ConfigurationException { - return AppConfig.getConfiguration().getString(Property.JUDDI_USERSFILE, Property.DEFAULT_HASHED_XML_USERSFILE); - } - /** - * - */ - @Override - public String authenticate(String userID, String credential) - throws AuthenticationException, FatalErrorException { - preProcess(userID, credential); - String encryptedCredential = hash(credential); - return postProcess(userID, encryptedCredential); - } - /** - * - */ - private String hash(String str) throws FatalErrorException { - try { - return DigestUtils.md5Hex(str) ; - } catch (Exception e) { - logger.error("Exception caught hashing password", e); - throw new FatalErrorException(new ErrorMessage( - "errors.auth.cryptor.InvalidKey", e.getMessage())); - } - } - /** - * @param userID - * @param credential - * @throws RegistryException - */ - private void preProcess(String userID, String credential) - throws AuthenticationException { - // a userID must be specified. - if (userID == null) { - throw new UnknownUserException(new ErrorMessage( - "errors.auth.InvalidUserId")); - } - // credential (password) must be specified. - if (credential == null) { - throw new UnknownUserException(new ErrorMessage( - "errors.auth.InvalidCredentials")); - } - } - /** - * @param userID - * @param encryptedCredential - * @return user id - * @throws AuthenticationException - */ - private String postProcess(String userID, String encryptedCredential) - throws AuthenticationException { - if (userTable.containsKey(userID)) { - User user = (User) userTable.get(userID); - if ((user.getPassword() == null) - || (!encryptedCredential.equals(user.getPassword()))) { - throw new UnknownUserException(new ErrorMessage( - "errors.auth.InvalidCredentials", userID)); - } - } else { - throw new UnknownUserException(new ErrorMessage( - "errors.auth.InvalidUserId", userID)); - } - int MaxBindingsPerService = -1; - int MaxServicesPerBusiness = -1; - int MaxTmodels = -1; - int MaxBusinesses = -1; - try { - MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE, -1); - MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS, -1); - MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1); - MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1); - } catch (Exception ex) { - MaxBindingsPerService = -1; - MaxServicesPerBusiness = -1; - MaxTmodels = -1; - MaxBusinesses = -1; - log.error("config exception! " + userID, ex); - } - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - Publisher publisher = em.find(Publisher.class, userID); - if (publisher == null) { - log.warn("Publisher \"" + userID + "\" was not found in the database, adding the publisher in on the fly."); - publisher = new Publisher(); - publisher.setAuthorizedName(userID); - publisher.setIsAdmin("false"); - publisher.setIsEnabled("true"); - publisher.setMaxBindingsPerService(MaxBindingsPerService); - publisher.setMaxBusinesses(MaxBusinesses); - publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness); - publisher.setMaxTmodels(MaxTmodels); - publisher.setPublisherName("Unknown"); - em.persist(publisher); - tx.commit(); - } - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - return userID; - } - - public static void main(String[] args) throws Exception - { - System.out.print("Password: "); - char[] readPassword = System.console().readPassword(); - System.out.println("Cipher: " + new MD5XMLDocAuthenticator(true).hash(new String(readPassword))); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.auth; + +import java.io.IOException; +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.xml.bind.JAXBException; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.PersistenceManager; +import org.apache.juddi.config.Property; +import org.apache.juddi.model.Publisher; +import org.apache.juddi.v3.error.AuthenticationException; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.FatalErrorException; +import org.apache.juddi.v3.error.RegistryException; +import org.apache.juddi.v3.error.UnknownUserException; + +/** + * Uses MD5 hashes for passwords + * @author Alex O'Ree + */ +public class MD5XMLDocAuthenticator extends XMLDocAuthenticator { + + private Log logger = LogFactory.getLog(this.getClass()); + /** + * @throws IOException + * @throws JAXBException + * @throws ConfigurationException + * + */ + public MD5XMLDocAuthenticator() throws JAXBException, IOException, ConfigurationException { + super(); + } + /** + * A private constructor used for calculating hashes only + * @param x + */ + private MD5XMLDocAuthenticator(boolean x) { + super(x); + } + @Override + protected String getFilename() throws ConfigurationException { + return AppConfig.getConfiguration().getString(Property.JUDDI_USERSFILE, Property.DEFAULT_HASHED_XML_USERSFILE); + } + /** + * + */ + @Override + public String authenticate(String userID, String credential) + throws AuthenticationException, FatalErrorException { + preProcess(userID, credential); + String encryptedCredential = hash(credential); + return postProcess(userID, encryptedCredential); + } + /** + * + */ + private String hash(String str) throws FatalErrorException { + try { + return DigestUtils.md5Hex(str) ; + } catch (Exception e) { + logger.error("Exception caught hashing password", e); + throw new FatalErrorException(new ErrorMessage( + "errors.auth.cryptor.InvalidKey", e.getMessage())); + } + } + /** + * @param userID + * @param credential + * @throws RegistryException + */ + private void preProcess(String userID, String credential) + throws AuthenticationException { + // a userID must be specified. + if (userID == null) { + throw new UnknownUserException(new ErrorMessage( + "errors.auth.InvalidUserId")); + } + // credential (password) must be specified. + if (credential == null) { + throw new UnknownUserException(new ErrorMessage( + "errors.auth.InvalidCredentials")); + } + } + /** + * @param userID + * @param encryptedCredential + * @return user id + * @throws AuthenticationException + */ + private String postProcess(String userID, String encryptedCredential) + throws AuthenticationException { + if (userTable.containsKey(userID)) { + User user = (User) userTable.get(userID); + if ((user.getPassword() == null) + || (!encryptedCredential.equals(user.getPassword()))) { + throw new UnknownUserException(new ErrorMessage( + "errors.auth.InvalidCredentials", userID)); + } + } else { + throw new UnknownUserException(new ErrorMessage( + "errors.auth.InvalidUserId", userID)); + } + int MaxBindingsPerService = -1; + int MaxServicesPerBusiness = -1; + int MaxTmodels = -1; + int MaxBusinesses = -1; + try { + MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE, -1); + MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS, -1); + MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1); + MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1); + } catch (Exception ex) { + MaxBindingsPerService = -1; + MaxServicesPerBusiness = -1; + MaxTmodels = -1; + MaxBusinesses = -1; + log.error("config exception! " + userID, ex); + } + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + Publisher publisher = em.find(Publisher.class, userID); + if (publisher == null) { + log.warn("Publisher \"" + userID + "\" was not found in the database, adding the publisher in on the fly."); + publisher = new Publisher(); + publisher.setAuthorizedName(userID); + publisher.setIsAdmin("false"); + publisher.setIsEnabled("true"); + publisher.setMaxBindingsPerService(MaxBindingsPerService); + publisher.setMaxBusinesses(MaxBusinesses); + publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness); + publisher.setMaxTmodels(MaxTmodels); + publisher.setPublisherName("Unknown"); + em.persist(publisher); + tx.commit(); + } + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + return userID; + } + + public static void main(String[] args) throws Exception + { + System.out.print("Password: "); + char[] readPassword = System.console().readPassword(); + System.out.println("Cipher: " + new MD5XMLDocAuthenticator(true).hash(new String(readPassword))); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/auth/User.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/User.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/v3/auth/User.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/User.java diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/auth/XMLDocAuthenticator.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/XMLDocAuthenticator.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/auth/XMLDocAuthenticator.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/XMLDocAuthenticator.java index 66884ddbf..d40c938a4 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/auth/XMLDocAuthenticator.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/XMLDocAuthenticator.java @@ -1,232 +1,232 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.auth; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; - -import javax.persistence.EntityManager; -import javax.persistence.EntityTransaction; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.transform.stream.StreamSource; -import javax.xml.ws.WebServiceContext; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.ClassUtil; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.PersistenceManager; -import org.apache.juddi.config.Property; -import org.apache.juddi.model.Publisher; -import org.apache.juddi.model.UddiEntityPublisher; -import org.apache.juddi.v3.error.AuthenticationException; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.FatalErrorException; -import org.apache.juddi.v3.error.UnknownUserException; - -/** - * This is a simple implementation of jUDDI's Authenticator interface. The - * credential store is simply an unencrypted xml document called 'juddi.users' - * that can be found in jUDDI's config directory. Below is an example of what - * you might find in this document. - * - * Example juddi.users document: ============================= - * - * - * - * - * - * - * - * @author Steve Viens (sviens@apache.org) - * @author Kurt T Stam - * @author Jeff Faath - */ -public class XMLDocAuthenticator implements Authenticator { - - protected final static Log log = LogFactory.getLog(AuthenticatorFactory.class); - /** - * Container for the user credentials - */ - Map userTable; - - /** - * - */ - public XMLDocAuthenticator() throws JAXBException, IOException, ConfigurationException { - readUserFile(); - } - - /** - * an empty constructor - */ - public XMLDocAuthenticator(boolean b) { - - } - - protected String getFilename() throws ConfigurationException { - return AppConfig.getConfiguration().getString(Property.JUDDI_USERSFILE, Property.DEFAULT_XML_USERSFILE); - } - - /** - * Read user data from the juddi-users file. - * - * @throws IOException when the file cannot be opened JAXBException when - * the content is malformed. - * @throws ConfigurationException - */ - public synchronized void readUserFile() throws JAXBException, IOException, ConfigurationException { - - userTable = new HashMap(); - String usersFileName = getFilename(); - if (usersFileName == null || usersFileName.length() == 0) { - throw new ConfigurationException("usersFileName value is null!"); - } - File file = new File(usersFileName); - InputStream stream = null; - try { - if (file.exists()) { - log.info("Reading jUDDI Users File: " + usersFileName + "..."); - stream = new FileInputStream(file); - } else { - URL resource = ClassUtil.getResource(usersFileName, this.getClass()); - if (resource != null) { - log.info("Reading jUDDI Users File: " + usersFileName + "...from " + resource.toExternalForm()); - } else { - log.info("Reading jUDDI Users File: " + usersFileName + "..."); - } - stream = ClassUtil.getResource(usersFileName, this.getClass()).openStream(); - } - JAXBContext jaxbContext = JAXBContext.newInstance(JuddiUsers.class); - Unmarshaller unMarshaller = jaxbContext.createUnmarshaller(); - JAXBElement element = unMarshaller.unmarshal(new StreamSource(stream), JuddiUsers.class); - JuddiUsers users = element.getValue(); - for (User user : users.getUser()) { - userTable.put(user.getUserid(), user); - log.debug("Loading user credentials for user: " + user.getUserid()); - } - } catch (IOException ex) { - log.warn("io exception", ex); - } finally { - if (stream != null) { - stream.close(); - } - } - } - - /** - * - * @param userID - * @param credential - */ - public String authenticate(String userID, String credential) - throws AuthenticationException, FatalErrorException { - // a userID must be specified. - if (userID == null) { - throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidUserId")); - } - - // credential (password) must be specified. - if (credential == null) { - throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidCredentials")); - } - - if (userTable.containsKey(userID)) { - User user = (User) userTable.get(userID); - if ((user.getPassword() == null) || (!credential.equals(user.getPassword()))) { - throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidCredentials")); - } - } else { - throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidUserId", userID)); - } - - int MaxBindingsPerService = -1; - int MaxServicesPerBusiness = -1; - int MaxTmodels = -1; - int MaxBusinesses = -1; - try { - MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE, -1); - MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS, -1); - MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1); - MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1); - } catch (Exception ex) { - MaxBindingsPerService = -1; - MaxServicesPerBusiness = -1; - MaxTmodels = -1; - MaxBusinesses = -1; - log.error("config exception! " + userID, ex); - } - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - Publisher publisher = em.find(Publisher.class, userID); - if (publisher == null) { - log.warn("Publisher \"" + userID + "\" was not found in the database, adding the publisher in on the fly."); - publisher = new Publisher(); - publisher.setAuthorizedName(userID); - publisher.setIsAdmin("false"); - publisher.setIsEnabled("true"); - publisher.setMaxBindingsPerService(MaxBindingsPerService); - publisher.setMaxBusinesses(MaxBusinesses); - publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness); - publisher.setMaxTmodels(MaxTmodels); - publisher.setPublisherName("Unknown"); - em.persist(publisher); - tx.commit(); - } - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - return userID; - } - - @Override - public UddiEntityPublisher identify(String authInfo, String authorizedName, WebServiceContext ctx) throws AuthenticationException { - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - Publisher publisher = em.find(Publisher.class, authorizedName); - if (publisher == null) { - throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); - } - - return publisher; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.auth; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.stream.StreamSource; +import javax.xml.ws.WebServiceContext; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.ClassUtil; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.PersistenceManager; +import org.apache.juddi.config.Property; +import org.apache.juddi.model.Publisher; +import org.apache.juddi.model.UddiEntityPublisher; +import org.apache.juddi.v3.error.AuthenticationException; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.FatalErrorException; +import org.apache.juddi.v3.error.UnknownUserException; + +/** + * This is a simple implementation of jUDDI's Authenticator interface. The + * credential store is simply an unencrypted xml document called 'juddi.users' + * that can be found in jUDDI's config directory. Below is an example of what + * you might find in this document. + * + * Example juddi.users document: ============================= + * + * + * + * + * + * + * + * @author Steve Viens (sviens@apache.org) + * @author Kurt T Stam + * @author Jeff Faath + */ +public class XMLDocAuthenticator implements Authenticator { + + protected final static Log log = LogFactory.getLog(AuthenticatorFactory.class); + /** + * Container for the user credentials + */ + Map userTable; + + /** + * + */ + public XMLDocAuthenticator() throws JAXBException, IOException, ConfigurationException { + readUserFile(); + } + + /** + * an empty constructor + */ + public XMLDocAuthenticator(boolean b) { + + } + + protected String getFilename() throws ConfigurationException { + return AppConfig.getConfiguration().getString(Property.JUDDI_USERSFILE, Property.DEFAULT_XML_USERSFILE); + } + + /** + * Read user data from the juddi-users file. + * + * @throws IOException when the file cannot be opened JAXBException when + * the content is malformed. + * @throws ConfigurationException + */ + public synchronized void readUserFile() throws JAXBException, IOException, ConfigurationException { + + userTable = new HashMap(); + String usersFileName = getFilename(); + if (usersFileName == null || usersFileName.length() == 0) { + throw new ConfigurationException("usersFileName value is null!"); + } + File file = new File(usersFileName); + InputStream stream = null; + try { + if (file.exists()) { + log.info("Reading jUDDI Users File: " + usersFileName + "..."); + stream = new FileInputStream(file); + } else { + URL resource = ClassUtil.getResource(usersFileName, this.getClass()); + if (resource != null) { + log.info("Reading jUDDI Users File: " + usersFileName + "...from " + resource.toExternalForm()); + } else { + log.info("Reading jUDDI Users File: " + usersFileName + "..."); + } + stream = ClassUtil.getResource(usersFileName, this.getClass()).openStream(); + } + JAXBContext jaxbContext = JAXBContext.newInstance(JuddiUsers.class); + Unmarshaller unMarshaller = jaxbContext.createUnmarshaller(); + JAXBElement element = unMarshaller.unmarshal(new StreamSource(stream), JuddiUsers.class); + JuddiUsers users = element.getValue(); + for (User user : users.getUser()) { + userTable.put(user.getUserid(), user); + log.debug("Loading user credentials for user: " + user.getUserid()); + } + } catch (IOException ex) { + log.warn("io exception", ex); + } finally { + if (stream != null) { + stream.close(); + } + } + } + + /** + * + * @param userID + * @param credential + */ + public String authenticate(String userID, String credential) + throws AuthenticationException, FatalErrorException { + // a userID must be specified. + if (userID == null) { + throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidUserId")); + } + + // credential (password) must be specified. + if (credential == null) { + throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidCredentials")); + } + + if (userTable.containsKey(userID)) { + User user = (User) userTable.get(userID); + if ((user.getPassword() == null) || (!credential.equals(user.getPassword()))) { + throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidCredentials")); + } + } else { + throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidUserId", userID)); + } + + int MaxBindingsPerService = -1; + int MaxServicesPerBusiness = -1; + int MaxTmodels = -1; + int MaxBusinesses = -1; + try { + MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE, -1); + MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS, -1); + MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1); + MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1); + } catch (Exception ex) { + MaxBindingsPerService = -1; + MaxServicesPerBusiness = -1; + MaxTmodels = -1; + MaxBusinesses = -1; + log.error("config exception! " + userID, ex); + } + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + Publisher publisher = em.find(Publisher.class, userID); + if (publisher == null) { + log.warn("Publisher \"" + userID + "\" was not found in the database, adding the publisher in on the fly."); + publisher = new Publisher(); + publisher.setAuthorizedName(userID); + publisher.setIsAdmin("false"); + publisher.setIsEnabled("true"); + publisher.setMaxBindingsPerService(MaxBindingsPerService); + publisher.setMaxBusinesses(MaxBusinesses); + publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness); + publisher.setMaxTmodels(MaxTmodels); + publisher.setPublisherName("Unknown"); + em.persist(publisher); + tx.commit(); + } + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + return userID; + } + + @Override + public UddiEntityPublisher identify(String authInfo, String authorizedName, WebServiceContext ctx) throws AuthenticationException { + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + Publisher publisher = em.find(Publisher.class, authorizedName); + if (publisher == null) { + throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); + } + + return publisher; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/auth/package-info.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/package-info.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/v3/auth/package-info.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/auth/package-info.java diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/AssertionNotFoundException.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/AssertionNotFoundException.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/AssertionNotFoundException.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/AssertionNotFoundException.java index 73110967a..dd06cee5d 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/error/AssertionNotFoundException.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/AssertionNotFoundException.java @@ -1,36 +1,36 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.error; - -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.RegistryException; -import org.apache.juddi.v3.error.UDDIErrorHelper; - -/** - * E_assertionNotFound: (30000) Signifies that a particular publisher assertion cannot be identified in a save or delete operation. - * - * @author Jeff Faath - */ -public class AssertionNotFoundException extends RegistryException { - - private static final long serialVersionUID = -2172986368788753140L; - - public AssertionNotFoundException(ErrorMessage message) { - super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_ASSERTION_NOT_FOUND)); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.error; + +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.RegistryException; +import org.apache.juddi.v3.error.UDDIErrorHelper; + +/** + * E_assertionNotFound: (30000) Signifies that a particular publisher assertion cannot be identified in a save or delete operation. + * + * @author Jeff Faath + */ +public class AssertionNotFoundException extends RegistryException { + + private static final long serialVersionUID = -2172986368788753140L; + + public AssertionNotFoundException(ErrorMessage message) { + super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_ASSERTION_NOT_FOUND)); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/AuthTokenExpiredException.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/AuthTokenExpiredException.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/AuthTokenExpiredException.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/AuthTokenExpiredException.java index 92621d99b..7a3ae1baf 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/error/AuthTokenExpiredException.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/AuthTokenExpiredException.java @@ -1,36 +1,36 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.error; - -import org.apache.juddi.v3.error.AuthenticationException; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.UDDIErrorHelper; - -/** - * E_authTokenExpired: (10110) Signifies that the authentication token information has timed out. - * - * @author Jeff Faath - */ -public class AuthTokenExpiredException extends AuthenticationException { - - private static final long serialVersionUID = -2993033147078083022L; - - public AuthTokenExpiredException(ErrorMessage message) { - super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_AUTH_TOKEN_EXPIRED)); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.error; + +import org.apache.juddi.v3.error.AuthenticationException; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.UDDIErrorHelper; + +/** + * E_authTokenExpired: (10110) Signifies that the authentication token information has timed out. + * + * @author Jeff Faath + */ +public class AuthTokenExpiredException extends AuthenticationException { + + private static final long serialVersionUID = -2993033147078083022L; + + public AuthTokenExpiredException(ErrorMessage message) { + super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_AUTH_TOKEN_EXPIRED)); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/AuthTokenRequiredException.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/AuthTokenRequiredException.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/AuthTokenRequiredException.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/AuthTokenRequiredException.java index c384ce122..f22c4766d 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/error/AuthTokenRequiredException.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/AuthTokenRequiredException.java @@ -1,36 +1,36 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.error; - -import org.apache.juddi.v3.error.AuthenticationException; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.UDDIErrorHelper; - -/** - * E_authTokenRequired: (10120) Signifies that an authentication token is missing or is invalid for an API call that requires authentication. - * - * @author Jeff Faath - */ -public class AuthTokenRequiredException extends AuthenticationException { - - private static final long serialVersionUID = 911181181554360596L; - - public AuthTokenRequiredException(ErrorMessage message) { - super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_AUTH_TOKEN_REQUIRED)); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.error; + +import org.apache.juddi.v3.error.AuthenticationException; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.UDDIErrorHelper; + +/** + * E_authTokenRequired: (10120) Signifies that an authentication token is missing or is invalid for an API call that requires authentication. + * + * @author Jeff Faath + */ +public class AuthTokenRequiredException extends AuthenticationException { + + private static final long serialVersionUID = 911181181554360596L; + + public AuthTokenRequiredException(ErrorMessage message) { + super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_AUTH_TOKEN_REQUIRED)); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/AuthenticationException.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/AuthenticationException.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/AuthenticationException.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/AuthenticationException.java index 63b506550..fdb41d5e8 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/error/AuthenticationException.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/AuthenticationException.java @@ -1,36 +1,36 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.error; - -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.RegistryException; -import org.uddi.api_v3.DispositionReport; - -/** - * Parenent of all Authentication exceptions. - * - * @author Kurt T Stam - */ -public class AuthenticationException extends RegistryException { - - private static final long serialVersionUID = 2117503081874302954L; - - public AuthenticationException(ErrorMessage message, DispositionReport dispositionReport) { - super(message, dispositionReport); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.error; + +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.RegistryException; +import org.uddi.api_v3.DispositionReport; + +/** + * Parenent of all Authentication exceptions. + * + * @author Kurt T Stam + */ +public class AuthenticationException extends RegistryException { + + private static final long serialVersionUID = 2117503081874302954L; + + public AuthenticationException(ErrorMessage message, DispositionReport dispositionReport) { + super(message, dispositionReport); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/ErrorMessage.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/ErrorMessage.java similarity index 95% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/ErrorMessage.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/ErrorMessage.java index 41228d4fc..e706b780c 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/error/ErrorMessage.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/ErrorMessage.java @@ -1,61 +1,61 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.error; - -import org.apache.juddi.config.ResourceConfig; - -/** - * @author Jeff Faath - */ -public class ErrorMessage { - private String message; - private String value; - - public ErrorMessage(String messageCode) { - this(messageCode, null); - } - - public ErrorMessage(String messageCode, String value) { - this.message = ResourceConfig.getGlobalMessage(messageCode); - this.value = value; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public String toString() { - if (value == null || value.length() == 0) - return message; - else - return message + ": " + value; - - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.error; + +import org.apache.juddi.config.ResourceConfig; + +/** + * @author Jeff Faath + */ +public class ErrorMessage { + private String message; + private String value; + + public ErrorMessage(String messageCode) { + this(messageCode, null); + } + + public ErrorMessage(String messageCode, String value) { + this.message = ResourceConfig.getGlobalMessage(messageCode); + this.value = value; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String toString() { + if (value == null || value.length() == 0) + return message; + else + return message + ": " + value; + + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/FatalErrorException.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/FatalErrorException.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/FatalErrorException.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/FatalErrorException.java index 510934d9a..f1cb9852e 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/error/FatalErrorException.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/FatalErrorException.java @@ -1,36 +1,36 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.error; - -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.RegistryException; -import org.apache.juddi.v3.error.UDDIErrorHelper; - -/** - * E_fatalError: (10500) Signifies that a serious technical error has occurred while processing the request. - * - * @author Jeff Faath - */ -public class FatalErrorException extends RegistryException { - - private static final long serialVersionUID = 6396216072725959470L; - - public FatalErrorException(ErrorMessage message) { - super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_FATAL_ERROR)); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.error; + +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.RegistryException; +import org.apache.juddi.v3.error.UDDIErrorHelper; + +/** + * E_fatalError: (10500) Signifies that a serious technical error has occurred while processing the request. + * + * @author Jeff Faath + */ +public class FatalErrorException extends RegistryException { + + private static final long serialVersionUID = 6396216072725959470L; + + public FatalErrorException(ErrorMessage message) { + super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_FATAL_ERROR)); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/InvalidCombinationException.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/InvalidCombinationException.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/InvalidCombinationException.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/InvalidCombinationException.java index 32eba8719..1f2ef09fa 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/error/InvalidCombinationException.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/InvalidCombinationException.java @@ -1,37 +1,37 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.error; - -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.RegistryException; -import org.apache.juddi.v3.error.UDDIErrorHelper; - -/** - * E_invalidCombination: (40500) Signifies conflicting find qualifiers have been specified. The find qualifiers that caused the problem SHOULD be - * clearly indicated in the error text. - * - * @author Jeff Faath - */ -public class InvalidCombinationException extends RegistryException { - - private static final long serialVersionUID = 9124050613724790829L; - - public InvalidCombinationException(ErrorMessage message) { - super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_INVALID_COMBINATION)); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.error; + +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.RegistryException; +import org.apache.juddi.v3.error.UDDIErrorHelper; + +/** + * E_invalidCombination: (40500) Signifies conflicting find qualifiers have been specified. The find qualifiers that caused the problem SHOULD be + * clearly indicated in the error text. + * + * @author Jeff Faath + */ +public class InvalidCombinationException extends RegistryException { + + private static final long serialVersionUID = 9124050613724790829L; + + public InvalidCombinationException(ErrorMessage message) { + super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_INVALID_COMBINATION)); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/InvalidKeyPassedException.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/InvalidKeyPassedException.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/InvalidKeyPassedException.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/InvalidKeyPassedException.java index 08a584dae..b948fbec2 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/error/InvalidKeyPassedException.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/InvalidKeyPassedException.java @@ -1,37 +1,37 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.error; - -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.RegistryException; -import org.apache.juddi.v3.error.UDDIErrorHelper; - -/** - * E_invalidKeyPassed: (10210) Signifies that the uddiKey value passed did not match with any known key values. The details on the invalid key SHOULD be - * included in the dispositionReport element. - * - * @author Jeff Faath - */ -public class InvalidKeyPassedException extends RegistryException { - - private static final long serialVersionUID = 3302122187004457095L; - - public InvalidKeyPassedException(ErrorMessage message) { - super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_INVALID_KEY_PASSED)); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.error; + +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.RegistryException; +import org.apache.juddi.v3.error.UDDIErrorHelper; + +/** + * E_invalidKeyPassed: (10210) Signifies that the uddiKey value passed did not match with any known key values. The details on the invalid key SHOULD be + * included in the dispositionReport element. + * + * @author Jeff Faath + */ +public class InvalidKeyPassedException extends RegistryException { + + private static final long serialVersionUID = 3302122187004457095L; + + public InvalidKeyPassedException(ErrorMessage message) { + super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_INVALID_KEY_PASSED)); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/InvalidProjectionException.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/InvalidProjectionException.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/InvalidProjectionException.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/InvalidProjectionException.java index 1d135159f..c7b58606a 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/error/InvalidProjectionException.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/InvalidProjectionException.java @@ -1,37 +1,37 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.error; - -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.RegistryException; -import org.apache.juddi.v3.error.UDDIErrorHelper; - -/** - * E_invalidProjection: (20230) Signifies that an attempt was made to save a businessEntity containing a service projection where the serviceKey does not - * belong to the business designated by the businessKey. The serviceKey of at least one such businessService SHOULD be included in the dispositionReport. - * - * @author Jeff Faath - */ -public class InvalidProjectionException extends RegistryException { - - private static final long serialVersionUID = -2447287220774262681L; - - public InvalidProjectionException(ErrorMessage message) { - super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_INVALID_PROJECTION)); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.error; + +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.RegistryException; +import org.apache.juddi.v3.error.UDDIErrorHelper; + +/** + * E_invalidProjection: (20230) Signifies that an attempt was made to save a businessEntity containing a service projection where the serviceKey does not + * belong to the business designated by the businessKey. The serviceKey of at least one such businessService SHOULD be included in the dispositionReport. + * + * @author Jeff Faath + */ +public class InvalidProjectionException extends RegistryException { + + private static final long serialVersionUID = -2447287220774262681L; + + public InvalidProjectionException(ErrorMessage message) { + super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_INVALID_PROJECTION)); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/InvalidTimeException.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/InvalidTimeException.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/InvalidTimeException.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/InvalidTimeException.java index 4dc14853e..48049d3b9 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/error/InvalidTimeException.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/InvalidTimeException.java @@ -1,37 +1,37 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.error; - -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.RegistryException; -import org.apache.juddi.v3.error.UDDIErrorHelper; - -/** - * E_invalidTime: (40030) Signifies that the time period, the date/time, or the pair of date/time is invalid. The error structure - * signifies the condition that occurred and the error text clearly calls out the cause of the problem. - * - * @author Jeff Faath - */ -public class InvalidTimeException extends RegistryException { - - private static final long serialVersionUID = 8225896425924629956L; - - public InvalidTimeException(ErrorMessage message) { - super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_INVALID_KEY_PASSED)); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.error; + +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.RegistryException; +import org.apache.juddi.v3.error.UDDIErrorHelper; + +/** + * E_invalidTime: (40030) Signifies that the time period, the date/time, or the pair of date/time is invalid. The error structure + * signifies the condition that occurred and the error text clearly calls out the cause of the problem. + * + * @author Jeff Faath + */ +public class InvalidTimeException extends RegistryException { + + private static final long serialVersionUID = 8225896425924629956L; + + public InvalidTimeException(ErrorMessage message) { + super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_INVALID_KEY_PASSED)); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/InvalidValueException.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/InvalidValueException.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/InvalidValueException.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/InvalidValueException.java index a10c7b650..01a08df21 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/error/InvalidValueException.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/InvalidValueException.java @@ -1,40 +1,40 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.error; - -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.RegistryException; -import org.apache.juddi.v3.error.UDDIErrorHelper; - -/** - * E_invalidValue: (20200) This error code has multiple uses. This error code applies to the subscription APIs and the value set APIs. It - * can be used to indicate that a value that was passed in a keyValue attribute did not pass validation. This applies to checked value - * sets that are referenced using keyedReferences. The error text SHOULD clearly indicate the key and value combination that failed validation. - * It can also be used to indicate that a chunkToken supplied is invalid. This applies in both subscription and value set APIs. The error text - * SHOULD clearly indicate the reason for failure. - * - * @author Jeff Faath - */ -public class InvalidValueException extends RegistryException { - - private static final long serialVersionUID = -5108592555540144175L; - - public InvalidValueException(ErrorMessage message) { - super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_INVALID_VALUE)); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.error; + +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.RegistryException; +import org.apache.juddi.v3.error.UDDIErrorHelper; + +/** + * E_invalidValue: (20200) This error code has multiple uses. This error code applies to the subscription APIs and the value set APIs. It + * can be used to indicate that a value that was passed in a keyValue attribute did not pass validation. This applies to checked value + * sets that are referenced using keyedReferences. The error text SHOULD clearly indicate the key and value combination that failed validation. + * It can also be used to indicate that a chunkToken supplied is invalid. This applies in both subscription and value set APIs. The error text + * SHOULD clearly indicate the reason for failure. + * + * @author Jeff Faath + */ +public class InvalidValueException extends RegistryException { + + private static final long serialVersionUID = -5108592555540144175L; + + public InvalidValueException(ErrorMessage message) { + super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_INVALID_VALUE)); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/KeyUnavailableException.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/KeyUnavailableException.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/KeyUnavailableException.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/KeyUnavailableException.java index 7077e0cb3..3614ea82f 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/error/KeyUnavailableException.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/KeyUnavailableException.java @@ -1,36 +1,36 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.error; - -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.RegistryException; -import org.apache.juddi.v3.error.UDDIErrorHelper; - -/** - * E_keyUnavailable: (40100) Signifies that the proposed key is in a partition that has already been assigned to some other publisher. - * - * @author Jeff Faath - */ -public class KeyUnavailableException extends RegistryException { - - private static final long serialVersionUID = 7532508672433733387L; - - public KeyUnavailableException(ErrorMessage message) { - super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_KEY_UNAVAILABLE)); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.error; + +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.RegistryException; +import org.apache.juddi.v3.error.UDDIErrorHelper; + +/** + * E_keyUnavailable: (40100) Signifies that the proposed key is in a partition that has already been assigned to some other publisher. + * + * @author Jeff Faath + */ +public class KeyUnavailableException extends RegistryException { + + private static final long serialVersionUID = 7532508672433733387L; + + public KeyUnavailableException(ErrorMessage message) { + super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_KEY_UNAVAILABLE)); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/MaxEntitiesExceededException.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/MaxEntitiesExceededException.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/MaxEntitiesExceededException.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/MaxEntitiesExceededException.java index 348c92b33..99d949b65 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/error/MaxEntitiesExceededException.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/MaxEntitiesExceededException.java @@ -1,37 +1,37 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.error; - -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.RegistryException; -import org.apache.juddi.v3.error.UDDIErrorHelper; - -/** - * E_valueNotAllowed: (20210) Signifies that a value did not pass validation because of contextual issues. The value may be valid in some contexts, but - * not in the context used. The error text MAY contain information about the contextual problem. - * - * @author Jeff Faath - */ -public class MaxEntitiesExceededException extends RegistryException { - - private static final long serialVersionUID = -4003033708851434957L; - - public MaxEntitiesExceededException(ErrorMessage message) { - super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_VALUE_NOT_ALLOWED)); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.error; + +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.RegistryException; +import org.apache.juddi.v3.error.UDDIErrorHelper; + +/** + * E_valueNotAllowed: (20210) Signifies that a value did not pass validation because of contextual issues. The value may be valid in some contexts, but + * not in the context used. The error text MAY contain information about the contextual problem. + * + * @author Jeff Faath + */ +public class MaxEntitiesExceededException extends RegistryException { + + private static final long serialVersionUID = -4003033708851434957L; + + public MaxEntitiesExceededException(ErrorMessage message) { + super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_VALUE_NOT_ALLOWED)); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/RegistryException.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/RegistryException.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/RegistryException.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/RegistryException.java index 8027b0a93..f2c6daa06 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/error/RegistryException.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/RegistryException.java @@ -1,36 +1,36 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.error; - -import org.apache.juddi.v3.error.ErrorMessage; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.api_v3.DispositionReport; - -/** - * Parent Exception for all UDDI registry exceptions - * - * @author Jeff Faath - */ -public class RegistryException extends DispositionReportFaultMessage { - - private static final long serialVersionUID = -4200811689537798618L; - - public RegistryException(ErrorMessage message, DispositionReport dispReport) { - super(message.toString(), dispReport); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.error; + +import org.apache.juddi.v3.error.ErrorMessage; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.api_v3.DispositionReport; + +/** + * Parent Exception for all UDDI registry exceptions + * + * @author Jeff Faath + */ +public class RegistryException extends DispositionReportFaultMessage { + + private static final long serialVersionUID = -4200811689537798618L; + + public RegistryException(ErrorMessage message, DispositionReport dispReport) { + super(message.toString(), dispReport); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/TokenAlreadyExistsException.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/TokenAlreadyExistsException.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/TokenAlreadyExistsException.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/TokenAlreadyExistsException.java index 8acd6de8a..52c2ef883 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/error/TokenAlreadyExistsException.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/TokenAlreadyExistsException.java @@ -1,37 +1,37 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.error; - -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.RegistryException; -import org.apache.juddi.v3.error.UDDIErrorHelper; - -/** - * E_tokenAlreadyExists: (40070) Signifies that one or more of the businessKey or tModelKey elements that identify entities to be transferred - * are not owned by the publisher identified by the authInfo element. The error text SHOULD clearly indicate which entity keys caused the error. - * - * @author Jeff Faath - */ -public class TokenAlreadyExistsException extends RegistryException { - - private static final long serialVersionUID = 2721076133362327262L; - - public TokenAlreadyExistsException(ErrorMessage message) { - super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_TOKEN_ALREADY_EXISTS)); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.error; + +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.RegistryException; +import org.apache.juddi.v3.error.UDDIErrorHelper; + +/** + * E_tokenAlreadyExists: (40070) Signifies that one or more of the businessKey or tModelKey elements that identify entities to be transferred + * are not owned by the publisher identified by the authInfo element. The error text SHOULD clearly indicate which entity keys caused the error. + * + * @author Jeff Faath + */ +public class TokenAlreadyExistsException extends RegistryException { + + private static final long serialVersionUID = 2721076133362327262L; + + public TokenAlreadyExistsException(ErrorMessage message) { + super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_TOKEN_ALREADY_EXISTS)); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/TransferNotAllowedException.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/TransferNotAllowedException.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/TransferNotAllowedException.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/TransferNotAllowedException.java index 0f3b3541a..a41dbcdd0 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/error/TransferNotAllowedException.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/TransferNotAllowedException.java @@ -1,37 +1,37 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.error; - -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.RegistryException; -import org.apache.juddi.v3.error.UDDIErrorHelper; - -/** - * E_transferNotAllowed: (40600) Signifies that the transfer of one or more entities has been by either the custodial node or - * the target node because the transfer token has expired or an attempt was made to transfer an unauthorized entity - * - * @author Jeff Faath - */ -public class TransferNotAllowedException extends RegistryException { - - private static final long serialVersionUID = 8070707155768168717L; - - public TransferNotAllowedException(ErrorMessage message) { - super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_TRANSFER_NOT_ALLOWED)); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.error; + +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.RegistryException; +import org.apache.juddi.v3.error.UDDIErrorHelper; + +/** + * E_transferNotAllowed: (40600) Signifies that the transfer of one or more entities has been by either the custodial node or + * the target node because the transfer token has expired or an attempt was made to transfer an unauthorized entity + * + * @author Jeff Faath + */ +public class TransferNotAllowedException extends RegistryException { + + private static final long serialVersionUID = 8070707155768168717L; + + public TransferNotAllowedException(ErrorMessage message) { + super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_TRANSFER_NOT_ALLOWED)); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/UDDIErrorHelper.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/UDDIErrorHelper.java similarity index 98% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/UDDIErrorHelper.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/UDDIErrorHelper.java index f0f72dce6..81f8e46b8 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/error/UDDIErrorHelper.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/UDDIErrorHelper.java @@ -1,211 +1,211 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.error; - -import org.apache.juddi.config.ResourceConfig; -import org.uddi.api_v3.DispositionReport; -import org.uddi.api_v3.Result; -import org.uddi.api_v3.ErrInfo; - -/** - * @author Jeff Faath - */ -public class UDDIErrorHelper { - /** - * E_assertionNotFound: (30000) Signifies that a particular publisher assertion cannot be identified in a save or delete operation. - */ - public static final int E_ASSERTION_NOT_FOUND = 30000; - /** - * E_authTokenExpired: (10110) Signifies that the authentication token information has timed out. - */ - public static final int E_AUTH_TOKEN_EXPIRED = 10110; - /** - * E_authTokenRequired: (10120) Signifies that an authentication token is missing or is invalid for an API call that requires authentication. - */ - public static final int E_AUTH_TOKEN_REQUIRED = 10120; - /** - * E_accountLimitExceeded: (10160) Signifies that a save request exceeded the quantity limits for a given data type. Account limits are established based on the relationship between an individual publisher and an individual node. See your UDDI node’s policy for account limits for details. Other nodes in the registry MAY NOT place additional restrictions on publishing limits established by a custodial node. - */ - public static final int E_ACCOUNT_LIMIT_EXCEEDED = 10160; - /** - * E_busy: (10400) Signifies that the request cannot be processed at the current time. - */ - public static final int E_BUSY = 10400; - /** - * NON UDDIv3 spec error - */ - public static final int E_CATEGORIZATION_NOT_ALLOWED = 20100; - /** - * E_fatalError: (10500) Signifies that a serious technical error has occurred while processing the request. - */ - public static final int E_FATAL_ERROR = 10500; - /** - * E_invalidKeyPassed: (10210) Signifies that the uddiKey value passed did not match with any known key values. The details on the invalid key SHOULD be included in the dispositionReport element. - */ - public static final int E_INVALID_KEY_PASSED = 10210; - /** - * E_invalidProjection: (20230) Signifies that an attempt was made to save a businessEntity containing a service projection where the serviceKey does not belong to the business designated by the businessKey. The serviceKey of at least one such businessService SHOULD be included in the dispositionReport. - */ - public static final int E_INVALID_PROJECTION = 20230; - /** - * NON UDDIv3 spec - */ - public static final int E_INVALID_CATEGORY = 20000; - /** - * E_invalidCompletionStatus: (30100) Signifies that one of the assertion status values passed is unrecognized. The completion status that caused the problem SHOULD be clearly indicated in the error text. - */ - public static final int E_INVALID_COMPLETION_STATUS = 30100; - - public static final int E_INVALID_URL_PASSED = 10220; - /** - * E_invalidValue: (20200) This error code has multiple uses. This error code applies to the subscription APIs and the value set APIs. It can be used to indicate that a value that was passed in a keyValue attribute did not pass validation. This applies to checked value sets that are referenced using keyedReferences. The error text SHOULD clearly indicate the key and value combination that failed validation. It can also be used to indicate that a chunkToken supplied is invalid. This applies in both subscription and value set APIs. The error text SHOULD clearly indicate the reason for failure. - */ - public static final int E_INVALID_VALUE = 20200; - /** - * E_invalidCombination: (40500) Signifies conflicting find qualifiers have been specified. The find qualifiers that caused the problem SHOULD be clearly indicated in the error text. - */ - public static final int E_INVALID_COMBINATION = 40500; - public static final int E_KEY_RETIRED = 10310; - /** - * E_keyUnavailable: (40100) Signifies that the proposed key is in a partition that has already been assigned to some other publisher. - */ - public static final int E_KEY_UNAVAILABLE = 40100; - public static final int E_LANGUAGE_ERROR = 10060; - /** - * E_messageTooLarge: (30110) Signifies that the message is too large. The upper limit SHOULD be clearly indicated in the error text. - */ - public static final int E_MESSAGE_TOO_LARGE = 30110; - public static final int E_NAME_TOO_LONG = 10020; - public static final int E_OPERATOR_MISMATCH = 10130; - public static final int E_PUBLISHER_CANCELLED = 30220; - /** - * Signifies that a subscription cannot be renewed. The request has been denied due to either node or registry policy. - */ - public static final int E_REQUEST_DENIED = 30210; - public static final int E_SECRET_UNKNOWN = 30230; - public static final int E_SUCCESS = 0; - public static final int E_TOO_MANY_OPTIONS = 10030; - public static final int E_TRANSFER_ABORTED = 30200; - /** - * E_unrecognizedVersion: (10040) Signifies that the value of the namespace attribute is unsupported by the node being queried. - */ - public static final int E_UNRECOGNIZED_VERSION = 10040; - /** - * E_unknownUser: (10150) Signifies that the user ID and password pair passed in a get_authToken API is not known to the UDDI node or is not valid. - */ - public static final int E_UNKNOWN_USER = 10150; - /** - * E_unsupported: (10050) Signifies that the implementer does not support a feature or API. - */ - public static final int E_UNSUPPORTED = 10050; - /** - * E_userMismatch: (10140) Signifies that an attempt was made to use the publishing API to change data that is controlled by another party. - */ - public static final int E_USER_MISMATCH = 10140; - /** - * E_valueNotAllowed: (20210) Signifies that a value did not pass validation because of contextual issues. The value may be valid in some contexts, but not in the context used. The error text MAY contain information about the contextual problem. - */ - public static final int E_VALUE_NOT_ALLOWED = 20210; - /** - * E_unvalidatable: (20220) Signifies that an attempt was made to reference a value set in a keyedReference whose tModel is categorized with the unvalidatable categorization. - */ - public static final int E_UNVALIDATABLE = 20220; - public static final int E_REQUEST_TIMEOUT = 20240; - /** - * E_invalidTime: (40030) Signifies that the time period, the date/time, or the pair of date/time is invalid. The error structure signifies the condition that occurred and the error text clearly calls out the cause of the problem. - */ - public static final int E_INVALID_TIME = 40030; - /** - * E_resultSetTooLarge: (40300) Signifies that the UDDI node deems that a result set from an inquiry is too large, and requests to obtain the results are not honored, even using subsets. The inquiry that triggered this error should be refined and re-issued. - */ - public static final int E_RESULT_SET_TOO_LARGE = 40300; - /** - * E_tokenAlreadyExists: (40070) Signifies that one or more of the businessKey or tModelKey elements that identify entities to be transferred are not owned by the publisher identified by the authInfo element. The error text SHOULD clearly indicate which entity keys caused the error. - */ - public static final int E_TOKEN_ALREADY_EXISTS = 40070; - /** - * E_transferNotAllowed: (40600) Signifies that the transfer of one or more entities has been by either the custodial node or the target node because the transfer token has expired or an attempt was made to transfer an unauthorized entity. - */ - public static final int E_TRANSFER_NOT_ALLOWED = 40600; - - public static final String lookupErrCode(int errno) { - switch (errno) { - case E_ACCOUNT_LIMIT_EXCEEDED : return DispositionReport.E_ACCOUNT_LIMIT_EXCEEDED; - case E_ASSERTION_NOT_FOUND : return DispositionReport.E_ASSERTION_NOT_FOUND; - case E_AUTH_TOKEN_EXPIRED : return DispositionReport.E_AUTH_TOKEN_EXPIRED; - case E_AUTH_TOKEN_REQUIRED : return DispositionReport.E_AUTH_TOKEN_REQUIRED; - case E_BUSY : return DispositionReport.E_BUSY; - case E_CATEGORIZATION_NOT_ALLOWED : return DispositionReport.E_CATEGORIZATION_NOT_ALLOWED; - case E_FATAL_ERROR : return DispositionReport.E_FATAL_ERROR; - case E_INVALID_COMBINATION : return DispositionReport.E_INVALID_COMBINATION; - case E_INVALID_CATEGORY : return DispositionReport.E_INVALID_CATEGORY; - case E_INVALID_COMPLETION_STATUS : return DispositionReport.E_INVALID_COMPLETION_STATUS; - case E_INVALID_KEY_PASSED : return DispositionReport.E_INVALID_KEY_PASSED; - case E_KEY_UNAVAILABLE : return DispositionReport.E_KEY_UNAVAILABLE; - case E_INVALID_PROJECTION : return DispositionReport.E_INVALID_PROJECTION; - case E_INVALID_TIME : return DispositionReport.E_INVALID_TIME; - case E_INVALID_URL_PASSED : return DispositionReport.E_INVALID_URL_PASSED; - case E_INVALID_VALUE : return DispositionReport.E_INVALID_VALUE; - case E_KEY_RETIRED : return DispositionReport.E_KEY_RETIRED; - case E_LANGUAGE_ERROR : return DispositionReport.E_LANGUAGE_ERROR; - case E_MESSAGE_TOO_LARGE : return DispositionReport.E_MESSAGE_TOO_LARGE; - case E_NAME_TOO_LONG : return DispositionReport.E_NAME_TOO_LONG; - case E_OPERATOR_MISMATCH : return DispositionReport.E_OPERATOR_MISMATCH; - case E_PUBLISHER_CANCELLED : return DispositionReport.E_PUBLISHER_CANCELLED; - case E_REQUEST_DENIED : return DispositionReport.E_REQUEST_DENIED; - case E_REQUEST_TIMEOUT : return DispositionReport.E_REQUEST_TIMEOUT; - case E_RESULT_SET_TOO_LARGE : return DispositionReport.E_RESULT_SET_TOO_LARGE; - case E_SECRET_UNKNOWN : return DispositionReport.E_SECRET_UNKNOWN; - case E_SUCCESS : return DispositionReport.E_SUCCESS; - case E_TOO_MANY_OPTIONS : return DispositionReport.E_TOO_MANY_OPTIONS; - case E_TRANSFER_ABORTED : return DispositionReport.E_TRANSFER_ABORTED; - case E_UNKNOWN_USER : return DispositionReport.E_UNKNOWN_USER; - case E_UNRECOGNIZED_VERSION : return DispositionReport.E_UNRECOGNIZED_VERSION; - case E_UNSUPPORTED : return DispositionReport.E_UNSUPPORTED; - case E_UNVALIDATABLE : return DispositionReport.E_UNVALIDATABLE; - case E_USER_MISMATCH : return DispositionReport.E_USER_MISMATCH; - case E_VALUE_NOT_ALLOWED : return DispositionReport.E_VALUE_NOT_ALLOWED; - case E_TOKEN_ALREADY_EXISTS : return DispositionReport.E_TOKEN_ALREADY_EXISTS; - case E_TRANSFER_NOT_ALLOWED : return DispositionReport.E_TRANSFER_NOT_ALLOWED; - default : return null; - } - } - - public static final String lookupErrText(int errno) { - String errCode = lookupErrCode(errno); - if (errCode == null) - return null; - return ResourceConfig.getGlobalMessage(errCode); - } - - public static final DispositionReport buildDispositionReport(int errNo) { - DispositionReport dr = new DispositionReport(); - Result res = new Result(); - res.setErrno(errNo); - - ErrInfo ei = new ErrInfo(); - ei.setErrCode(lookupErrCode(errNo)); - ei.setValue(lookupErrText(errNo)); - - res.setErrInfo(ei); - - dr.getResult().add(res); - - return dr; - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.error; + +import org.apache.juddi.config.ResourceConfig; +import org.uddi.api_v3.DispositionReport; +import org.uddi.api_v3.Result; +import org.uddi.api_v3.ErrInfo; + +/** + * @author Jeff Faath + */ +public class UDDIErrorHelper { + /** + * E_assertionNotFound: (30000) Signifies that a particular publisher assertion cannot be identified in a save or delete operation. + */ + public static final int E_ASSERTION_NOT_FOUND = 30000; + /** + * E_authTokenExpired: (10110) Signifies that the authentication token information has timed out. + */ + public static final int E_AUTH_TOKEN_EXPIRED = 10110; + /** + * E_authTokenRequired: (10120) Signifies that an authentication token is missing or is invalid for an API call that requires authentication. + */ + public static final int E_AUTH_TOKEN_REQUIRED = 10120; + /** + * E_accountLimitExceeded: (10160) Signifies that a save request exceeded the quantity limits for a given data type. Account limits are established based on the relationship between an individual publisher and an individual node. See your UDDI node’s policy for account limits for details. Other nodes in the registry MAY NOT place additional restrictions on publishing limits established by a custodial node. + */ + public static final int E_ACCOUNT_LIMIT_EXCEEDED = 10160; + /** + * E_busy: (10400) Signifies that the request cannot be processed at the current time. + */ + public static final int E_BUSY = 10400; + /** + * NON UDDIv3 spec error + */ + public static final int E_CATEGORIZATION_NOT_ALLOWED = 20100; + /** + * E_fatalError: (10500) Signifies that a serious technical error has occurred while processing the request. + */ + public static final int E_FATAL_ERROR = 10500; + /** + * E_invalidKeyPassed: (10210) Signifies that the uddiKey value passed did not match with any known key values. The details on the invalid key SHOULD be included in the dispositionReport element. + */ + public static final int E_INVALID_KEY_PASSED = 10210; + /** + * E_invalidProjection: (20230) Signifies that an attempt was made to save a businessEntity containing a service projection where the serviceKey does not belong to the business designated by the businessKey. The serviceKey of at least one such businessService SHOULD be included in the dispositionReport. + */ + public static final int E_INVALID_PROJECTION = 20230; + /** + * NON UDDIv3 spec + */ + public static final int E_INVALID_CATEGORY = 20000; + /** + * E_invalidCompletionStatus: (30100) Signifies that one of the assertion status values passed is unrecognized. The completion status that caused the problem SHOULD be clearly indicated in the error text. + */ + public static final int E_INVALID_COMPLETION_STATUS = 30100; + + public static final int E_INVALID_URL_PASSED = 10220; + /** + * E_invalidValue: (20200) This error code has multiple uses. This error code applies to the subscription APIs and the value set APIs. It can be used to indicate that a value that was passed in a keyValue attribute did not pass validation. This applies to checked value sets that are referenced using keyedReferences. The error text SHOULD clearly indicate the key and value combination that failed validation. It can also be used to indicate that a chunkToken supplied is invalid. This applies in both subscription and value set APIs. The error text SHOULD clearly indicate the reason for failure. + */ + public static final int E_INVALID_VALUE = 20200; + /** + * E_invalidCombination: (40500) Signifies conflicting find qualifiers have been specified. The find qualifiers that caused the problem SHOULD be clearly indicated in the error text. + */ + public static final int E_INVALID_COMBINATION = 40500; + public static final int E_KEY_RETIRED = 10310; + /** + * E_keyUnavailable: (40100) Signifies that the proposed key is in a partition that has already been assigned to some other publisher. + */ + public static final int E_KEY_UNAVAILABLE = 40100; + public static final int E_LANGUAGE_ERROR = 10060; + /** + * E_messageTooLarge: (30110) Signifies that the message is too large. The upper limit SHOULD be clearly indicated in the error text. + */ + public static final int E_MESSAGE_TOO_LARGE = 30110; + public static final int E_NAME_TOO_LONG = 10020; + public static final int E_OPERATOR_MISMATCH = 10130; + public static final int E_PUBLISHER_CANCELLED = 30220; + /** + * Signifies that a subscription cannot be renewed. The request has been denied due to either node or registry policy. + */ + public static final int E_REQUEST_DENIED = 30210; + public static final int E_SECRET_UNKNOWN = 30230; + public static final int E_SUCCESS = 0; + public static final int E_TOO_MANY_OPTIONS = 10030; + public static final int E_TRANSFER_ABORTED = 30200; + /** + * E_unrecognizedVersion: (10040) Signifies that the value of the namespace attribute is unsupported by the node being queried. + */ + public static final int E_UNRECOGNIZED_VERSION = 10040; + /** + * E_unknownUser: (10150) Signifies that the user ID and password pair passed in a get_authToken API is not known to the UDDI node or is not valid. + */ + public static final int E_UNKNOWN_USER = 10150; + /** + * E_unsupported: (10050) Signifies that the implementer does not support a feature or API. + */ + public static final int E_UNSUPPORTED = 10050; + /** + * E_userMismatch: (10140) Signifies that an attempt was made to use the publishing API to change data that is controlled by another party. + */ + public static final int E_USER_MISMATCH = 10140; + /** + * E_valueNotAllowed: (20210) Signifies that a value did not pass validation because of contextual issues. The value may be valid in some contexts, but not in the context used. The error text MAY contain information about the contextual problem. + */ + public static final int E_VALUE_NOT_ALLOWED = 20210; + /** + * E_unvalidatable: (20220) Signifies that an attempt was made to reference a value set in a keyedReference whose tModel is categorized with the unvalidatable categorization. + */ + public static final int E_UNVALIDATABLE = 20220; + public static final int E_REQUEST_TIMEOUT = 20240; + /** + * E_invalidTime: (40030) Signifies that the time period, the date/time, or the pair of date/time is invalid. The error structure signifies the condition that occurred and the error text clearly calls out the cause of the problem. + */ + public static final int E_INVALID_TIME = 40030; + /** + * E_resultSetTooLarge: (40300) Signifies that the UDDI node deems that a result set from an inquiry is too large, and requests to obtain the results are not honored, even using subsets. The inquiry that triggered this error should be refined and re-issued. + */ + public static final int E_RESULT_SET_TOO_LARGE = 40300; + /** + * E_tokenAlreadyExists: (40070) Signifies that one or more of the businessKey or tModelKey elements that identify entities to be transferred are not owned by the publisher identified by the authInfo element. The error text SHOULD clearly indicate which entity keys caused the error. + */ + public static final int E_TOKEN_ALREADY_EXISTS = 40070; + /** + * E_transferNotAllowed: (40600) Signifies that the transfer of one or more entities has been by either the custodial node or the target node because the transfer token has expired or an attempt was made to transfer an unauthorized entity. + */ + public static final int E_TRANSFER_NOT_ALLOWED = 40600; + + public static final String lookupErrCode(int errno) { + switch (errno) { + case E_ACCOUNT_LIMIT_EXCEEDED : return DispositionReport.E_ACCOUNT_LIMIT_EXCEEDED; + case E_ASSERTION_NOT_FOUND : return DispositionReport.E_ASSERTION_NOT_FOUND; + case E_AUTH_TOKEN_EXPIRED : return DispositionReport.E_AUTH_TOKEN_EXPIRED; + case E_AUTH_TOKEN_REQUIRED : return DispositionReport.E_AUTH_TOKEN_REQUIRED; + case E_BUSY : return DispositionReport.E_BUSY; + case E_CATEGORIZATION_NOT_ALLOWED : return DispositionReport.E_CATEGORIZATION_NOT_ALLOWED; + case E_FATAL_ERROR : return DispositionReport.E_FATAL_ERROR; + case E_INVALID_COMBINATION : return DispositionReport.E_INVALID_COMBINATION; + case E_INVALID_CATEGORY : return DispositionReport.E_INVALID_CATEGORY; + case E_INVALID_COMPLETION_STATUS : return DispositionReport.E_INVALID_COMPLETION_STATUS; + case E_INVALID_KEY_PASSED : return DispositionReport.E_INVALID_KEY_PASSED; + case E_KEY_UNAVAILABLE : return DispositionReport.E_KEY_UNAVAILABLE; + case E_INVALID_PROJECTION : return DispositionReport.E_INVALID_PROJECTION; + case E_INVALID_TIME : return DispositionReport.E_INVALID_TIME; + case E_INVALID_URL_PASSED : return DispositionReport.E_INVALID_URL_PASSED; + case E_INVALID_VALUE : return DispositionReport.E_INVALID_VALUE; + case E_KEY_RETIRED : return DispositionReport.E_KEY_RETIRED; + case E_LANGUAGE_ERROR : return DispositionReport.E_LANGUAGE_ERROR; + case E_MESSAGE_TOO_LARGE : return DispositionReport.E_MESSAGE_TOO_LARGE; + case E_NAME_TOO_LONG : return DispositionReport.E_NAME_TOO_LONG; + case E_OPERATOR_MISMATCH : return DispositionReport.E_OPERATOR_MISMATCH; + case E_PUBLISHER_CANCELLED : return DispositionReport.E_PUBLISHER_CANCELLED; + case E_REQUEST_DENIED : return DispositionReport.E_REQUEST_DENIED; + case E_REQUEST_TIMEOUT : return DispositionReport.E_REQUEST_TIMEOUT; + case E_RESULT_SET_TOO_LARGE : return DispositionReport.E_RESULT_SET_TOO_LARGE; + case E_SECRET_UNKNOWN : return DispositionReport.E_SECRET_UNKNOWN; + case E_SUCCESS : return DispositionReport.E_SUCCESS; + case E_TOO_MANY_OPTIONS : return DispositionReport.E_TOO_MANY_OPTIONS; + case E_TRANSFER_ABORTED : return DispositionReport.E_TRANSFER_ABORTED; + case E_UNKNOWN_USER : return DispositionReport.E_UNKNOWN_USER; + case E_UNRECOGNIZED_VERSION : return DispositionReport.E_UNRECOGNIZED_VERSION; + case E_UNSUPPORTED : return DispositionReport.E_UNSUPPORTED; + case E_UNVALIDATABLE : return DispositionReport.E_UNVALIDATABLE; + case E_USER_MISMATCH : return DispositionReport.E_USER_MISMATCH; + case E_VALUE_NOT_ALLOWED : return DispositionReport.E_VALUE_NOT_ALLOWED; + case E_TOKEN_ALREADY_EXISTS : return DispositionReport.E_TOKEN_ALREADY_EXISTS; + case E_TRANSFER_NOT_ALLOWED : return DispositionReport.E_TRANSFER_NOT_ALLOWED; + default : return null; + } + } + + public static final String lookupErrText(int errno) { + String errCode = lookupErrCode(errno); + if (errCode == null) + return null; + return ResourceConfig.getGlobalMessage(errCode); + } + + public static final DispositionReport buildDispositionReport(int errNo) { + DispositionReport dr = new DispositionReport(); + Result res = new Result(); + res.setErrno(errNo); + + ErrInfo ei = new ErrInfo(); + ei.setErrCode(lookupErrCode(errNo)); + ei.setValue(lookupErrText(errNo)); + + res.setErrInfo(ei); + + dr.getResult().add(res); + + return dr; + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/UnknownUserException.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/UnknownUserException.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/UnknownUserException.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/UnknownUserException.java index 1d5068e4f..e7ae36ef6 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/error/UnknownUserException.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/UnknownUserException.java @@ -1,36 +1,36 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.error; - -import org.apache.juddi.v3.error.AuthenticationException; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.UDDIErrorHelper; - -/** - * E_unknownUser: (10150) Signifies that the user ID and password pair passed in a get_authToken API is not known to the UDDI node or is not valid. - * - * @author Jeff Faath - */ -public class UnknownUserException extends AuthenticationException { - - private static final long serialVersionUID = -3435412795602392194L; - - public UnknownUserException(ErrorMessage message) { - super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_UNKNOWN_USER)); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.error; + +import org.apache.juddi.v3.error.AuthenticationException; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.UDDIErrorHelper; + +/** + * E_unknownUser: (10150) Signifies that the user ID and password pair passed in a get_authToken API is not known to the UDDI node or is not valid. + * + * @author Jeff Faath + */ +public class UnknownUserException extends AuthenticationException { + + private static final long serialVersionUID = -3435412795602392194L; + + public UnknownUserException(ErrorMessage message) { + super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_UNKNOWN_USER)); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/UnsupportedException.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/UnsupportedException.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/UnsupportedException.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/UnsupportedException.java index 57ad83141..aa29dd942 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/error/UnsupportedException.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/UnsupportedException.java @@ -1,36 +1,36 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.error; - -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.RegistryException; -import org.apache.juddi.v3.error.UDDIErrorHelper; - -/** - * E_unsupported: (10050) Signifies that the implementer does not support a feature or API. - * - * @author Jeff Faath - */ -public class UnsupportedException extends RegistryException { - - private static final long serialVersionUID = -2979768558052264874L; - - public UnsupportedException(ErrorMessage message) { - super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_UNSUPPORTED)); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.error; + +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.RegistryException; +import org.apache.juddi.v3.error.UDDIErrorHelper; + +/** + * E_unsupported: (10050) Signifies that the implementer does not support a feature or API. + * + * @author Jeff Faath + */ +public class UnsupportedException extends RegistryException { + + private static final long serialVersionUID = -2979768558052264874L; + + public UnsupportedException(ErrorMessage message) { + super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_UNSUPPORTED)); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/UserMismatchException.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/UserMismatchException.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/UserMismatchException.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/UserMismatchException.java index c1151ba0e..f65ea4b1a 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/error/UserMismatchException.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/UserMismatchException.java @@ -1,32 +1,32 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.error; - -/** - * E_userMismatch: (10140) Signifies that an attempt was made to use the publishing API to change data that is controlled by another party. - * - * @author Jeff Faath - */ -public class UserMismatchException extends RegistryException { - - private static final long serialVersionUID = -3459894364164959205L; - - public UserMismatchException(ErrorMessage message) { - super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_USER_MISMATCH)); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.error; + +/** + * E_userMismatch: (10140) Signifies that an attempt was made to use the publishing API to change data that is controlled by another party. + * + * @author Jeff Faath + */ +public class UserMismatchException extends RegistryException { + + private static final long serialVersionUID = -3459894364164959205L; + + public UserMismatchException(ErrorMessage message) { + super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_USER_MISMATCH)); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/ValueNotAllowedException.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/ValueNotAllowedException.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/ValueNotAllowedException.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/ValueNotAllowedException.java index 3cd00545b..b1764671e 100644 --- a/juddi-core/src/main/java/org/apache/juddi/v3/error/ValueNotAllowedException.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/ValueNotAllowedException.java @@ -1,37 +1,37 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.v3.error; - -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.RegistryException; -import org.apache.juddi.v3.error.UDDIErrorHelper; - -/** - * E_valueNotAllowed: (20210) Signifies that a value did not pass validation because of contextual issues. The value may be valid in some contexts, but - * not in the context used. The error text MAY contain information about the contextual problem. - * - * @author Jeff Faath - */ -public class ValueNotAllowedException extends RegistryException { - - private static final long serialVersionUID = -4003033708851434957L; - - public ValueNotAllowedException(ErrorMessage message) { - super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_VALUE_NOT_ALLOWED)); - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.v3.error; + +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.RegistryException; +import org.apache.juddi.v3.error.UDDIErrorHelper; + +/** + * E_valueNotAllowed: (20210) Signifies that a value did not pass validation because of contextual issues. The value may be valid in some contexts, but + * not in the context used. The error text MAY contain information about the contextual problem. + * + * @author Jeff Faath + */ +public class ValueNotAllowedException extends RegistryException { + + private static final long serialVersionUID = -4003033708851434957L; + + public ValueNotAllowedException(ErrorMessage message) { + super(message, UDDIErrorHelper.buildDispositionReport(UDDIErrorHelper.E_VALUE_NOT_ALLOWED)); + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/v3/error/package-info.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/package-info.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/v3/error/package-info.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/v3/error/package-info.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateClerk.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateClerk.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/validation/ValidateClerk.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateClerk.java index 3542c123b..dafbef29f 100644 --- a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateClerk.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateClerk.java @@ -1,99 +1,99 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.validation; - -import java.util.List; - -import javax.persistence.EntityManager; - -import org.apache.juddi.api_v3.Clerk; -import org.apache.juddi.api_v3.Node; -import org.apache.juddi.model.UddiEntityPublisher; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.FatalErrorException; -import org.apache.juddi.v3.error.InvalidKeyPassedException; -import org.apache.juddi.v3.error.ValueNotAllowedException; -import org.uddi.v3_service.DispositionReportFaultMessage; - - -/** - * @author Jeff Faath - */ -public class ValidateClerk extends ValidateUDDIApi { - - public ValidateClerk(UddiEntityPublisher publisher) { - super(publisher); - } - - - - /*------------------------------------------------------------------- - ClientSubscriptionInf functions are specific to jUDDI. - --------------------------------------------------------------------*/ - - - public void validateSaveClerk(EntityManager em, org.apache.juddi.api_v3.SaveClerk body) throws DispositionReportFaultMessage { - - if (body == null) - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - - // No null or empty list - List clerks = body.getClerk(); - if (clerks == null) - throw new ValueNotAllowedException(new ErrorMessage("errors.saveClerk.NoInput")); - - for (Clerk clerk : body.getClerk()) { - validateClerk(em, clerk); - } - - } - - public void validateClerk(EntityManager em, org.apache.juddi.api_v3.Clerk clerk) throws DispositionReportFaultMessage { - - // No null input - if (clerk == null) - throw new ValueNotAllowedException(new ErrorMessage("errors.clerk.NullInput")); - - String name = clerk.getName(); - if (name == null || name.length() == 0) - throw new ValueNotAllowedException(new ErrorMessage("errors.clerk.NoName")); - - String publisherName = clerk.getPublisher(); - if (publisherName == null || publisherName.length() == 0) - throw new ValueNotAllowedException(new ErrorMessage("errors.clerk.NoPublisherName")); - - Node node = clerk.getNode(); - if (node == null) - throw new ValueNotAllowedException(new ErrorMessage("errors.clerk.NullNodeInput")); - - String nodeName = node.getName(); - if (nodeName == null || nodeName.length() == 0) - throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoName")); - - //make sure node exists - //edit, doesn't matter if it doesn't exist, it'll be created on save of the clerk - /*Object obj = em.find(org.apache.juddi.model.Node.class, nodeName); - if (obj == null) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NodeNotFound", nodeName)); -*/ - } - - - - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.validation; + +import java.util.List; + +import javax.persistence.EntityManager; + +import org.apache.juddi.api_v3.Clerk; +import org.apache.juddi.api_v3.Node; +import org.apache.juddi.model.UddiEntityPublisher; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.FatalErrorException; +import org.apache.juddi.v3.error.InvalidKeyPassedException; +import org.apache.juddi.v3.error.ValueNotAllowedException; +import org.uddi.v3_service.DispositionReportFaultMessage; + + +/** + * @author Jeff Faath + */ +public class ValidateClerk extends ValidateUDDIApi { + + public ValidateClerk(UddiEntityPublisher publisher) { + super(publisher); + } + + + + /*------------------------------------------------------------------- + ClientSubscriptionInf functions are specific to jUDDI. + --------------------------------------------------------------------*/ + + + public void validateSaveClerk(EntityManager em, org.apache.juddi.api_v3.SaveClerk body) throws DispositionReportFaultMessage { + + if (body == null) + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + + // No null or empty list + List clerks = body.getClerk(); + if (clerks == null) + throw new ValueNotAllowedException(new ErrorMessage("errors.saveClerk.NoInput")); + + for (Clerk clerk : body.getClerk()) { + validateClerk(em, clerk); + } + + } + + public void validateClerk(EntityManager em, org.apache.juddi.api_v3.Clerk clerk) throws DispositionReportFaultMessage { + + // No null input + if (clerk == null) + throw new ValueNotAllowedException(new ErrorMessage("errors.clerk.NullInput")); + + String name = clerk.getName(); + if (name == null || name.length() == 0) + throw new ValueNotAllowedException(new ErrorMessage("errors.clerk.NoName")); + + String publisherName = clerk.getPublisher(); + if (publisherName == null || publisherName.length() == 0) + throw new ValueNotAllowedException(new ErrorMessage("errors.clerk.NoPublisherName")); + + Node node = clerk.getNode(); + if (node == null) + throw new ValueNotAllowedException(new ErrorMessage("errors.clerk.NullNodeInput")); + + String nodeName = node.getName(); + if (nodeName == null || nodeName.length() == 0) + throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoName")); + + //make sure node exists + //edit, doesn't matter if it doesn't exist, it'll be created on save of the clerk + /*Object obj = em.find(org.apache.juddi.model.Node.class, nodeName); + if (obj == null) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NodeNotFound", nodeName)); +*/ + } + + + + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateClientSubscriptionInfo.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateClientSubscriptionInfo.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/validation/ValidateClientSubscriptionInfo.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateClientSubscriptionInfo.java index d84e41c70..468fbebce 100644 --- a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateClientSubscriptionInfo.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateClientSubscriptionInfo.java @@ -1,140 +1,140 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.validation; - -import java.util.HashSet; -import java.util.List; - -import javax.persistence.EntityManager; - -import org.apache.juddi.api_v3.ClientSubscriptionInfo; -import org.apache.juddi.api_v3.DeleteClientSubscriptionInfo; -import org.apache.juddi.api_v3.GetAllClientSubscriptionInfoDetail; -import org.apache.juddi.api_v3.GetClientSubscriptionInfoDetail; -import org.apache.juddi.api_v3.SaveClientSubscriptionInfo; -import org.apache.juddi.model.UddiEntityPublisher; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.FatalErrorException; -import org.apache.juddi.v3.error.InvalidKeyPassedException; -import org.apache.juddi.v3.error.ValueNotAllowedException; -import org.uddi.v3_service.DispositionReportFaultMessage; - - -/** - * @author Jeff Faath - */ -public class ValidateClientSubscriptionInfo extends ValidateUDDIApi { - - public ValidateClientSubscriptionInfo(UddiEntityPublisher publisher) { - super(publisher); - } - - - - /*------------------------------------------------------------------- - ClientSubscriptionInf functions are specific to jUDDI. - --------------------------------------------------------------------*/ - - public void validateDeleteClientSubscriptionInfo(EntityManager em, DeleteClientSubscriptionInfo body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - - // No null or empty list - List entityKeyList = body.getSubscriptionKey(); - if (entityKeyList == null || entityKeyList.size() == 0) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); - - HashSet dupCheck = new HashSet(); - for (String entityKey : entityKeyList) { - boolean inserted = dupCheck.add(entityKey); - if (!inserted) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); - - Object obj = em.find(org.apache.juddi.model.ClientSubscriptionInfo.class, entityKey); - if (obj == null) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.SubscriptionKeyNotFound", entityKey)); - - } - } - - public void validateSaveClientSubscriptionInfo(EntityManager em, SaveClientSubscriptionInfo body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - - // No null or empty list - List clientSubscriptionInfos = body.getClientSubscriptionInfo(); - if (clientSubscriptionInfos == null) - throw new ValueNotAllowedException(new ErrorMessage("errors.saveclientsubscriptioninfo.NoInput")); - - for (ClientSubscriptionInfo clientSubscriptionInfo : body.getClientSubscriptionInfo()) { - if (clientSubscriptionInfo.getSubscriptionKey()==null || clientSubscriptionInfo.getSubscriptionKey().equals("")) { - throw new ValueNotAllowedException(new ErrorMessage("errors.saveclientsubscriptionKey.NoInput")); - } - validateClerk(em, clientSubscriptionInfo.getFromClerk()); - } - } - - public void validateClerk(EntityManager em, org.apache.juddi.api_v3.Clerk clerk) throws DispositionReportFaultMessage { - - // No null input - if (clerk == null) - throw new ValueNotAllowedException(new ErrorMessage("errors.clerk.NullInput")); - - String name = clerk.getName(); - if (name == null || name.length() == 0) - throw new ValueNotAllowedException(new ErrorMessage("errors.clerk.NoName")); - - //make sure clerk exists - Object obj = em.find(org.apache.juddi.model.Clerk.class, name); - if (obj == null) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ClerkNotFound", name)); - } - - public void validateGetClientSubscriptionInfoDetail(GetClientSubscriptionInfoDetail body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - - // No null or empty list - List clientSubscriptionKeyList = body.getClientSubscriptionKey(); - if (clientSubscriptionKeyList == null || clientSubscriptionKeyList.size() == 0) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); - - HashSet dupCheck = new HashSet(); - for (String clientSubscriptionKey : clientSubscriptionKeyList) { - boolean inserted = dupCheck.add(clientSubscriptionKey); - if (!inserted) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", clientSubscriptionKey)); - } - } - - public void validateGetAllClientSubscriptionDetail(GetAllClientSubscriptionInfoDetail body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - - } - - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.validation; + +import java.util.HashSet; +import java.util.List; + +import javax.persistence.EntityManager; + +import org.apache.juddi.api_v3.ClientSubscriptionInfo; +import org.apache.juddi.api_v3.DeleteClientSubscriptionInfo; +import org.apache.juddi.api_v3.GetAllClientSubscriptionInfoDetail; +import org.apache.juddi.api_v3.GetClientSubscriptionInfoDetail; +import org.apache.juddi.api_v3.SaveClientSubscriptionInfo; +import org.apache.juddi.model.UddiEntityPublisher; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.FatalErrorException; +import org.apache.juddi.v3.error.InvalidKeyPassedException; +import org.apache.juddi.v3.error.ValueNotAllowedException; +import org.uddi.v3_service.DispositionReportFaultMessage; + + +/** + * @author Jeff Faath + */ +public class ValidateClientSubscriptionInfo extends ValidateUDDIApi { + + public ValidateClientSubscriptionInfo(UddiEntityPublisher publisher) { + super(publisher); + } + + + + /*------------------------------------------------------------------- + ClientSubscriptionInf functions are specific to jUDDI. + --------------------------------------------------------------------*/ + + public void validateDeleteClientSubscriptionInfo(EntityManager em, DeleteClientSubscriptionInfo body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + + // No null or empty list + List entityKeyList = body.getSubscriptionKey(); + if (entityKeyList == null || entityKeyList.size() == 0) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); + + HashSet dupCheck = new HashSet(); + for (String entityKey : entityKeyList) { + boolean inserted = dupCheck.add(entityKey); + if (!inserted) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); + + Object obj = em.find(org.apache.juddi.model.ClientSubscriptionInfo.class, entityKey); + if (obj == null) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.SubscriptionKeyNotFound", entityKey)); + + } + } + + public void validateSaveClientSubscriptionInfo(EntityManager em, SaveClientSubscriptionInfo body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + + // No null or empty list + List clientSubscriptionInfos = body.getClientSubscriptionInfo(); + if (clientSubscriptionInfos == null) + throw new ValueNotAllowedException(new ErrorMessage("errors.saveclientsubscriptioninfo.NoInput")); + + for (ClientSubscriptionInfo clientSubscriptionInfo : body.getClientSubscriptionInfo()) { + if (clientSubscriptionInfo.getSubscriptionKey()==null || clientSubscriptionInfo.getSubscriptionKey().equals("")) { + throw new ValueNotAllowedException(new ErrorMessage("errors.saveclientsubscriptionKey.NoInput")); + } + validateClerk(em, clientSubscriptionInfo.getFromClerk()); + } + } + + public void validateClerk(EntityManager em, org.apache.juddi.api_v3.Clerk clerk) throws DispositionReportFaultMessage { + + // No null input + if (clerk == null) + throw new ValueNotAllowedException(new ErrorMessage("errors.clerk.NullInput")); + + String name = clerk.getName(); + if (name == null || name.length() == 0) + throw new ValueNotAllowedException(new ErrorMessage("errors.clerk.NoName")); + + //make sure clerk exists + Object obj = em.find(org.apache.juddi.model.Clerk.class, name); + if (obj == null) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ClerkNotFound", name)); + } + + public void validateGetClientSubscriptionInfoDetail(GetClientSubscriptionInfoDetail body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + + // No null or empty list + List clientSubscriptionKeyList = body.getClientSubscriptionKey(); + if (clientSubscriptionKeyList == null || clientSubscriptionKeyList.size() == 0) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); + + HashSet dupCheck = new HashSet(); + for (String clientSubscriptionKey : clientSubscriptionKeyList) { + boolean inserted = dupCheck.add(clientSubscriptionKey); + if (!inserted) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", clientSubscriptionKey)); + } + } + + public void validateGetAllClientSubscriptionDetail(GetAllClientSubscriptionInfoDetail body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + + } + + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateCustodyTransfer.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateCustodyTransfer.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/ValidateCustodyTransfer.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateCustodyTransfer.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateInquiry.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateInquiry.java similarity index 98% rename from juddi-core/src/main/java/org/apache/juddi/validation/ValidateInquiry.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateInquiry.java index 37d6ae0cf..018eb4e3d 100644 --- a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateInquiry.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateInquiry.java @@ -1,802 +1,802 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.validation; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Hashtable; -import java.util.Map; -import javax.persistence.EntityManager; -import javax.persistence.EntityTransaction; -import org.apache.juddi.api.impl.InquiryHelper; -import org.apache.juddi.api.util.InquiryQuery; -import org.apache.juddi.api.util.QueryStatus; -import org.apache.juddi.config.PersistenceManager; -import org.apache.juddi.mapping.MappingModelToApi; - -import org.uddi.api_v3.GetBusinessDetail; -import org.uddi.api_v3.GetOperationalInfo; -import org.uddi.api_v3.GetServiceDetail; -import org.uddi.api_v3.GetBindingDetail; -import org.uddi.api_v3.GetTModelDetail; -import org.uddi.api_v3.FindBusiness; -import org.uddi.api_v3.FindService; -import org.uddi.api_v3.FindBinding; -import org.uddi.api_v3.FindTModel; -import org.uddi.api_v3.FindRelatedBusinesses; -import org.uddi.api_v3.KeyedReference; -import org.uddi.api_v3.KeyedReferenceGroup; -import org.uddi.api_v3.Name; -import org.uddi.api_v3.TModelBag; - -import org.uddi.v3_service.DispositionReportFaultMessage; - -import org.apache.juddi.model.UddiEntityPublisher; -import org.apache.juddi.query.BusinessServiceQuery; -import org.apache.juddi.query.util.DynamicQuery; -import org.apache.juddi.query.util.FindQualifiers; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.FatalErrorException; -import org.apache.juddi.v3.error.InvalidCombinationException; -import org.apache.juddi.v3.error.InvalidKeyPassedException; -import org.apache.juddi.v3.error.UnsupportedException; -import org.apache.juddi.v3.error.ValueNotAllowedException; -import org.uddi.api_v3.BindingDetail; -import org.uddi.api_v3.ServiceDetail; - -/** - * @author Jeff Faath - * @author Tom Cunningham - * @author Alex O'Ree - */ -public class ValidateInquiry extends ValidateUDDIApi { - - public ValidateInquiry(UddiEntityPublisher publisher) { - super(publisher); - } - - public void validateGetBusinessDetail(GetBusinessDetail body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - // No null or empty list - List entityKeyList = body.getBusinessKey(); - if (entityKeyList == null || entityKeyList.size() == 0) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); - } - - HashSet dupCheck = new HashSet(); - int i = 0; - for (String entityKey : entityKeyList) { - - // Per section 4.4: keys must be case-folded - entityKey = entityKey.toLowerCase(); - entityKeyList.set(i, entityKey); - - boolean inserted = dupCheck.add(entityKey); - if (!inserted) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); - } - - i++; - } - } - - public void validateGetServiceDetail(GetServiceDetail body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - // No null or empty list - List entityKeyList = body.getServiceKey(); - if (entityKeyList == null || entityKeyList.size() == 0) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); - } - - HashSet dupCheck = new HashSet(); - int i = 0; - for (String entityKey : entityKeyList) { - - // Per section 4.4: keys must be case-folded - entityKey = entityKey.toLowerCase(); - entityKeyList.set(i, entityKey); - - boolean inserted = dupCheck.add(entityKey); - if (!inserted) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); - } - - i++; - } - } - - public void validateGetBindingDetail(GetBindingDetail body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - // No null or empty list - List entityKeyList = body.getBindingKey(); - if (entityKeyList == null || entityKeyList.size() == 0) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); - } - - HashSet dupCheck = new HashSet(); - int i = 0; - for (String entityKey : entityKeyList) { - - // Per section 4.4: keys must be case-folded - entityKey = entityKey.toLowerCase(); - entityKeyList.set(i, entityKey); - - boolean inserted = dupCheck.add(entityKey); - if (!inserted) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); - } - - i++; - } - } - - public void validateGetTModelDetail(GetTModelDetail body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - // No null or empty list - List entityKeyList = body.getTModelKey(); - if (entityKeyList == null || entityKeyList.size() == 0) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); - } - - HashSet dupCheck = new HashSet(); - int i = 0; - for (String entityKey : entityKeyList) { - - // Per section 4.4: keys must be case-folded - entityKey = entityKey.toLowerCase(); - entityKeyList.set(i, entityKey); - - boolean inserted = dupCheck.add(entityKey); - if (!inserted) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); - } - - i++; - } - } - - public void validateGetOperationalInfo(GetOperationalInfo body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - // No null or empty list - List entityKeyList = body.getEntityKey(); - if (entityKeyList == null || entityKeyList.size() == 0) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); - } - - HashSet dupCheck = new HashSet(); - int i = 0; - for (String entityKey : entityKeyList) { - - // Per section 4.4: keys must be case-folded - entityKey = entityKey.toLowerCase(); - entityKeyList.set(i, entityKey); - - boolean inserted = dupCheck.add(entityKey); - if (!inserted) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); - } - - i++; - } - } - - public void validateFindBusiness(FindBusiness body) throws DispositionReportFaultMessage { - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - if (body.getCategoryBag() == null && body.getFindTModel() == null && body.getTModelBag() == null && body.getName().size() == 0 - && body.getIdentifierBag() == null && body.getDiscoveryURLs() == null && body.getFindRelatedBusinesses() == null) { - throw new FatalErrorException(new ErrorMessage("errors.findbusiness.NoInput")); - } - - validateNames(body.getName()); - validateFindQualifiers(body.getFindQualifiers()); - validateTModelBag(body.getTModelBag()); - validateFindTModel(body.getFindTModel(), true); - validateFindRelatedBusinesses(body.getFindRelatedBusinesses(), true); - validateDiscoveryUrls(body.getDiscoveryURLs()); - validateIdentifierBag(body.getIdentifierBag()); - validateCategoryBag(body.getCategoryBag()); - - } - - public void validateFindService(FindService body) throws DispositionReportFaultMessage { - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - if (body.getCategoryBag() == null && body.getFindTModel() == null - && (body.getTModelBag() == null || body.getTModelBag().getTModelKey().size() == 0) - && body.getName().size() == 0 && body.getBusinessKey() == null) { - throw new FatalErrorException(new ErrorMessage("errors.findservice.NoInput")); - } - - validateNames(body.getName()); - validateFindQualifiers(body.getFindQualifiers()); - validateTModelBag(body.getTModelBag()); - validateFindTModel(body.getFindTModel(), true); - validateCategoryBag(body.getCategoryBag()); - - } - - public void validateFindBinding(FindBinding body) throws DispositionReportFaultMessage { - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - if (body.getServiceKey()!=null && body.getServiceKey().length() > 0) { - validateServiceExists(body.getServiceKey()); - } - if ((body.getServiceKey()==null || body.getServiceKey().length()==0) && body.getCategoryBag() == null && body.getFindTModel() == null && body.getTModelBag() == null) { - throw new FatalErrorException(new ErrorMessage("errors.findbinding.NoInput")); - } - - validateFindQualifiers(body.getFindQualifiers()); - validateTModelBag(body.getTModelBag()); - validateFindTModel(body.getFindTModel(), true); - validateCategoryBag(body.getCategoryBag()); - validateFindingBindingFQ(body.getFindQualifiers()); - validateFindQualifiers_AppoximateMatchAndCombinedCatbag(body.getFindQualifiers()); - - } - - public void validateFindTModel(FindTModel body, boolean nullAllowed) throws DispositionReportFaultMessage { - if (body == null) { - // When FindTModel objects are embedded in other find calls, null is allowed. - if (nullAllowed) { - return; - } else { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - } - - if (body.getCategoryBag() == null && body.getIdentifierBag() == null && body.getName() == null) { - throw new FatalErrorException(new ErrorMessage("errors.findtmodel.NoInput")); - } - - validateFindQualifiers(body.getFindQualifiers()); - validateIdentifierBag(body.getIdentifierBag()); - validateCategoryBag(body.getCategoryBag()); - validateFindQualifiers_AppoximateMatchAndCombinedCatbag(body.getFindQualifiers()); - } - - public void validateFindRelatedBusinesses(FindRelatedBusinesses body, boolean nullAllowed) throws DispositionReportFaultMessage { - if (body == null) { - // When FindRelatedBusinesses objects are embedded in other find calls, null is allowed. - if (nullAllowed) { - return; - } else { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - } - - if ((body.getBusinessKey() == null || body.getBusinessKey().length() == 0) - && (body.getFromKey() == null || body.getFromKey().length() == 0) - && (body.getToKey() == null || body.getToKey().length() == 0)) { - throw new FatalErrorException(new ErrorMessage("errors.findrelatedbusiness.NoInput")); - } - - boolean businessKeyExists = false; - boolean fromKeyExists = false; - if (body.getBusinessKey() != null && body.getBusinessKey().length() > 0) { - businessKeyExists = true; - - // Per section 4.4: keys must be case-folded - body.setBusinessKey(body.getBusinessKey().toLowerCase()); - } - if (body.getFromKey() != null && body.getFromKey().length() > 0) { - fromKeyExists = true; - if (businessKeyExists) { - throw new FatalErrorException(new ErrorMessage("errors.findrelatedbusiness.MultipleInput")); - } - - // Per section 4.4: keys must be case-folded - body.setFromKey(body.getFromKey().toLowerCase()); - } - if (body.getToKey() != null && body.getToKey().length() > 0) { - if (businessKeyExists || fromKeyExists) { - throw new FatalErrorException(new ErrorMessage("errors.findrelatedbusiness.MultipleInput")); - } - - // Per section 4.4: keys must be case-folded - body.setToKey(body.getToKey().toLowerCase()); - } - - KeyedReference keyedRef = body.getKeyedReference(); - if (keyedRef != null) { - if (keyedRef.getTModelKey() == null || keyedRef.getTModelKey().length() == 0 - || keyedRef.getKeyName() == null || keyedRef.getKeyName().length() == 0 - || keyedRef.getKeyValue() == null || keyedRef.getKeyValue().length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.findrelatedbusiness.BlankKeyedRef")); - } - - validateKeyedReference(keyedRef); - } - validateFindQualifiers(body.getFindQualifiers()); - validateFindRelatedBusinessesFindQualifiers(body.getFindQualifiers()); - validateFindQualifiers_AppoximateMatchAndCombinedCatbag(body.getFindQualifiers()); - } - - public void validateNames(List names) throws DispositionReportFaultMessage { - if (names != null) { - for (Name n : names) { - if (n.getValue() == null || n.getValue().length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.names.NoValue")); - } - ValidatePublish.validateLang(n.getLang()); - } - } - } - - public void validateTModelBag(TModelBag tmodelBag) throws DispositionReportFaultMessage { - // tmodelBag is optional - if (tmodelBag == null) { - return; - } - - if (tmodelBag.getTModelKey() == null || tmodelBag.getTModelKey().size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.tmodelbag.NoInput")); - } - - List keyList = tmodelBag.getTModelKey(); - int i = 0; - for (String key : keyList) { - // Per section 4.4: keys must be case-folded - key = key.toLowerCase(); - keyList.set(i, key); - i++; - } - - } - - public void validateDiscoveryUrls(org.uddi.api_v3.DiscoveryURLs discUrls) throws DispositionReportFaultMessage { - // Discovery Urls is optional - if (discUrls == null) { - return; - } - - // If discUrls does exist, it must have at least one element - List discUrlList = discUrls.getDiscoveryURL(); - if (discUrlList == null || discUrlList.size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.discurls.NoInput")); - } - } - - public void validateCategoryBag(org.uddi.api_v3.CategoryBag categories) throws DispositionReportFaultMessage { - - // Category bag is optional - if (categories == null) { - return; - } - - // If category bag does exist, it must have at least one element - List elems = categories.getKeyedReference(); - List krgs = categories.getKeyedReferenceGroup(); - if ((elems == null || elems.size() == 0) && (krgs == null || krgs.size() == 0)) { - throw new ValueNotAllowedException(new ErrorMessage("errors.categorybag.NoInput")); - } - - for (KeyedReference elem : elems) { - validateKeyedReference(elem); - } - for (KeyedReferenceGroup elem : krgs) { - validateKeyedReferenceGroup(elem); - } - } - - public void validateIdentifierBag(org.uddi.api_v3.IdentifierBag identifiers) throws DispositionReportFaultMessage { - - // Identifier bag is optional - if (identifiers == null) { - return; - } - - // If category bag does exist, it must have at least one element - List keyedRefList = identifiers.getKeyedReference(); - if (keyedRefList == null || keyedRefList.size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.identifierbag.NoInput")); - } - - for (org.uddi.api_v3.KeyedReference keyedRef : keyedRefList) { - validateKeyedReference(keyedRef); - } - } - - public void validateKeyedReferenceGroup(KeyedReferenceGroup krg) throws DispositionReportFaultMessage { - // Keyed reference groups must contain a tModelKey - if (krg.getTModelKey() == null || krg.getTModelKey().length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.keyedreference.NoTModelKey")); - } - - // Per section 4.4: keys must be case-folded - krg.setTModelKey(krg.getTModelKey().toLowerCase()); - - List keyedRefs = krg.getKeyedReference(); - // Should being empty raise an error? - if (keyedRefs != null && keyedRefs.size() > 0) { - for (KeyedReference keyedRef : keyedRefs) { - validateKeyedReference(keyedRef); - } - } - } - - public void validateKeyedReference(KeyedReference kr) throws DispositionReportFaultMessage { - if (kr == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.keyedreference.NullInput")); - } - - // Keyed references must contain a tModelKey and keyValue - if (kr.getTModelKey() == null || kr.getTModelKey().length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.keyedreference.NoTModelKey")); - } - - // Per section 4.4: keys must be case-folded - kr.setTModelKey(kr.getTModelKey().toLowerCase()); - - if (kr.getKeyValue() == null || kr.getKeyValue().length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.keyedreference.NoKeyValue")); - } - } - - private void validateFindQualifiers(org.uddi.api_v3.FindQualifiers findQualifiers) throws DispositionReportFaultMessage { - if (findQualifiers == null) { - return; - } - - List fqList = findQualifiers.getFindQualifier(); - if (fqList == null || fqList.size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.findqualifiers.NoInput")); - } - - Hashtable fqTable = new Hashtable(); - for (String fq : fqList) { - String result = fqTable.put(fq.toUpperCase(), fq.toUpperCase()); - if (result != null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.findqualifiers.DuplicateValue", result)); - } - - ValidateSupportedFindQualifier(fq); - - // Invalid combo: andAllKeys, orAllKeys, and orLikeKeys - if (fq.equalsIgnoreCase(FindQualifiers.AND_ALL_KEYS) || fq.equalsIgnoreCase(FindQualifiers.AND_ALL_KEYS_TMODEL)) { - if (fqTable.get(FindQualifiers.OR_ALL_KEYS.toUpperCase()) != null || fqTable.get(FindQualifiers.OR_ALL_KEYS_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.OR_ALL_KEYS)); - } - - if (fqTable.get(FindQualifiers.OR_LIKE_KEYS.toUpperCase()) != null || fqTable.get(FindQualifiers.OR_LIKE_KEYS_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.OR_LIKE_KEYS)); - } - } else if (fq.equalsIgnoreCase(FindQualifiers.OR_ALL_KEYS) || fq.equalsIgnoreCase(FindQualifiers.OR_ALL_KEYS_TMODEL)) { - if (fqTable.get(FindQualifiers.AND_ALL_KEYS.toUpperCase()) != null || fqTable.get(FindQualifiers.AND_ALL_KEYS_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.AND_ALL_KEYS)); - } - - if (fqTable.get(FindQualifiers.OR_LIKE_KEYS.toUpperCase()) != null || fqTable.get(FindQualifiers.OR_LIKE_KEYS_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.OR_LIKE_KEYS)); - } - } else if (fq.equalsIgnoreCase(FindQualifiers.OR_LIKE_KEYS) || fq.equalsIgnoreCase(FindQualifiers.OR_LIKE_KEYS_TMODEL)) { - if (fqTable.get(FindQualifiers.AND_ALL_KEYS.toUpperCase()) != null || fqTable.get(FindQualifiers.AND_ALL_KEYS_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.AND_ALL_KEYS)); - } - - if (fqTable.get(FindQualifiers.OR_ALL_KEYS.toUpperCase()) != null || fqTable.get(FindQualifiers.OR_ALL_KEYS_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.OR_ALL_KEYS)); - } - } - - // Invalid combo: sortByNameAsc and sortByNameDesc - if (fq.equalsIgnoreCase(FindQualifiers.SORT_BY_NAME_ASC) || fq.equalsIgnoreCase(FindQualifiers.SORT_BY_NAME_ASC_TMODEL)) { - if (fqTable.get(FindQualifiers.SORT_BY_NAME_DESC.toUpperCase()) != null || fqTable.get(FindQualifiers.SORT_BY_NAME_DESC_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.SORT_BY_NAME_DESC)); - } - } else if (fq.equalsIgnoreCase(FindQualifiers.SORT_BY_NAME_DESC) || fq.equalsIgnoreCase(FindQualifiers.SORT_BY_NAME_DESC_TMODEL)) { - if (fqTable.get(FindQualifiers.SORT_BY_NAME_ASC.toUpperCase()) != null || fqTable.get(FindQualifiers.SORT_BY_NAME_ASC_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.SORT_BY_NAME_ASC)); - } - } - - // Invalid combo: sortByDateAsc and sortByDateDesc - if (fq.equalsIgnoreCase(FindQualifiers.SORT_BY_DATE_ASC) || fq.equalsIgnoreCase(FindQualifiers.SORT_BY_DATE_ASC_TMODEL)) { - if (fqTable.get(FindQualifiers.SORT_BY_DATE_DESC.toUpperCase()) != null || fqTable.get(FindQualifiers.SORT_BY_DATE_DESC_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.SORT_BY_DATE_DESC)); - } - } else if (fq.equalsIgnoreCase(FindQualifiers.SORT_BY_DATE_DESC) || fq.equalsIgnoreCase(FindQualifiers.SORT_BY_DATE_DESC_TMODEL)) { - if (fqTable.get(FindQualifiers.SORT_BY_DATE_ASC.toUpperCase()) != null || fqTable.get(FindQualifiers.SORT_BY_DATE_ASC_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.SORT_BY_DATE_ASC)); - } - } - - // Invalid combo: combineCategoryBags, serviceSubset and bindingSubset - if (fq.equalsIgnoreCase(FindQualifiers.COMBINE_CATEGORY_BAGS) || fq.equalsIgnoreCase(FindQualifiers.COMBINE_CATEGORY_BAGS_TMODEL)) { - if (fqTable.get(FindQualifiers.SERVICE_SUBSET.toUpperCase()) != null || fqTable.get(FindQualifiers.SERVICE_SUBSET_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.SERVICE_SUBSET)); - } - - if (fqTable.get(FindQualifiers.BINDING_SUBSET.toUpperCase()) != null || fqTable.get(FindQualifiers.BINDING_SUBSET_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.BINDING_SUBSET)); - } - } else if (fq.equalsIgnoreCase(FindQualifiers.SERVICE_SUBSET) || fq.equalsIgnoreCase(FindQualifiers.SERVICE_SUBSET_TMODEL)) { - if (fqTable.get(FindQualifiers.COMBINE_CATEGORY_BAGS.toUpperCase()) != null || fqTable.get(FindQualifiers.COMBINE_CATEGORY_BAGS_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.COMBINE_CATEGORY_BAGS)); - } - - if (fqTable.get(FindQualifiers.BINDING_SUBSET.toUpperCase()) != null || fqTable.get(FindQualifiers.BINDING_SUBSET_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.BINDING_SUBSET)); - } - } else if (fq.equalsIgnoreCase(FindQualifiers.BINDING_SUBSET) || fq.equalsIgnoreCase(FindQualifiers.BINDING_SUBSET_TMODEL)) { - if (fqTable.get(FindQualifiers.SERVICE_SUBSET.toUpperCase()) != null || fqTable.get(FindQualifiers.SERVICE_SUBSET_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.SERVICE_SUBSET)); - } - - if (fqTable.get(FindQualifiers.COMBINE_CATEGORY_BAGS.toUpperCase()) != null || fqTable.get(FindQualifiers.COMBINE_CATEGORY_BAGS_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.COMBINE_CATEGORY_BAGS)); - } - } - - // Invalid combo: exactMatch and approximateMatch - if (fq.equalsIgnoreCase(FindQualifiers.EXACT_MATCH) || fq.equalsIgnoreCase(FindQualifiers.EXACT_MATCH_TMODEL)) { - if (fqTable.get(FindQualifiers.APPROXIMATE_MATCH.toUpperCase()) != null || fqTable.get(FindQualifiers.APPROXIMATE_MATCH_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.APPROXIMATE_MATCH)); - } - } else if (fq.equalsIgnoreCase(FindQualifiers.APPROXIMATE_MATCH) || fq.equalsIgnoreCase(FindQualifiers.APPROXIMATE_MATCH_TMODEL)) { - if (fqTable.get(FindQualifiers.EXACT_MATCH.toUpperCase()) != null || fqTable.get(FindQualifiers.EXACT_MATCH_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.EXACT_MATCH)); - } - } - - // Invalid combo: exactMatch and caseInsensitiveMatch - if (fq.equalsIgnoreCase(FindQualifiers.EXACT_MATCH) || fq.equalsIgnoreCase(FindQualifiers.EXACT_MATCH_TMODEL)) { - if (fqTable.get(FindQualifiers.CASE_INSENSITIVE_MATCH.toUpperCase()) != null || fqTable.get(FindQualifiers.CASE_INSENSITIVE_MATCH_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.CASE_INSENSITIVE_MATCH)); - } - } else if (fq.equalsIgnoreCase(FindQualifiers.CASE_INSENSITIVE_MATCH) || fq.equalsIgnoreCase(FindQualifiers.CASE_INSENSITIVE_MATCH_TMODEL)) { - if (fqTable.get(FindQualifiers.EXACT_MATCH.toUpperCase()) != null || fqTable.get(FindQualifiers.EXACT_MATCH_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.EXACT_MATCH)); - } - } - - // Invalid combo: binarySort and UTS-10 - if (fq.equalsIgnoreCase(FindQualifiers.BINARY_SORT) || fq.equalsIgnoreCase(FindQualifiers.BINARY_SORT_TMODEL)) { - if (fqTable.get(FindQualifiers.UTS_10.toUpperCase()) != null || fqTable.get(FindQualifiers.UTS_10_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.UTS_10)); - } - } else if (fq.equalsIgnoreCase(FindQualifiers.UTS_10) || fq.equalsIgnoreCase(FindQualifiers.UTS_10_TMODEL)) { - if (fqTable.get(FindQualifiers.BINARY_SORT.toUpperCase()) != null || fqTable.get(FindQualifiers.BINARY_SORT_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.BINARY_SORT)); - } - } - - // Invalid combo: diacriticSensitiveMatch and diacriticInsensitiveMatch - if (fq.equalsIgnoreCase(FindQualifiers.DIACRITIC_SENSITIVE_MATCH) || fq.equalsIgnoreCase(FindQualifiers.DIACRITIC_SENSITIVE_MATCH_TMODEL)) { - if (fqTable.get(FindQualifiers.DIACRITIC_INSENSITIVE_MATCH.toUpperCase()) != null || fqTable.get(FindQualifiers.DIACRITIC_INSENSITIVE_MATCH_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.DIACRITIC_INSENSITIVE_MATCH)); - } - } else if (fq.equalsIgnoreCase(FindQualifiers.DIACRITIC_INSENSITIVE_MATCH) || fq.equalsIgnoreCase(FindQualifiers.DIACRITIC_INSENSITIVE_MATCH_TMODEL)) { - if (fqTable.get(FindQualifiers.DIACRITIC_SENSITIVE_MATCH.toUpperCase()) != null || fqTable.get(FindQualifiers.DIACRITIC_SENSITIVE_MATCH_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.DIACRITIC_SENSITIVE_MATCH)); - } - } - - // Invalid combo: exactMatch and diacriticInsensitiveMatch - if (fq.equalsIgnoreCase(FindQualifiers.EXACT_MATCH) || fq.equalsIgnoreCase(FindQualifiers.EXACT_MATCH_TMODEL)) { - if (fqTable.get(FindQualifiers.DIACRITIC_INSENSITIVE_MATCH.toUpperCase()) != null || fqTable.get(FindQualifiers.DIACRITIC_INSENSITIVE_MATCH_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.DIACRITIC_INSENSITIVE_MATCH)); - } - } else if (fq.equalsIgnoreCase(FindQualifiers.DIACRITIC_INSENSITIVE_MATCH) || fq.equalsIgnoreCase(FindQualifiers.DIACRITIC_INSENSITIVE_MATCH_TMODEL)) { - if (fqTable.get(FindQualifiers.EXACT_MATCH.toUpperCase()) != null || fqTable.get(FindQualifiers.EXACT_MATCH_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.EXACT_MATCH)); - } - } - - // Invalid combo: caseSensitiveSort and caseInsensitiveSort - if (fq.equalsIgnoreCase(FindQualifiers.CASE_SENSITIVE_SORT) || fq.equalsIgnoreCase(FindQualifiers.CASE_SENSITIVE_SORT_TMODEL)) { - if (fqTable.get(FindQualifiers.CASE_INSENSITIVE_SORT.toUpperCase()) != null || fqTable.get(FindQualifiers.CASE_INSENSITIVE_SORT_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.CASE_INSENSITIVE_SORT)); - } - } else if (fq.equalsIgnoreCase(FindQualifiers.CASE_INSENSITIVE_SORT) || fq.equalsIgnoreCase(FindQualifiers.CASE_INSENSITIVE_SORT_TMODEL)) { - if (fqTable.get(FindQualifiers.CASE_SENSITIVE_SORT.toUpperCase()) != null || fqTable.get(FindQualifiers.CASE_SENSITIVE_SORT_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.CASE_SENSITIVE_SORT)); - } - } - - // Invalid combo: caseSensitiveMatch and caseInsensitiveMatch - if (fq.equalsIgnoreCase(FindQualifiers.CASE_SENSITIVE_MATCH) || fq.equalsIgnoreCase(FindQualifiers.CASE_SENSITIVE_MATCH_TMODEL)) { - if (fqTable.get(FindQualifiers.CASE_INSENSITIVE_MATCH.toUpperCase()) != null || fqTable.get(FindQualifiers.CASE_INSENSITIVE_MATCH_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.CASE_INSENSITIVE_MATCH)); - } - } else if (fq.equalsIgnoreCase(FindQualifiers.CASE_INSENSITIVE_MATCH) || fq.equalsIgnoreCase(FindQualifiers.CASE_INSENSITIVE_MATCH_TMODEL)) { - if (fqTable.get(FindQualifiers.CASE_SENSITIVE_MATCH.toUpperCase()) != null || fqTable.get(FindQualifiers.CASE_SENSITIVE_MATCH_TMODEL.toUpperCase()) != null) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.CASE_SENSITIVE_MATCH)); - } - } - - } - } - - private void validateFindingBindingFQ(org.uddi.api_v3.FindQualifiers findQualifiers) throws InvalidCombinationException { - if (findQualifiers == null) { - return; - } - for (int i = 0; i < findQualifiers.getFindQualifier().size(); i++) { - if (findQualifiers.getFindQualifier().get(i).equals(FindQualifiers.BINARY_SORT) || findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.BINARY_SORT_TMODEL)) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", FindQualifiers.BINARY_SORT)); - } - if (findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.CASE_INSENSITIVE_MATCH) || findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.CASE_INSENSITIVE_MATCH_TMODEL)) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", FindQualifiers.CASE_INSENSITIVE_MATCH)); - } - if (findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.CASE_SENSITIVE_MATCH) || findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.CASE_SENSITIVE_MATCH_TMODEL)) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", FindQualifiers.CASE_SENSITIVE_MATCH)); - } - if (findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.CASE_INSENSITIVE_SORT) || findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.CASE_INSENSITIVE_SORT_TMODEL)) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", FindQualifiers.CASE_INSENSITIVE_SORT)); - } - if (findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.CASE_SENSITIVE_SORT) || findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.CASE_SENSITIVE_SORT_TMODEL)) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", FindQualifiers.CASE_SENSITIVE_SORT_TMODEL)); - } - if (findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.SORT_BY_NAME_ASC) || findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.SORT_BY_NAME_ASC_TMODEL)) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", FindQualifiers.SORT_BY_NAME_ASC)); - } - if (findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.SORT_BY_NAME_DESC) || findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.SORT_BY_NAME_DESC_TMODEL)) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", FindQualifiers.SORT_BY_NAME_DESC)); - } - } - } - - private void validateFindRelatedBusinessesFindQualifiers(org.uddi.api_v3.FindQualifiers findQualifiers) throws InvalidCombinationException { - if (findQualifiers == null) { - return; - } - for (int i = 0; i < findQualifiers.getFindQualifier().size(); i++) { - if (findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.AND_ALL_KEYS) || findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.AND_ALL_KEYS_TMODEL)) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", FindQualifiers.AND_ALL_KEYS)); - } - } - } - - private void validateFindQualifiers_AppoximateMatchAndCombinedCatbag(org.uddi.api_v3.FindQualifiers findQualifiers) throws InvalidCombinationException { - if (findQualifiers == null) { - return; - } - boolean containsAPPROXIMATE_MATCH = false; - boolean containsCOMBINE_CATEGORY_BAGS = false; - for (int i = 0; i < findQualifiers.getFindQualifier().size(); i++) { - if (findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.APPROXIMATE_MATCH) || findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.APPROXIMATE_MATCH_TMODEL)) { - containsAPPROXIMATE_MATCH = true; - } - if (findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.COMBINE_CATEGORY_BAGS) || findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.COMBINE_CATEGORY_BAGS_TMODEL)) { - containsCOMBINE_CATEGORY_BAGS = true; - } - } - if (containsAPPROXIMATE_MATCH && containsCOMBINE_CATEGORY_BAGS) { - throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", FindQualifiers.COMBINE_CATEGORY_BAGS + " & " + FindQualifiers.APPROXIMATE_MATCH_TMODEL)); - } - - } - - static Map supportedFindqualifiers = null; - private void ValidateSupportedFindQualifier(String fq) throws UnsupportedException { - if (supportedFindqualifiers==null || supportedFindqualifiers.isEmpty()) - InitFindQualifierMap(); - if (supportedFindqualifiers.get(fq.toLowerCase())==null) - throw new UnsupportedException(new ErrorMessage("errors.Unsupported.findQualifier", fq)); - } - - private void InitFindQualifierMap() { - supportedFindqualifiers = new HashMap(); - supportedFindqualifiers.put(FindQualifiers.AND_ALL_KEYS.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.AND_ALL_KEYS_TMODEL.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.APPROXIMATE_MATCH.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.APPROXIMATE_MATCH_TMODEL.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.BINARY_SORT.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.BINARY_SORT_TMODEL.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.BINDING_SUBSET.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.BINDING_SUBSET_TMODEL.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.CASE_INSENSITIVE_MATCH.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.CASE_INSENSITIVE_MATCH_TMODEL.toLowerCase(), true); - //these are NOT supported, see JUDDI-785 - //supportedFindqualifiers.put(FindQualifiers.CASE_INSENSITIVE_SORT.toLowerCase(), true); - //supportedFindqualifiers.put(FindQualifiers.CASE_INSENSITIVE_SORT_TMODEL.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.CASE_SENSITIVE_MATCH.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.CASE_SENSITIVE_MATCH_TMODEL.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.CASE_SENSITIVE_SORT.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.CASE_SENSITIVE_SORT_TMODEL.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.COMBINE_CATEGORY_BAGS.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.COMBINE_CATEGORY_BAGS_TMODEL.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.DIACRITIC_INSENSITIVE_MATCH.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.DIACRITIC_INSENSITIVE_MATCH_TMODEL.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.DIACRITIC_SENSITIVE_MATCH.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.DIACRITIC_SENSITIVE_MATCH_TMODEL.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.EXACT_MATCH.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.EXACT_MATCH_TMODEL.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.OR_ALL_KEYS.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.OR_ALL_KEYS_TMODEL.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.OR_LIKE_KEYS.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.OR_LIKE_KEYS_TMODEL.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.SERVICE_SUBSET.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.SERVICE_SUBSET_TMODEL.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.SIGNATURE_PRESENT.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.SIGNATURE_PRESENT_TMODEL.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.SORT_BY_DATE_ASC.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.SORT_BY_DATE_ASC_TMODEL.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.SORT_BY_DATE_DESC.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.SORT_BY_DATE_DESC_TMODEL.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.SORT_BY_NAME_ASC.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.SORT_BY_NAME_ASC_TMODEL.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.SORT_BY_NAME_DESC.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.SORT_BY_NAME_DESC_TMODEL.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.SUPPRESS_PROJECTED_SERVICES.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.SUPPRESS_PROJECTED_SERVICES_TMODEL.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.UTS_10.toLowerCase(), true); - supportedFindqualifiers.put(FindQualifiers.UTS_10_TMODEL.toLowerCase(), true); - - } - - private void validateServiceExists(String serviceKey) throws InvalidKeyPassedException { - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - org.apache.juddi.model.BusinessService modelBusinessService = null; - try { - modelBusinessService = em.find(org.apache.juddi.model.BusinessService.class, serviceKey); - } catch (ClassCastException e) { - } - if (modelBusinessService == null) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ServiceNotFound", serviceKey)); - } - - tx.commit(); - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.validation; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Hashtable; +import java.util.Map; +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import org.apache.juddi.api.impl.InquiryHelper; +import org.apache.juddi.api.util.InquiryQuery; +import org.apache.juddi.api.util.QueryStatus; +import org.apache.juddi.config.PersistenceManager; +import org.apache.juddi.mapping.MappingModelToApi; + +import org.uddi.api_v3.GetBusinessDetail; +import org.uddi.api_v3.GetOperationalInfo; +import org.uddi.api_v3.GetServiceDetail; +import org.uddi.api_v3.GetBindingDetail; +import org.uddi.api_v3.GetTModelDetail; +import org.uddi.api_v3.FindBusiness; +import org.uddi.api_v3.FindService; +import org.uddi.api_v3.FindBinding; +import org.uddi.api_v3.FindTModel; +import org.uddi.api_v3.FindRelatedBusinesses; +import org.uddi.api_v3.KeyedReference; +import org.uddi.api_v3.KeyedReferenceGroup; +import org.uddi.api_v3.Name; +import org.uddi.api_v3.TModelBag; + +import org.uddi.v3_service.DispositionReportFaultMessage; + +import org.apache.juddi.model.UddiEntityPublisher; +import org.apache.juddi.query.BusinessServiceQuery; +import org.apache.juddi.query.util.DynamicQuery; +import org.apache.juddi.query.util.FindQualifiers; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.FatalErrorException; +import org.apache.juddi.v3.error.InvalidCombinationException; +import org.apache.juddi.v3.error.InvalidKeyPassedException; +import org.apache.juddi.v3.error.UnsupportedException; +import org.apache.juddi.v3.error.ValueNotAllowedException; +import org.uddi.api_v3.BindingDetail; +import org.uddi.api_v3.ServiceDetail; + +/** + * @author Jeff Faath + * @author Tom Cunningham + * @author Alex O'Ree + */ +public class ValidateInquiry extends ValidateUDDIApi { + + public ValidateInquiry(UddiEntityPublisher publisher) { + super(publisher); + } + + public void validateGetBusinessDetail(GetBusinessDetail body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + // No null or empty list + List entityKeyList = body.getBusinessKey(); + if (entityKeyList == null || entityKeyList.size() == 0) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); + } + + HashSet dupCheck = new HashSet(); + int i = 0; + for (String entityKey : entityKeyList) { + + // Per section 4.4: keys must be case-folded + entityKey = entityKey.toLowerCase(); + entityKeyList.set(i, entityKey); + + boolean inserted = dupCheck.add(entityKey); + if (!inserted) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); + } + + i++; + } + } + + public void validateGetServiceDetail(GetServiceDetail body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + // No null or empty list + List entityKeyList = body.getServiceKey(); + if (entityKeyList == null || entityKeyList.size() == 0) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); + } + + HashSet dupCheck = new HashSet(); + int i = 0; + for (String entityKey : entityKeyList) { + + // Per section 4.4: keys must be case-folded + entityKey = entityKey.toLowerCase(); + entityKeyList.set(i, entityKey); + + boolean inserted = dupCheck.add(entityKey); + if (!inserted) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); + } + + i++; + } + } + + public void validateGetBindingDetail(GetBindingDetail body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + // No null or empty list + List entityKeyList = body.getBindingKey(); + if (entityKeyList == null || entityKeyList.size() == 0) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); + } + + HashSet dupCheck = new HashSet(); + int i = 0; + for (String entityKey : entityKeyList) { + + // Per section 4.4: keys must be case-folded + entityKey = entityKey.toLowerCase(); + entityKeyList.set(i, entityKey); + + boolean inserted = dupCheck.add(entityKey); + if (!inserted) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); + } + + i++; + } + } + + public void validateGetTModelDetail(GetTModelDetail body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + // No null or empty list + List entityKeyList = body.getTModelKey(); + if (entityKeyList == null || entityKeyList.size() == 0) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); + } + + HashSet dupCheck = new HashSet(); + int i = 0; + for (String entityKey : entityKeyList) { + + // Per section 4.4: keys must be case-folded + entityKey = entityKey.toLowerCase(); + entityKeyList.set(i, entityKey); + + boolean inserted = dupCheck.add(entityKey); + if (!inserted) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); + } + + i++; + } + } + + public void validateGetOperationalInfo(GetOperationalInfo body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + // No null or empty list + List entityKeyList = body.getEntityKey(); + if (entityKeyList == null || entityKeyList.size() == 0) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); + } + + HashSet dupCheck = new HashSet(); + int i = 0; + for (String entityKey : entityKeyList) { + + // Per section 4.4: keys must be case-folded + entityKey = entityKey.toLowerCase(); + entityKeyList.set(i, entityKey); + + boolean inserted = dupCheck.add(entityKey); + if (!inserted) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); + } + + i++; + } + } + + public void validateFindBusiness(FindBusiness body) throws DispositionReportFaultMessage { + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + if (body.getCategoryBag() == null && body.getFindTModel() == null && body.getTModelBag() == null && body.getName().size() == 0 + && body.getIdentifierBag() == null && body.getDiscoveryURLs() == null && body.getFindRelatedBusinesses() == null) { + throw new FatalErrorException(new ErrorMessage("errors.findbusiness.NoInput")); + } + + validateNames(body.getName()); + validateFindQualifiers(body.getFindQualifiers()); + validateTModelBag(body.getTModelBag()); + validateFindTModel(body.getFindTModel(), true); + validateFindRelatedBusinesses(body.getFindRelatedBusinesses(), true); + validateDiscoveryUrls(body.getDiscoveryURLs()); + validateIdentifierBag(body.getIdentifierBag()); + validateCategoryBag(body.getCategoryBag()); + + } + + public void validateFindService(FindService body) throws DispositionReportFaultMessage { + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + if (body.getCategoryBag() == null && body.getFindTModel() == null + && (body.getTModelBag() == null || body.getTModelBag().getTModelKey().size() == 0) + && body.getName().size() == 0 && body.getBusinessKey() == null) { + throw new FatalErrorException(new ErrorMessage("errors.findservice.NoInput")); + } + + validateNames(body.getName()); + validateFindQualifiers(body.getFindQualifiers()); + validateTModelBag(body.getTModelBag()); + validateFindTModel(body.getFindTModel(), true); + validateCategoryBag(body.getCategoryBag()); + + } + + public void validateFindBinding(FindBinding body) throws DispositionReportFaultMessage { + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + if (body.getServiceKey()!=null && body.getServiceKey().length() > 0) { + validateServiceExists(body.getServiceKey()); + } + if ((body.getServiceKey()==null || body.getServiceKey().length()==0) && body.getCategoryBag() == null && body.getFindTModel() == null && body.getTModelBag() == null) { + throw new FatalErrorException(new ErrorMessage("errors.findbinding.NoInput")); + } + + validateFindQualifiers(body.getFindQualifiers()); + validateTModelBag(body.getTModelBag()); + validateFindTModel(body.getFindTModel(), true); + validateCategoryBag(body.getCategoryBag()); + validateFindingBindingFQ(body.getFindQualifiers()); + validateFindQualifiers_AppoximateMatchAndCombinedCatbag(body.getFindQualifiers()); + + } + + public void validateFindTModel(FindTModel body, boolean nullAllowed) throws DispositionReportFaultMessage { + if (body == null) { + // When FindTModel objects are embedded in other find calls, null is allowed. + if (nullAllowed) { + return; + } else { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + } + + if (body.getCategoryBag() == null && body.getIdentifierBag() == null && body.getName() == null) { + throw new FatalErrorException(new ErrorMessage("errors.findtmodel.NoInput")); + } + + validateFindQualifiers(body.getFindQualifiers()); + validateIdentifierBag(body.getIdentifierBag()); + validateCategoryBag(body.getCategoryBag()); + validateFindQualifiers_AppoximateMatchAndCombinedCatbag(body.getFindQualifiers()); + } + + public void validateFindRelatedBusinesses(FindRelatedBusinesses body, boolean nullAllowed) throws DispositionReportFaultMessage { + if (body == null) { + // When FindRelatedBusinesses objects are embedded in other find calls, null is allowed. + if (nullAllowed) { + return; + } else { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + } + + if ((body.getBusinessKey() == null || body.getBusinessKey().length() == 0) + && (body.getFromKey() == null || body.getFromKey().length() == 0) + && (body.getToKey() == null || body.getToKey().length() == 0)) { + throw new FatalErrorException(new ErrorMessage("errors.findrelatedbusiness.NoInput")); + } + + boolean businessKeyExists = false; + boolean fromKeyExists = false; + if (body.getBusinessKey() != null && body.getBusinessKey().length() > 0) { + businessKeyExists = true; + + // Per section 4.4: keys must be case-folded + body.setBusinessKey(body.getBusinessKey().toLowerCase()); + } + if (body.getFromKey() != null && body.getFromKey().length() > 0) { + fromKeyExists = true; + if (businessKeyExists) { + throw new FatalErrorException(new ErrorMessage("errors.findrelatedbusiness.MultipleInput")); + } + + // Per section 4.4: keys must be case-folded + body.setFromKey(body.getFromKey().toLowerCase()); + } + if (body.getToKey() != null && body.getToKey().length() > 0) { + if (businessKeyExists || fromKeyExists) { + throw new FatalErrorException(new ErrorMessage("errors.findrelatedbusiness.MultipleInput")); + } + + // Per section 4.4: keys must be case-folded + body.setToKey(body.getToKey().toLowerCase()); + } + + KeyedReference keyedRef = body.getKeyedReference(); + if (keyedRef != null) { + if (keyedRef.getTModelKey() == null || keyedRef.getTModelKey().length() == 0 + || keyedRef.getKeyName() == null || keyedRef.getKeyName().length() == 0 + || keyedRef.getKeyValue() == null || keyedRef.getKeyValue().length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.findrelatedbusiness.BlankKeyedRef")); + } + + validateKeyedReference(keyedRef); + } + validateFindQualifiers(body.getFindQualifiers()); + validateFindRelatedBusinessesFindQualifiers(body.getFindQualifiers()); + validateFindQualifiers_AppoximateMatchAndCombinedCatbag(body.getFindQualifiers()); + } + + public void validateNames(List names) throws DispositionReportFaultMessage { + if (names != null) { + for (Name n : names) { + if (n.getValue() == null || n.getValue().length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.names.NoValue")); + } + ValidatePublish.validateLang(n.getLang()); + } + } + } + + public void validateTModelBag(TModelBag tmodelBag) throws DispositionReportFaultMessage { + // tmodelBag is optional + if (tmodelBag == null) { + return; + } + + if (tmodelBag.getTModelKey() == null || tmodelBag.getTModelKey().size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.tmodelbag.NoInput")); + } + + List keyList = tmodelBag.getTModelKey(); + int i = 0; + for (String key : keyList) { + // Per section 4.4: keys must be case-folded + key = key.toLowerCase(); + keyList.set(i, key); + i++; + } + + } + + public void validateDiscoveryUrls(org.uddi.api_v3.DiscoveryURLs discUrls) throws DispositionReportFaultMessage { + // Discovery Urls is optional + if (discUrls == null) { + return; + } + + // If discUrls does exist, it must have at least one element + List discUrlList = discUrls.getDiscoveryURL(); + if (discUrlList == null || discUrlList.size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.discurls.NoInput")); + } + } + + public void validateCategoryBag(org.uddi.api_v3.CategoryBag categories) throws DispositionReportFaultMessage { + + // Category bag is optional + if (categories == null) { + return; + } + + // If category bag does exist, it must have at least one element + List elems = categories.getKeyedReference(); + List krgs = categories.getKeyedReferenceGroup(); + if ((elems == null || elems.size() == 0) && (krgs == null || krgs.size() == 0)) { + throw new ValueNotAllowedException(new ErrorMessage("errors.categorybag.NoInput")); + } + + for (KeyedReference elem : elems) { + validateKeyedReference(elem); + } + for (KeyedReferenceGroup elem : krgs) { + validateKeyedReferenceGroup(elem); + } + } + + public void validateIdentifierBag(org.uddi.api_v3.IdentifierBag identifiers) throws DispositionReportFaultMessage { + + // Identifier bag is optional + if (identifiers == null) { + return; + } + + // If category bag does exist, it must have at least one element + List keyedRefList = identifiers.getKeyedReference(); + if (keyedRefList == null || keyedRefList.size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.identifierbag.NoInput")); + } + + for (org.uddi.api_v3.KeyedReference keyedRef : keyedRefList) { + validateKeyedReference(keyedRef); + } + } + + public void validateKeyedReferenceGroup(KeyedReferenceGroup krg) throws DispositionReportFaultMessage { + // Keyed reference groups must contain a tModelKey + if (krg.getTModelKey() == null || krg.getTModelKey().length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.keyedreference.NoTModelKey")); + } + + // Per section 4.4: keys must be case-folded + krg.setTModelKey(krg.getTModelKey().toLowerCase()); + + List keyedRefs = krg.getKeyedReference(); + // Should being empty raise an error? + if (keyedRefs != null && keyedRefs.size() > 0) { + for (KeyedReference keyedRef : keyedRefs) { + validateKeyedReference(keyedRef); + } + } + } + + public void validateKeyedReference(KeyedReference kr) throws DispositionReportFaultMessage { + if (kr == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.keyedreference.NullInput")); + } + + // Keyed references must contain a tModelKey and keyValue + if (kr.getTModelKey() == null || kr.getTModelKey().length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.keyedreference.NoTModelKey")); + } + + // Per section 4.4: keys must be case-folded + kr.setTModelKey(kr.getTModelKey().toLowerCase()); + + if (kr.getKeyValue() == null || kr.getKeyValue().length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.keyedreference.NoKeyValue")); + } + } + + private void validateFindQualifiers(org.uddi.api_v3.FindQualifiers findQualifiers) throws DispositionReportFaultMessage { + if (findQualifiers == null) { + return; + } + + List fqList = findQualifiers.getFindQualifier(); + if (fqList == null || fqList.size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.findqualifiers.NoInput")); + } + + Hashtable fqTable = new Hashtable(); + for (String fq : fqList) { + String result = fqTable.put(fq.toUpperCase(), fq.toUpperCase()); + if (result != null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.findqualifiers.DuplicateValue", result)); + } + + ValidateSupportedFindQualifier(fq); + + // Invalid combo: andAllKeys, orAllKeys, and orLikeKeys + if (fq.equalsIgnoreCase(FindQualifiers.AND_ALL_KEYS) || fq.equalsIgnoreCase(FindQualifiers.AND_ALL_KEYS_TMODEL)) { + if (fqTable.get(FindQualifiers.OR_ALL_KEYS.toUpperCase()) != null || fqTable.get(FindQualifiers.OR_ALL_KEYS_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.OR_ALL_KEYS)); + } + + if (fqTable.get(FindQualifiers.OR_LIKE_KEYS.toUpperCase()) != null || fqTable.get(FindQualifiers.OR_LIKE_KEYS_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.OR_LIKE_KEYS)); + } + } else if (fq.equalsIgnoreCase(FindQualifiers.OR_ALL_KEYS) || fq.equalsIgnoreCase(FindQualifiers.OR_ALL_KEYS_TMODEL)) { + if (fqTable.get(FindQualifiers.AND_ALL_KEYS.toUpperCase()) != null || fqTable.get(FindQualifiers.AND_ALL_KEYS_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.AND_ALL_KEYS)); + } + + if (fqTable.get(FindQualifiers.OR_LIKE_KEYS.toUpperCase()) != null || fqTable.get(FindQualifiers.OR_LIKE_KEYS_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.OR_LIKE_KEYS)); + } + } else if (fq.equalsIgnoreCase(FindQualifiers.OR_LIKE_KEYS) || fq.equalsIgnoreCase(FindQualifiers.OR_LIKE_KEYS_TMODEL)) { + if (fqTable.get(FindQualifiers.AND_ALL_KEYS.toUpperCase()) != null || fqTable.get(FindQualifiers.AND_ALL_KEYS_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.AND_ALL_KEYS)); + } + + if (fqTable.get(FindQualifiers.OR_ALL_KEYS.toUpperCase()) != null || fqTable.get(FindQualifiers.OR_ALL_KEYS_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.OR_ALL_KEYS)); + } + } + + // Invalid combo: sortByNameAsc and sortByNameDesc + if (fq.equalsIgnoreCase(FindQualifiers.SORT_BY_NAME_ASC) || fq.equalsIgnoreCase(FindQualifiers.SORT_BY_NAME_ASC_TMODEL)) { + if (fqTable.get(FindQualifiers.SORT_BY_NAME_DESC.toUpperCase()) != null || fqTable.get(FindQualifiers.SORT_BY_NAME_DESC_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.SORT_BY_NAME_DESC)); + } + } else if (fq.equalsIgnoreCase(FindQualifiers.SORT_BY_NAME_DESC) || fq.equalsIgnoreCase(FindQualifiers.SORT_BY_NAME_DESC_TMODEL)) { + if (fqTable.get(FindQualifiers.SORT_BY_NAME_ASC.toUpperCase()) != null || fqTable.get(FindQualifiers.SORT_BY_NAME_ASC_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.SORT_BY_NAME_ASC)); + } + } + + // Invalid combo: sortByDateAsc and sortByDateDesc + if (fq.equalsIgnoreCase(FindQualifiers.SORT_BY_DATE_ASC) || fq.equalsIgnoreCase(FindQualifiers.SORT_BY_DATE_ASC_TMODEL)) { + if (fqTable.get(FindQualifiers.SORT_BY_DATE_DESC.toUpperCase()) != null || fqTable.get(FindQualifiers.SORT_BY_DATE_DESC_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.SORT_BY_DATE_DESC)); + } + } else if (fq.equalsIgnoreCase(FindQualifiers.SORT_BY_DATE_DESC) || fq.equalsIgnoreCase(FindQualifiers.SORT_BY_DATE_DESC_TMODEL)) { + if (fqTable.get(FindQualifiers.SORT_BY_DATE_ASC.toUpperCase()) != null || fqTable.get(FindQualifiers.SORT_BY_DATE_ASC_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.SORT_BY_DATE_ASC)); + } + } + + // Invalid combo: combineCategoryBags, serviceSubset and bindingSubset + if (fq.equalsIgnoreCase(FindQualifiers.COMBINE_CATEGORY_BAGS) || fq.equalsIgnoreCase(FindQualifiers.COMBINE_CATEGORY_BAGS_TMODEL)) { + if (fqTable.get(FindQualifiers.SERVICE_SUBSET.toUpperCase()) != null || fqTable.get(FindQualifiers.SERVICE_SUBSET_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.SERVICE_SUBSET)); + } + + if (fqTable.get(FindQualifiers.BINDING_SUBSET.toUpperCase()) != null || fqTable.get(FindQualifiers.BINDING_SUBSET_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.BINDING_SUBSET)); + } + } else if (fq.equalsIgnoreCase(FindQualifiers.SERVICE_SUBSET) || fq.equalsIgnoreCase(FindQualifiers.SERVICE_SUBSET_TMODEL)) { + if (fqTable.get(FindQualifiers.COMBINE_CATEGORY_BAGS.toUpperCase()) != null || fqTable.get(FindQualifiers.COMBINE_CATEGORY_BAGS_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.COMBINE_CATEGORY_BAGS)); + } + + if (fqTable.get(FindQualifiers.BINDING_SUBSET.toUpperCase()) != null || fqTable.get(FindQualifiers.BINDING_SUBSET_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.BINDING_SUBSET)); + } + } else if (fq.equalsIgnoreCase(FindQualifiers.BINDING_SUBSET) || fq.equalsIgnoreCase(FindQualifiers.BINDING_SUBSET_TMODEL)) { + if (fqTable.get(FindQualifiers.SERVICE_SUBSET.toUpperCase()) != null || fqTable.get(FindQualifiers.SERVICE_SUBSET_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.SERVICE_SUBSET)); + } + + if (fqTable.get(FindQualifiers.COMBINE_CATEGORY_BAGS.toUpperCase()) != null || fqTable.get(FindQualifiers.COMBINE_CATEGORY_BAGS_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.COMBINE_CATEGORY_BAGS)); + } + } + + // Invalid combo: exactMatch and approximateMatch + if (fq.equalsIgnoreCase(FindQualifiers.EXACT_MATCH) || fq.equalsIgnoreCase(FindQualifiers.EXACT_MATCH_TMODEL)) { + if (fqTable.get(FindQualifiers.APPROXIMATE_MATCH.toUpperCase()) != null || fqTable.get(FindQualifiers.APPROXIMATE_MATCH_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.APPROXIMATE_MATCH)); + } + } else if (fq.equalsIgnoreCase(FindQualifiers.APPROXIMATE_MATCH) || fq.equalsIgnoreCase(FindQualifiers.APPROXIMATE_MATCH_TMODEL)) { + if (fqTable.get(FindQualifiers.EXACT_MATCH.toUpperCase()) != null || fqTable.get(FindQualifiers.EXACT_MATCH_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.EXACT_MATCH)); + } + } + + // Invalid combo: exactMatch and caseInsensitiveMatch + if (fq.equalsIgnoreCase(FindQualifiers.EXACT_MATCH) || fq.equalsIgnoreCase(FindQualifiers.EXACT_MATCH_TMODEL)) { + if (fqTable.get(FindQualifiers.CASE_INSENSITIVE_MATCH.toUpperCase()) != null || fqTable.get(FindQualifiers.CASE_INSENSITIVE_MATCH_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.CASE_INSENSITIVE_MATCH)); + } + } else if (fq.equalsIgnoreCase(FindQualifiers.CASE_INSENSITIVE_MATCH) || fq.equalsIgnoreCase(FindQualifiers.CASE_INSENSITIVE_MATCH_TMODEL)) { + if (fqTable.get(FindQualifiers.EXACT_MATCH.toUpperCase()) != null || fqTable.get(FindQualifiers.EXACT_MATCH_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.EXACT_MATCH)); + } + } + + // Invalid combo: binarySort and UTS-10 + if (fq.equalsIgnoreCase(FindQualifiers.BINARY_SORT) || fq.equalsIgnoreCase(FindQualifiers.BINARY_SORT_TMODEL)) { + if (fqTable.get(FindQualifiers.UTS_10.toUpperCase()) != null || fqTable.get(FindQualifiers.UTS_10_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.UTS_10)); + } + } else if (fq.equalsIgnoreCase(FindQualifiers.UTS_10) || fq.equalsIgnoreCase(FindQualifiers.UTS_10_TMODEL)) { + if (fqTable.get(FindQualifiers.BINARY_SORT.toUpperCase()) != null || fqTable.get(FindQualifiers.BINARY_SORT_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.BINARY_SORT)); + } + } + + // Invalid combo: diacriticSensitiveMatch and diacriticInsensitiveMatch + if (fq.equalsIgnoreCase(FindQualifiers.DIACRITIC_SENSITIVE_MATCH) || fq.equalsIgnoreCase(FindQualifiers.DIACRITIC_SENSITIVE_MATCH_TMODEL)) { + if (fqTable.get(FindQualifiers.DIACRITIC_INSENSITIVE_MATCH.toUpperCase()) != null || fqTable.get(FindQualifiers.DIACRITIC_INSENSITIVE_MATCH_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.DIACRITIC_INSENSITIVE_MATCH)); + } + } else if (fq.equalsIgnoreCase(FindQualifiers.DIACRITIC_INSENSITIVE_MATCH) || fq.equalsIgnoreCase(FindQualifiers.DIACRITIC_INSENSITIVE_MATCH_TMODEL)) { + if (fqTable.get(FindQualifiers.DIACRITIC_SENSITIVE_MATCH.toUpperCase()) != null || fqTable.get(FindQualifiers.DIACRITIC_SENSITIVE_MATCH_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.DIACRITIC_SENSITIVE_MATCH)); + } + } + + // Invalid combo: exactMatch and diacriticInsensitiveMatch + if (fq.equalsIgnoreCase(FindQualifiers.EXACT_MATCH) || fq.equalsIgnoreCase(FindQualifiers.EXACT_MATCH_TMODEL)) { + if (fqTable.get(FindQualifiers.DIACRITIC_INSENSITIVE_MATCH.toUpperCase()) != null || fqTable.get(FindQualifiers.DIACRITIC_INSENSITIVE_MATCH_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.DIACRITIC_INSENSITIVE_MATCH)); + } + } else if (fq.equalsIgnoreCase(FindQualifiers.DIACRITIC_INSENSITIVE_MATCH) || fq.equalsIgnoreCase(FindQualifiers.DIACRITIC_INSENSITIVE_MATCH_TMODEL)) { + if (fqTable.get(FindQualifiers.EXACT_MATCH.toUpperCase()) != null || fqTable.get(FindQualifiers.EXACT_MATCH_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.EXACT_MATCH)); + } + } + + // Invalid combo: caseSensitiveSort and caseInsensitiveSort + if (fq.equalsIgnoreCase(FindQualifiers.CASE_SENSITIVE_SORT) || fq.equalsIgnoreCase(FindQualifiers.CASE_SENSITIVE_SORT_TMODEL)) { + if (fqTable.get(FindQualifiers.CASE_INSENSITIVE_SORT.toUpperCase()) != null || fqTable.get(FindQualifiers.CASE_INSENSITIVE_SORT_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.CASE_INSENSITIVE_SORT)); + } + } else if (fq.equalsIgnoreCase(FindQualifiers.CASE_INSENSITIVE_SORT) || fq.equalsIgnoreCase(FindQualifiers.CASE_INSENSITIVE_SORT_TMODEL)) { + if (fqTable.get(FindQualifiers.CASE_SENSITIVE_SORT.toUpperCase()) != null || fqTable.get(FindQualifiers.CASE_SENSITIVE_SORT_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.CASE_SENSITIVE_SORT)); + } + } + + // Invalid combo: caseSensitiveMatch and caseInsensitiveMatch + if (fq.equalsIgnoreCase(FindQualifiers.CASE_SENSITIVE_MATCH) || fq.equalsIgnoreCase(FindQualifiers.CASE_SENSITIVE_MATCH_TMODEL)) { + if (fqTable.get(FindQualifiers.CASE_INSENSITIVE_MATCH.toUpperCase()) != null || fqTable.get(FindQualifiers.CASE_INSENSITIVE_MATCH_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.CASE_INSENSITIVE_MATCH)); + } + } else if (fq.equalsIgnoreCase(FindQualifiers.CASE_INSENSITIVE_MATCH) || fq.equalsIgnoreCase(FindQualifiers.CASE_INSENSITIVE_MATCH_TMODEL)) { + if (fqTable.get(FindQualifiers.CASE_SENSITIVE_MATCH.toUpperCase()) != null || fqTable.get(FindQualifiers.CASE_SENSITIVE_MATCH_TMODEL.toUpperCase()) != null) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", fq + " & " + FindQualifiers.CASE_SENSITIVE_MATCH)); + } + } + + } + } + + private void validateFindingBindingFQ(org.uddi.api_v3.FindQualifiers findQualifiers) throws InvalidCombinationException { + if (findQualifiers == null) { + return; + } + for (int i = 0; i < findQualifiers.getFindQualifier().size(); i++) { + if (findQualifiers.getFindQualifier().get(i).equals(FindQualifiers.BINARY_SORT) || findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.BINARY_SORT_TMODEL)) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", FindQualifiers.BINARY_SORT)); + } + if (findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.CASE_INSENSITIVE_MATCH) || findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.CASE_INSENSITIVE_MATCH_TMODEL)) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", FindQualifiers.CASE_INSENSITIVE_MATCH)); + } + if (findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.CASE_SENSITIVE_MATCH) || findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.CASE_SENSITIVE_MATCH_TMODEL)) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", FindQualifiers.CASE_SENSITIVE_MATCH)); + } + if (findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.CASE_INSENSITIVE_SORT) || findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.CASE_INSENSITIVE_SORT_TMODEL)) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", FindQualifiers.CASE_INSENSITIVE_SORT)); + } + if (findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.CASE_SENSITIVE_SORT) || findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.CASE_SENSITIVE_SORT_TMODEL)) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", FindQualifiers.CASE_SENSITIVE_SORT_TMODEL)); + } + if (findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.SORT_BY_NAME_ASC) || findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.SORT_BY_NAME_ASC_TMODEL)) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", FindQualifiers.SORT_BY_NAME_ASC)); + } + if (findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.SORT_BY_NAME_DESC) || findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.SORT_BY_NAME_DESC_TMODEL)) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", FindQualifiers.SORT_BY_NAME_DESC)); + } + } + } + + private void validateFindRelatedBusinessesFindQualifiers(org.uddi.api_v3.FindQualifiers findQualifiers) throws InvalidCombinationException { + if (findQualifiers == null) { + return; + } + for (int i = 0; i < findQualifiers.getFindQualifier().size(); i++) { + if (findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.AND_ALL_KEYS) || findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.AND_ALL_KEYS_TMODEL)) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", FindQualifiers.AND_ALL_KEYS)); + } + } + } + + private void validateFindQualifiers_AppoximateMatchAndCombinedCatbag(org.uddi.api_v3.FindQualifiers findQualifiers) throws InvalidCombinationException { + if (findQualifiers == null) { + return; + } + boolean containsAPPROXIMATE_MATCH = false; + boolean containsCOMBINE_CATEGORY_BAGS = false; + for (int i = 0; i < findQualifiers.getFindQualifier().size(); i++) { + if (findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.APPROXIMATE_MATCH) || findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.APPROXIMATE_MATCH_TMODEL)) { + containsAPPROXIMATE_MATCH = true; + } + if (findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.COMBINE_CATEGORY_BAGS) || findQualifiers.getFindQualifier().get(i).equalsIgnoreCase(FindQualifiers.COMBINE_CATEGORY_BAGS_TMODEL)) { + containsCOMBINE_CATEGORY_BAGS = true; + } + } + if (containsAPPROXIMATE_MATCH && containsCOMBINE_CATEGORY_BAGS) { + throw new InvalidCombinationException(new ErrorMessage("errors.findqualifiers.InvalidCombo", FindQualifiers.COMBINE_CATEGORY_BAGS + " & " + FindQualifiers.APPROXIMATE_MATCH_TMODEL)); + } + + } + + static Map supportedFindqualifiers = null; + private void ValidateSupportedFindQualifier(String fq) throws UnsupportedException { + if (supportedFindqualifiers==null || supportedFindqualifiers.isEmpty()) + InitFindQualifierMap(); + if (supportedFindqualifiers.get(fq.toLowerCase())==null) + throw new UnsupportedException(new ErrorMessage("errors.Unsupported.findQualifier", fq)); + } + + private void InitFindQualifierMap() { + supportedFindqualifiers = new HashMap(); + supportedFindqualifiers.put(FindQualifiers.AND_ALL_KEYS.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.AND_ALL_KEYS_TMODEL.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.APPROXIMATE_MATCH.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.APPROXIMATE_MATCH_TMODEL.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.BINARY_SORT.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.BINARY_SORT_TMODEL.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.BINDING_SUBSET.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.BINDING_SUBSET_TMODEL.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.CASE_INSENSITIVE_MATCH.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.CASE_INSENSITIVE_MATCH_TMODEL.toLowerCase(), true); + //these are NOT supported, see JUDDI-785 + //supportedFindqualifiers.put(FindQualifiers.CASE_INSENSITIVE_SORT.toLowerCase(), true); + //supportedFindqualifiers.put(FindQualifiers.CASE_INSENSITIVE_SORT_TMODEL.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.CASE_SENSITIVE_MATCH.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.CASE_SENSITIVE_MATCH_TMODEL.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.CASE_SENSITIVE_SORT.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.CASE_SENSITIVE_SORT_TMODEL.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.COMBINE_CATEGORY_BAGS.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.COMBINE_CATEGORY_BAGS_TMODEL.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.DIACRITIC_INSENSITIVE_MATCH.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.DIACRITIC_INSENSITIVE_MATCH_TMODEL.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.DIACRITIC_SENSITIVE_MATCH.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.DIACRITIC_SENSITIVE_MATCH_TMODEL.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.EXACT_MATCH.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.EXACT_MATCH_TMODEL.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.OR_ALL_KEYS.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.OR_ALL_KEYS_TMODEL.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.OR_LIKE_KEYS.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.OR_LIKE_KEYS_TMODEL.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.SERVICE_SUBSET.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.SERVICE_SUBSET_TMODEL.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.SIGNATURE_PRESENT.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.SIGNATURE_PRESENT_TMODEL.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.SORT_BY_DATE_ASC.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.SORT_BY_DATE_ASC_TMODEL.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.SORT_BY_DATE_DESC.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.SORT_BY_DATE_DESC_TMODEL.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.SORT_BY_NAME_ASC.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.SORT_BY_NAME_ASC_TMODEL.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.SORT_BY_NAME_DESC.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.SORT_BY_NAME_DESC_TMODEL.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.SUPPRESS_PROJECTED_SERVICES.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.SUPPRESS_PROJECTED_SERVICES_TMODEL.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.UTS_10.toLowerCase(), true); + supportedFindqualifiers.put(FindQualifiers.UTS_10_TMODEL.toLowerCase(), true); + + } + + private void validateServiceExists(String serviceKey) throws InvalidKeyPassedException { + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + org.apache.juddi.model.BusinessService modelBusinessService = null; + try { + modelBusinessService = em.find(org.apache.juddi.model.BusinessService.class, serviceKey); + } catch (ClassCastException e) { + } + if (modelBusinessService == null) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ServiceNotFound", serviceKey)); + } + + tx.commit(); + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateNode.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateNode.java similarity index 98% rename from juddi-core/src/main/java/org/apache/juddi/validation/ValidateNode.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateNode.java index 1f6a203a9..d494344bd 100644 --- a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateNode.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateNode.java @@ -1,123 +1,123 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.validation; - -import java.util.List; -import java.util.logging.Logger; - -import javax.persistence.EntityManager; - -import org.apache.juddi.api_v3.Node; -import org.apache.juddi.model.UddiEntityPublisher; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.FatalErrorException; -import org.apache.juddi.v3.error.ValueNotAllowedException; -import org.uddi.v3_service.DispositionReportFaultMessage; - -/** - * @author Kurt T Stam - * @author Alex O'Ree - */ -public class ValidateNode extends ValidateUDDIApi { - - public ValidateNode(UddiEntityPublisher publisher) { - super(publisher); - } - private static final Logger logger = Logger.getLogger(ValidateNode.class.getCanonicalName()); - /*------------------------------------------------------------------- - validateSaveNode functions are specific to jUDDI. - --------------------------------------------------------------------*/ - - public void validateSaveNode(EntityManager em, org.apache.juddi.api_v3.SaveNode body) throws DispositionReportFaultMessage { - - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - // No null or empty list - List nodes = body.getNode(); - if (nodes == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.saveNodes.NoInput")); - } - - for (Node clerk : body.getNode()) { - validateNode(clerk); - } - - } - - public void validateNode(org.apache.juddi.api_v3.Node node) throws DispositionReportFaultMessage { - - // No null input - if (node == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.node.NullInput")); - } - - String name = node.getName(); - if (name == null || name.length() == 0 || name.length()>255 || node.getClientName()==null|| node.getClientName().length() > 255) { - throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoName")); - } - if (node.getDescription() == null || node.getDescription().length() == 0 || node.getDescription().length() > 255) { - throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoDescription")); - } - if (node.getClientName() == null || node.getClientName().length() == 0 || node.getClientName().length() > 255) { - throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoClientName")); - } - if (node.getCustodyTransferUrl() == null || node.getCustodyTransferUrl().length() == 0 || node.getClientName().length() > 255) { - throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoNCT")); - } - if (node.getInquiryUrl() == null || node.getInquiryUrl().length() == 0 || node.getInquiryUrl().length() > 255) { - throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoIN")); - } - if (node.getPublishUrl() == null || node.getPublishUrl().length() == 0 || node.getPublishUrl().length() > 255) { - throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoPUB")); - } - if (node.getSubscriptionListenerUrl() == null || node.getSubscriptionListenerUrl().length() == 0 || node.getSubscriptionListenerUrl().length() > 255) { - // throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoSUBL")); - } - if (node.getReplicationUrl() == null || node.getReplicationUrl().length() == 0 || node.getReplicationUrl().length() > 255) { - //throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoSUBL")); - //logger.log(Level.WARNING, "No replication url on save node request!"); - } - if (node.getSubscriptionUrl() == null || node.getSubscriptionUrl().length() == 0 || node.getSubscriptionUrl().length() > 255) { - throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoSUB")); - } - if (node.getSecurityUrl()== null || node.getSecurityUrl().length() == 0 || node.getSecurityUrl().length() > 255) { - throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoSec")); - } - if (node.getProxyTransport() == null || node.getProxyTransport().length() == 0 || node.getProxyTransport().length() > 255) { - throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoProxy")); - } else { - try { - //validate that the class exists and that it is of type - //org.apache.juddi.v3.client.transport.Transport - Class forName = Class.forName(node.getProxyTransport()); - Object j = forName.newInstance(); - if (!(j instanceof org.apache.juddi.v3.client.transport.Transport)) { - throw new ValueNotAllowedException(new ErrorMessage("errors.node.illegalProxyTransport")); - } - } catch (Exception ex) { - throw new ValueNotAllowedException(new ErrorMessage("errors.node.illegalProxyTransport")); - } - } - if (node.getProxyTransport().equalsIgnoreCase("org.apache.juddi.v3.client.transport.RMITransport")) { - throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoRMIData")); - - } - - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.validation; + +import java.util.List; +import java.util.logging.Logger; + +import javax.persistence.EntityManager; + +import org.apache.juddi.api_v3.Node; +import org.apache.juddi.model.UddiEntityPublisher; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.FatalErrorException; +import org.apache.juddi.v3.error.ValueNotAllowedException; +import org.uddi.v3_service.DispositionReportFaultMessage; + +/** + * @author Kurt T Stam + * @author Alex O'Ree + */ +public class ValidateNode extends ValidateUDDIApi { + + public ValidateNode(UddiEntityPublisher publisher) { + super(publisher); + } + private static final Logger logger = Logger.getLogger(ValidateNode.class.getCanonicalName()); + /*------------------------------------------------------------------- + validateSaveNode functions are specific to jUDDI. + --------------------------------------------------------------------*/ + + public void validateSaveNode(EntityManager em, org.apache.juddi.api_v3.SaveNode body) throws DispositionReportFaultMessage { + + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + // No null or empty list + List nodes = body.getNode(); + if (nodes == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.saveNodes.NoInput")); + } + + for (Node clerk : body.getNode()) { + validateNode(clerk); + } + + } + + public void validateNode(org.apache.juddi.api_v3.Node node) throws DispositionReportFaultMessage { + + // No null input + if (node == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.node.NullInput")); + } + + String name = node.getName(); + if (name == null || name.length() == 0 || name.length()>255 || node.getClientName()==null|| node.getClientName().length() > 255) { + throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoName")); + } + if (node.getDescription() == null || node.getDescription().length() == 0 || node.getDescription().length() > 255) { + throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoDescription")); + } + if (node.getClientName() == null || node.getClientName().length() == 0 || node.getClientName().length() > 255) { + throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoClientName")); + } + if (node.getCustodyTransferUrl() == null || node.getCustodyTransferUrl().length() == 0 || node.getClientName().length() > 255) { + throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoNCT")); + } + if (node.getInquiryUrl() == null || node.getInquiryUrl().length() == 0 || node.getInquiryUrl().length() > 255) { + throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoIN")); + } + if (node.getPublishUrl() == null || node.getPublishUrl().length() == 0 || node.getPublishUrl().length() > 255) { + throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoPUB")); + } + if (node.getSubscriptionListenerUrl() == null || node.getSubscriptionListenerUrl().length() == 0 || node.getSubscriptionListenerUrl().length() > 255) { + // throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoSUBL")); + } + if (node.getReplicationUrl() == null || node.getReplicationUrl().length() == 0 || node.getReplicationUrl().length() > 255) { + //throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoSUBL")); + //logger.log(Level.WARNING, "No replication url on save node request!"); + } + if (node.getSubscriptionUrl() == null || node.getSubscriptionUrl().length() == 0 || node.getSubscriptionUrl().length() > 255) { + throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoSUB")); + } + if (node.getSecurityUrl()== null || node.getSecurityUrl().length() == 0 || node.getSecurityUrl().length() > 255) { + throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoSec")); + } + if (node.getProxyTransport() == null || node.getProxyTransport().length() == 0 || node.getProxyTransport().length() > 255) { + throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoProxy")); + } else { + try { + //validate that the class exists and that it is of type + //org.apache.juddi.v3.client.transport.Transport + Class forName = Class.forName(node.getProxyTransport()); + Object j = forName.newInstance(); + if (!(j instanceof org.apache.juddi.v3.client.transport.Transport)) { + throw new ValueNotAllowedException(new ErrorMessage("errors.node.illegalProxyTransport")); + } + } catch (Exception ex) { + throw new ValueNotAllowedException(new ErrorMessage("errors.node.illegalProxyTransport")); + } + } + if (node.getProxyTransport().equalsIgnoreCase("org.apache.juddi.v3.client.transport.RMITransport")) { + throw new ValueNotAllowedException(new ErrorMessage("errors.node.NoRMIData")); + + } + + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/ValidatePublish.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidatePublish.java similarity index 98% rename from juddi-core/src/main/java/org/apache/juddi/validation/ValidatePublish.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidatePublish.java index c4ca76cdb..4d385cc44 100644 --- a/juddi-core/src/main/java/org/apache/juddi/validation/ValidatePublish.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidatePublish.java @@ -1,2551 +1,2551 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.validation; - -import java.net.MalformedURLException; -import java.net.URL; -import java.security.cert.CertificateException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.atomic.AtomicReference; - -import javax.persistence.EntityManager; -import javax.persistence.EntityTransaction; -import javax.xml.ws.Holder; - -import org.apache.commons.configuration.Configuration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.api_v3.AccessPointType; -import org.apache.juddi.api_v3.DeleteClerk; -import org.apache.juddi.api_v3.DeleteNode; -import org.apache.juddi.api_v3.DeletePublisher; -import org.apache.juddi.api_v3.SavePublisher; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.Constants; -import org.apache.juddi.config.Install; -import org.apache.juddi.config.PersistenceManager; -import org.apache.juddi.config.Property; -import org.apache.juddi.keygen.KeyGenerator; -import org.apache.juddi.keygen.KeyGeneratorFactory; -import org.apache.juddi.mapping.MappingModelToApi; -import org.apache.juddi.model.Publisher; -import org.apache.juddi.model.Tmodel; -import org.apache.juddi.model.UddiEntity; -import org.apache.juddi.model.UddiEntityPublisher; -import org.apache.juddi.query.FindBusinessByPublisherQuery; -import org.apache.juddi.query.FindTModelByPublisherQuery; -import org.apache.juddi.v3.client.UDDIConstants; -import org.apache.juddi.v3.client.UDDIConstantsV2; -import org.apache.juddi.v3.client.config.TokenResolver; -import org.apache.juddi.v3.client.cryptor.CryptorFactory; -import org.apache.juddi.v3.client.cryptor.DigSigUtil; -import org.apache.juddi.v3.error.AssertionNotFoundException; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.FatalErrorException; -import org.apache.juddi.v3.error.InvalidKeyPassedException; -import org.apache.juddi.v3.error.InvalidProjectionException; -import org.apache.juddi.v3.error.KeyUnavailableException; -import org.apache.juddi.v3.error.MaxEntitiesExceededException; -import org.apache.juddi.v3.error.UserMismatchException; -import org.apache.juddi.v3.error.ValueNotAllowedException; -import org.uddi.api_v3.AccessPoint; -import org.uddi.api_v3.AddPublisherAssertions; -import org.uddi.api_v3.AddressLine; -import org.uddi.api_v3.BindingTemplate; -import org.uddi.api_v3.BusinessEntity; -import org.uddi.api_v3.BusinessService; -import org.uddi.api_v3.DeleteBinding; -import org.uddi.api_v3.DeleteBusiness; -import org.uddi.api_v3.DeletePublisherAssertions; -import org.uddi.api_v3.DeleteService; -import org.uddi.api_v3.DeleteTModel; -import org.uddi.api_v3.Description; -import org.uddi.api_v3.DiscoveryURL; -import org.uddi.api_v3.Email; -import org.uddi.api_v3.HostingRedirector; -import org.uddi.api_v3.KeyedReference; -import org.uddi.api_v3.KeyedReferenceGroup; -import org.uddi.api_v3.Name; -import org.uddi.api_v3.OverviewDoc; -import org.uddi.api_v3.OverviewURL; -import org.uddi.api_v3.Phone; -import org.uddi.api_v3.SaveBinding; -import org.uddi.api_v3.SaveBusiness; -import org.uddi.api_v3.SaveService; -import org.uddi.api_v3.SaveTModel; -import org.uddi.api_v3.TModel; -import org.uddi.repl_v3.ReplicationConfiguration; -import org.uddi.sub_v3.Subscription; -import org.uddi.v3_service.DispositionReportFaultMessage; - -/** - * Provides validation of publish requests to Juddi - * - * @author Jeff Faath - * @author Tom Cunningham - * @author Alex O'Ree Modified March - * 2013 to validate string length and ref integrity - * - * Advisory, be careful calling AppConfig.getConfiguration() from within - * validation functions, it may inadvertently cause infinite loops during the - * Install phase - * @see Install - */ -public class ValidatePublish extends ValidateUDDIApi { - - private static final Log log = LogFactory.getLog(ValidatePublish.class); - - /** - * used from Install class - * - * @param publisher - * @param nodeid - * @see Install - */ - public ValidatePublish(UddiEntityPublisher publisher, String nodeid) { - super(publisher, nodeid); - } - - public ValidatePublish(UddiEntityPublisher publisher) { - super(publisher); - } - - public void validateDeleteBusiness(EntityManager em, DeleteBusiness body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - // No null or empty list - List entityKeyList = body.getBusinessKey(); - if (entityKeyList == null || entityKeyList.size() == 0) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); - } - - HashSet dupCheck = new HashSet(); - int i = 0; - for (String entityKey : entityKeyList) { - - // Per section 4.4: keys must be case-folded - entityKey = entityKey.toLowerCase(); - entityKeyList.set(i, entityKey); - - boolean inserted = dupCheck.add(entityKey); - if (!inserted) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); - } - - Object obj = em.find(org.apache.juddi.model.BusinessEntity.class, entityKey); - if (obj == null) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BusinessNotFound", entityKey)); - } - - if (!publisher.isOwner((UddiEntity) obj) && !((Publisher) publisher).isAdmin()) { - throw new UserMismatchException(new ErrorMessage("errors.usermismatch.InvalidOwner", entityKey)); - } - - i++; - } - } - - public void validateDeleteService(EntityManager em, DeleteService body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - // No null or empty list - List entityKeyList = body.getServiceKey(); - if (entityKeyList == null || entityKeyList.size() == 0) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); - } - - HashSet dupCheck = new HashSet(); - int i = 0; - for (String entityKey : entityKeyList) { - - // Per section 4.4: keys must be case-folded - entityKey = entityKey.toLowerCase(); - entityKeyList.set(i, entityKey); - - boolean inserted = dupCheck.add(entityKey); - if (!inserted) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); - } - - Object obj = em.find(org.apache.juddi.model.BusinessService.class, entityKey); - if (obj == null) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ServiceNotFound", entityKey)); - } - - //if you're are the owner, access granted - //if you are an admin && this item belongs to this node, access granted - //else denied - AccessCheck(obj, entityKey); - i++; - } - } - - public void validateDeleteBinding(EntityManager em, DeleteBinding body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - // No null or empty list - List entityKeyList = body.getBindingKey(); - if (entityKeyList == null || entityKeyList.size() == 0) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); - } - - // Checking for duplicates and existence - HashSet dupCheck = new HashSet(); - int i = 0; - for (String entityKey : entityKeyList) { - validateKeyLength(entityKey); - // Per section 4.4: keys must be case-folded - entityKey = entityKey.toLowerCase(); - entityKeyList.set(i, entityKey); - - boolean inserted = dupCheck.add(entityKey); - if (!inserted) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); - } - - Object obj = em.find(org.apache.juddi.model.BindingTemplate.class, entityKey); - if (obj == null) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BindingTemplateNotFound", entityKey)); - } - - AccessCheck(obj, entityKey); - - i++; - } - } - - public void validateDeleteTModel(EntityManager em, DeleteTModel body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - // No null or empty list - List entityKeyList = body.getTModelKey(); - if (entityKeyList == null || entityKeyList.size() == 0) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); - } - - HashSet dupCheck = new HashSet(); - int i = 0; - for (String entityKey : entityKeyList) { - validateKeyLength(entityKey); - // Per section 4.4: keys must be case-folded - entityKey = entityKey.toLowerCase(); - entityKeyList.set(i, entityKey); - - boolean inserted = dupCheck.add(entityKey); - if (!inserted) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); - } - - Object obj = em.find(org.apache.juddi.model.Tmodel.class, entityKey); - if (obj == null) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.TModelNotFound", entityKey)); - } - - AccessCheck(obj, entityKey); - - i++; - } - } - - private void AccessCheck(Object obj, String entityKey) throws UserMismatchException { - boolean accessCheck = false; //assume access denied - if (!((UddiEntity) obj).getNodeId().equals(nodeID)) { - //prevent changes to data owned by another node in a replicated environment - //even if you're the boss - throw new UserMismatchException(new ErrorMessage("errors.usermismatch.InvalidNode", entityKey + " Owning Node: " + ((UddiEntity) obj).getNodeId() - + ", this node: " + nodeID)); - } - - if (publisher.isOwner((UddiEntity) obj) && nodeID.equals(((UddiEntity) obj).getNodeId())) { - accessCheck = true; - - } - //if i'm an admin, let me edit stuff on this node, but only stuff that's owned by this node - if (((Publisher) publisher).isAdmin() - && nodeID.equals(((UddiEntity) obj).getNodeId())) { - accessCheck = true; - } - - if (!accessCheck) { - throw new UserMismatchException(new ErrorMessage("errors.usermismatch.InvalidOwner", entityKey)); - } - - } - - public void validateDeletePublisherAssertions(EntityManager em, DeletePublisherAssertions body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - // No null or empty list - List entityList = body.getPublisherAssertion(); - if (entityList == null || entityList.size() == 0) { - throw new AssertionNotFoundException(new ErrorMessage("errors.pubassertion.NoPubAssertions")); - } - - for (org.uddi.api_v3.PublisherAssertion entity : entityList) { - validateKeyLength(entity.getFromKey()); - validateKeyLength(entity.getToKey()); - validatePublisherAssertion(em, entity); - - org.apache.juddi.model.PublisherAssertionId pubAssertionId = new org.apache.juddi.model.PublisherAssertionId(entity.getFromKey(), entity.getToKey()); - Object obj = em.find(org.apache.juddi.model.PublisherAssertion.class, pubAssertionId); - if (obj == null) { - throw new AssertionNotFoundException(new ErrorMessage("errors.pubassertion.AssertionNotFound", entity.getFromKey() + ", " + entity.getToKey())); - } else { - org.apache.juddi.model.PublisherAssertion pubAssertion = (org.apache.juddi.model.PublisherAssertion) obj; - org.uddi.api_v3.KeyedReference keyedRef = entity.getKeyedReference(); - if (keyedRef == null) { - throw new AssertionNotFoundException(new ErrorMessage("errors.pubassertion.AssertionNotFound", entity.getFromKey() + ", " + entity.getToKey())); - } - - if (!pubAssertion.getTmodelKey().equalsIgnoreCase(keyedRef.getTModelKey()) - || !pubAssertion.getKeyName().equalsIgnoreCase(keyedRef.getKeyName()) - || !pubAssertion.getKeyValue().equalsIgnoreCase(keyedRef.getKeyValue())) { - throw new AssertionNotFoundException(new ErrorMessage("errors.pubassertion.AssertionNotFound", entity.getFromKey() + ", " + entity.getToKey())); - } - //JUDDI-908 - if (!publisher.isOwner(pubAssertion.getBusinessEntityByToKey()) - && !publisher.isOwner(pubAssertion.getBusinessEntityByFromKey())) { - throw new UserMismatchException(new ErrorMessage("errors.usermismatch.assertion")); - } - - } - - } - } - - public void validateSaveBusiness(EntityManager em, SaveBusiness body, Configuration config, UddiEntityPublisher publisher) throws DispositionReportFaultMessage { - - if (config == null) { - try { - config = AppConfig.getConfiguration(); - } catch (ConfigurationException ce) { - log.error("Could not optain config. " + ce.getMessage(), ce); - } - } - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - // No null or empty list - List entityList = body.getBusinessEntity(); - if (entityList == null || entityList.size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.savebusiness.NoInput")); - } - - for (org.uddi.api_v3.BusinessEntity entity : entityList) { - validateBusinessEntity(em, entity, config, publisher); - - } - validateCheckedTModelsBE(entityList, config); - } - - public void validateSaveBusinessMax(EntityManager em) throws DispositionReportFaultMessage { - - //Obtain the maxSettings for this publisher or get the defaults - Publisher publisher = em.find(Publisher.class, getPublisher().getAuthorizedName()); - Integer maxBusinesses = publisher.getMaxBusinesses(); - try { - if (maxBusinesses == null) { - if (AppConfig.getConfiguration().containsKey(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER)) { - maxBusinesses = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1); - } else { - maxBusinesses = -1; - } - } - } catch (ConfigurationException e) { - log.error(e.getMessage(), e); - maxBusinesses = -1; //in case the configuration is not available - } - //if we have the maxBusinesses set for this publisher then we need to make sure we did not exceed it. - if (maxBusinesses > 0) { - //get the businesses owned by this publisher - List businessKeysFound = FindBusinessByPublisherQuery.select(em, null, publisher, null); - if (businessKeysFound != null && businessKeysFound.size() > maxBusinesses) { - throw new MaxEntitiesExceededException(new ErrorMessage("errors.save.maxBusinessesExceeded")); - } - } - - } - - public void validateSaveService(EntityManager em, SaveService body, Configuration config, UddiEntityPublisher publisher) throws DispositionReportFaultMessage { - - if (config == null) { - try { - config = AppConfig.getConfiguration(); - } catch (ConfigurationException ce) { - log.error("Could not optain config. " + ce.getMessage(), ce); - } - } - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - // No null or empty list - List entityList = body.getBusinessService(); - if (entityList == null || entityList.size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.saveservice.NoInput")); - } - - for (org.uddi.api_v3.BusinessService entity : entityList) { - // Entity specific data validation - validateBusinessService(em, entity, null, config, publisher); - - } - validateCheckedTModelsBS(entityList, config); - } - - public void validateSaveServiceMax(EntityManager em, String businessKey) throws DispositionReportFaultMessage { - - //Obtain the maxSettings for this publisher or get the defaults - Publisher publisher = em.find(Publisher.class, getPublisher().getAuthorizedName()); - Integer maxServices = publisher.getMaxBusinesses(); - try { - if (maxServices == null) { - if (AppConfig.getConfiguration().containsKey(Property.JUDDI_MAX_SERVICES_PER_BUSINESS)) { - maxServices = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_SERVICES_PER_BUSINESS, -1); - } else { - maxServices = -1; - } - } - } catch (ConfigurationException e) { - log.error(e.getMessage(), e); - maxServices = -1; //incase the configuration isn't available - } - //if we have the maxServices set for a business then we need to make sure we did not exceed it. - if (maxServices > 0) { - //get the businesses owned by this publisher - org.apache.juddi.model.BusinessEntity modelBusinessEntity = em.find(org.apache.juddi.model.BusinessEntity.class, businessKey); - if (modelBusinessEntity.getBusinessServices() != null && modelBusinessEntity.getBusinessServices().size() > maxServices) { - throw new MaxEntitiesExceededException(new ErrorMessage("errors.save.maxServicesExceeded")); - } - } - } - - public void validateSaveBinding(EntityManager em, SaveBinding body, Configuration config, UddiEntityPublisher publisher) throws DispositionReportFaultMessage { - - if (config == null) { - try { - config = AppConfig.getConfiguration(); - } catch (ConfigurationException ce) { - log.error("Could not optain config. " + ce.getMessage(), ce); - } - } - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - // No null or empty list - List entityList = body.getBindingTemplate(); - if (entityList == null || entityList.size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.savebinding.NoInput")); - } - - for (org.uddi.api_v3.BindingTemplate entity : entityList) { - validateBindingTemplate(em, entity, null, config, publisher); - - } - validateCheckedTModelsBT(entityList, config); - } - - public void validateSaveBindingMax(EntityManager em, String serviceKey) throws DispositionReportFaultMessage { - - //Obtain the maxSettings for this publisher or get the defaults - Publisher publisher = em.find(Publisher.class, getPublisher().getAuthorizedName()); - Integer maxBindings = publisher.getMaxBindingsPerService(); - try { - if (maxBindings == null) { - if (AppConfig.getConfiguration().containsKey(Property.JUDDI_MAX_BINDINGS_PER_SERVICE)) { - maxBindings = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_BINDINGS_PER_SERVICE, -1); - } else { - maxBindings = -1; - } - } - } catch (ConfigurationException e) { - log.error(e.getMessage(), e); - maxBindings = -1; //incase the config isn't available - } - //if we have the maxBindings set for a service then we need to make sure we did not exceed it. - if (maxBindings > 0) { - //get the bindings owned by this service - org.apache.juddi.model.BusinessService modelBusinessService = em.find(org.apache.juddi.model.BusinessService.class, serviceKey); - if (modelBusinessService.getBindingTemplates() != null && modelBusinessService.getBindingTemplates().size() > maxBindings) { - throw new MaxEntitiesExceededException(new ErrorMessage("errors.save.maxBindingsExceeded")); - } - } - } - - public void validateSaveTModel(EntityManager em, SaveTModel body, Configuration config, UddiEntityPublisher publisher) throws DispositionReportFaultMessage { - - if (config == null) { - try { - config = AppConfig.getConfiguration(); - } catch (ConfigurationException ce) { - log.error("Could not optain config. " + ce.getMessage(), ce); - } - } - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - // No null or empty list - List entityList = body.getTModel(); - if (entityList == null || entityList.size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.savetmodel.NoInput")); - } - - for (org.uddi.api_v3.TModel entity : entityList) { - validateTModel(em, entity, config, publisher); - - } - validateCheckedTModelsTM(entityList, config); - } - - public void validateSaveTModelMax(EntityManager em) throws DispositionReportFaultMessage { - - //Obtain the maxSettings for this publisher or get the defaults - Publisher publisher = em.find(Publisher.class, getPublisher().getAuthorizedName()); - Integer maxTModels = publisher.getMaxTmodels(); - try { - if (maxTModels == null) { - if (AppConfig.getConfiguration().containsKey(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER)) { - maxTModels = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1); - } else { - maxTModels = -1; - } - } - } catch (ConfigurationException e) { - log.error(e.getMessage(), e); - maxTModels = -1; //incase the config isn't available - } - //if we have the TModels set for a publisher then we need to make sure we did not exceed it. - if (maxTModels > 0) { - //get the tmodels owned by this publisher - List tmodelKeysFound = FindTModelByPublisherQuery.select(em, null, publisher, null); - if (tmodelKeysFound != null && tmodelKeysFound.size() > maxTModels) { - throw new MaxEntitiesExceededException(new ErrorMessage("errors.save.maxTModelsExceeded")); - } - } - } - - public void validateAddPublisherAssertions(EntityManager em, AddPublisherAssertions body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - // No null or empty list - List entityList = body.getPublisherAssertion(); - if (entityList == null || entityList.size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.addpublisherassertions.NoInput")); - } - - for (org.uddi.api_v3.PublisherAssertion entity : entityList) { - validatePublisherAssertion(em, entity); - } - } - - public void validateSetPublisherAssertions(EntityManager em, Holder> body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - // Assertion list can be null or empty - it signifies that publisher is deleting all their assertions - List entityList = body.value; - if (entityList != null && entityList.size() > 0) { - - for (org.uddi.api_v3.PublisherAssertion entity : entityList) { - validatePublisherAssertion(em, entity); - } - } - } - - void validateNotSigned(org.uddi.api_v3.BusinessEntity item) throws ValueNotAllowedException { - if (item == null) { - return; - } - if (item.getBusinessKey() == null && !item.getSignature().isEmpty()) { - throw new ValueNotAllowedException(new ErrorMessage("errors.entity.SignedButNoKey", "businessKey")); - } - if (item.getBusinessServices() != null && !item.getSignature().isEmpty()) { - for (int i = 0; i < item.getBusinessServices().getBusinessService().size(); i++) { - if (item.getBusinessServices().getBusinessService().get(i).getBusinessKey() == null - || item.getBusinessServices().getBusinessService().get(i).getBusinessKey().length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.entity.SignedButNoKey", "business/Service(" + i + ")/businessKey")); - } - if (item.getBusinessServices().getBusinessService().get(i).getServiceKey() == null - || item.getBusinessServices().getBusinessService().get(i).getServiceKey().length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.entity.SignedButNoKey", "business/Service(" + i + ")/serviceKey")); - } - if (item.getBusinessServices().getBusinessService().get(i).getBindingTemplates() != null) { - for (int k = 0; k < item.getBusinessServices().getBusinessService().get(i).getBindingTemplates().getBindingTemplate().size(); k++) { - if (item.getBusinessServices().getBusinessService().get(i).getBindingTemplates().getBindingTemplate().get(k).getBindingKey() == null - || item.getBusinessServices().getBusinessService().get(i).getBindingTemplates().getBindingTemplate().get(k).getBindingKey().length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.entity.SignedButNoKey", "business/Service(" + i + ")/bindingTemplate)" + k + ")/bindingKey")); - } - } - } - } - } - } - - void validateNotSigned(org.uddi.api_v3.BindingTemplate item) throws ValueNotAllowedException { - if (item == null) { - return; - } - if (item.getBindingKey() == null && !item.getSignature().isEmpty()) { - throw new ValueNotAllowedException(new ErrorMessage("errors.entity.SignedButNoKey", "bindingKey")); - } - if (item.getServiceKey() == null && !item.getSignature().isEmpty()) { - throw new ValueNotAllowedException(new ErrorMessage("errors.entity.SignedButNoKey", "serviceKey")); - } - } - - void validateNotSigned(org.uddi.api_v3.TModel item) throws ValueNotAllowedException { - if (item == null) { - return; - } - if (item.getTModelKey() == null && !item.getSignature().isEmpty()) { - throw new ValueNotAllowedException(new ErrorMessage("errors.entity.SignedButNoKey", "tModelKey")); - } - } - - void validateNotSigned(org.uddi.api_v3.BusinessService item) throws ValueNotAllowedException { - if (item == null) { - return; - } - if (item.getBusinessKey() == null && !item.getSignature().isEmpty()) { - throw new ValueNotAllowedException(new ErrorMessage("errors.entity.SignedButNoKey", "businessKey")); - } - if (item.getServiceKey() == null && !item.getSignature().isEmpty()) { - throw new ValueNotAllowedException(new ErrorMessage("errors.entity.SignedButNoKey", "serviceKey")); - } - //if i'm signed and a key isn't defined in a bt - if (item.getBindingTemplates() != null && !item.getSignature().isEmpty()) { - for (int i = 0; i < item.getBindingTemplates().getBindingTemplate().size(); i++) { - if (item.getBindingTemplates().getBindingTemplate().get(i).getBindingKey() == null - || item.getBindingTemplates().getBindingTemplate().get(i).getBindingKey().length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.entity.SignedButNoKey", "businessService/bindingTemplate(" + i + ")/bindingKey")); - } - } - } - } - - public void validateBusinessEntity(EntityManager em, org.uddi.api_v3.BusinessEntity businessEntity, - Configuration config, UddiEntityPublisher publisher) throws DispositionReportFaultMessage { - - // A supplied businessEntity can't be null - if (businessEntity == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.businessentity.NullInput")); - } - - boolean entityExists = false; - validateNotSigned(businessEntity); - String entityKey = businessEntity.getBusinessKey(); - if (entityKey == null || entityKey.length() == 0) { - KeyGenerator keyGen = KeyGeneratorFactory.getKeyGenerator(); - entityKey = keyGen.generate(publisher); - businessEntity.setBusinessKey(entityKey); - } else { - // Per section 4.4: keys must be case-folded - entityKey = entityKey.toLowerCase(); - businessEntity.setBusinessKey(entityKey); - validateKeyLength(entityKey); - Object obj = em.find(org.apache.juddi.model.BusinessEntity.class, entityKey); - if (obj != null) { - entityExists = true; - - // Make sure publisher owns this entity. - AccessCheck(obj, entityKey); - - } else { - // Inside this block, we have a key proposed by the publisher on a new entity - - // Validate key and then check to see that the proposed key is valid for this publisher - ValidateUDDIKey.validateUDDIv3Key(entityKey); - if (!publisher.isValidPublisherKey(em, entityKey)) { - throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", entityKey)); - } - - } - } - - if (!entityExists) { - // Check to make sure key isn't used by another entity. - if (!isUniqueKey(em, entityKey)) { - throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.KeyExists", entityKey)); - } - } - - // was TODO: validate "checked" categories or category groups (see section 5.2.3 of spec)? optional to support - //covered by ref integrity checks - validateNames(businessEntity.getName()); - validateDiscoveryUrls(businessEntity.getDiscoveryURLs()); - validateContacts(businessEntity.getContacts(), config); - validateCategoryBag(businessEntity.getCategoryBag(), config, false); - validateIdentifierBag(businessEntity.getIdentifierBag(), config, false); - validateDescriptions(businessEntity.getDescription()); - validateBusinessServices(em, businessEntity.getBusinessServices(), businessEntity, config, publisher); - validateSignaturesBusiness(businessEntity, config); - - } - - public void validateBusinessServices(EntityManager em, org.uddi.api_v3.BusinessServices businessServices, - org.uddi.api_v3.BusinessEntity parent, Configuration config, UddiEntityPublisher publisher) - throws DispositionReportFaultMessage { - // Business services is optional - if (businessServices == null) { - return; - } - List businessServiceList = businessServices.getBusinessService(); - if (businessServiceList == null || businessServiceList.size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.businessservices.NoInput")); - } - - for (org.uddi.api_v3.BusinessService businessService : businessServiceList) { - validateBusinessService(em, businessService, parent, config, publisher); - } - - } - - public void validateBusinessService(EntityManager em, org.uddi.api_v3.BusinessService businessService, - org.uddi.api_v3.BusinessEntity parent, Configuration config, UddiEntityPublisher publisher) - throws DispositionReportFaultMessage { - - // A supplied businessService can't be null - if (businessService == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.businessservice.NullInput")); - } - - validateNotSigned(businessService); - // Retrieve the service's passed key - String entityKey = businessService.getServiceKey(); - if (entityKey != null && entityKey.length() > 0) { - // Per section 4.4: keys must be case-folded - entityKey = entityKey.toLowerCase(); - validateKeyLength(entityKey); - businessService.setServiceKey(entityKey); - } - - // The parent key is either supplied or provided by the higher call to the parent entity save. If the passed-in parent's business key differs from - // the (non-null) business key retrieved from the service, then we have a possible service projection. - String parentKey = businessService.getBusinessKey(); - if (parentKey != null && parentKey.length() > 0) { - // Per section 4.4: keys must be case-folded - parentKey = parentKey.toLowerCase(); - businessService.setBusinessKey(parentKey); - } - - boolean isProjection = false; - if (parent != null) { - if (parentKey != null && parentKey.length() > 0) { - if (!parentKey.equalsIgnoreCase(parent.getBusinessKey())) { - // Possible projected service - if we have differing parent businesses but a service key was not provided, this is an error as it is not possible - // for the business that doesn't "own" the service to generate the key for it. - if (entityKey == null || entityKey.length() == 0) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ServiceKeyNotProvidedWithProjection", parentKey + ", " + parent.getBusinessKey())); - } - - isProjection = true; - } - } else { - parentKey = parent.getBusinessKey(); - } - } - - // Projections don't require as rigorous testing as only the projected service's business key and service key are examined for validity. - if (isProjection) { - - Object obj = em.find(org.apache.juddi.model.BusinessService.class, entityKey); - // Can't project a service that doesn't exist! - if (obj == null) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ProjectedServiceNotFound", parentKey + ", " + entityKey)); - } else { - // If the supplied business key doesn't match the existing service's business key, the projection is invalid. - org.apache.juddi.model.BusinessService bs = (org.apache.juddi.model.BusinessService) obj; - if (!businessService.getBusinessKey().equalsIgnoreCase(bs.getBusinessEntity().getEntityKey())) { - throw new InvalidProjectionException(new ErrorMessage("errors.invalidprojection.ParentMismatch", businessService.getBusinessKey() + ", " + bs.getBusinessEntity().getEntityKey())); - } - } - obj = null; - } else { - boolean entityExists = false; - if (entityKey == null || entityKey.length() == 0) { - KeyGenerator keyGen = KeyGeneratorFactory.getKeyGenerator(); - entityKey = keyGen.generate(publisher); - businessService.setServiceKey(entityKey); - } else { - - Object obj = em.find(org.apache.juddi.model.BusinessService.class, entityKey); - if (obj != null) { - entityExists = true; - - org.apache.juddi.model.BusinessService bs = (org.apache.juddi.model.BusinessService) obj; - - // If the object exists, and the parentKey was not found to this point, then a save on an existing service with a blank - // business key has occurred. It is set here and added to the entity being saved - a necessary step for the object to be - // persisted properly. (This condition makes some validation tests below unnecessary as the parent is "verified" but it's OK to - // still run them). - if (parentKey == null || parentKey.length() == 0) { - parentKey = bs.getBusinessEntity().getEntityKey(); - businessService.setBusinessKey(parentKey); - } - - // Make sure publisher owns this entity. - AccessCheck(obj, entityKey); - - // If existing service trying to be saved has a different parent key, then we have a problem - if (!parentKey.equalsIgnoreCase(bs.getBusinessEntity().getEntityKey())) { - // if both businesses are owned by this publisher then we allow it. - // we already check the current business is owned, lets see if the old one is too - if (!publisher.isOwner(bs.getBusinessEntity())) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.businessservice.ParentMismatch", parentKey + ", " + bs.getBusinessEntity().getEntityKey())); - } else { - if (log.isDebugEnabled()) { - log.debug("Services moved from business " + bs.getBusinessEntity() + " to " + businessService.getBusinessKey()); - } - } - } - - } else { - // Inside this block, we have a key proposed by the publisher on a new entity - - // Validate key and then check to see that the proposed key is valid for this publisher - ValidateUDDIKey.validateUDDIv3Key(entityKey); - if (!publisher.isValidPublisherKey(em, entityKey)) { - throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", entityKey)); - } - - } - - } - - // Parent key must be passed if this is a new entity - if (!entityExists) { - if (parentKey == null || parentKey.length() == 0) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ParentBusinessNotFound", parentKey)); - } - } - - // If parent key IS passed, whether new entity or not, it must be valid. Additionally, the current publisher must be the owner of the parent. Note that - // if a parent ENTITY was passed in, then we don't need to check for any of this since this is part of a higher call. - if (parentKey != null) { - if (parent == null) { - Object parentTemp = em.find(org.apache.juddi.model.BusinessEntity.class, parentKey); - if (parentTemp == null) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ParentBusinessNotFound", parentKey)); - } - - // Make sure publisher owns this parent entity. - AccessCheck(parentTemp, parentKey); - // if (!publisher.isOwner((UddiEntity) parentTemp)) { - // throw new UserMismatchException(new ErrorMessage("errors.usermismatch.InvalidOwnerParent", parentKey)); - //} - } - } - - if (!entityExists) { - // Check to make sure key isn't used by another entity. - if (!isUniqueKey(em, entityKey)) { - throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.KeyExists", entityKey)); - } - } - - // TODO: validate "checked" categories or category groups (see section 5.2.3 of spec)? optional to support - validateNames(businessService.getName()); - validateCategoryBag(businessService.getCategoryBag(), config, false); - validateDescriptions(businessService.getDescription()); - validateBindingTemplates(em, businessService.getBindingTemplates(), businessService, config, publisher); - validateSignaturesService(businessService, config); - } - - } - - public void validateBindingTemplates(EntityManager em, org.uddi.api_v3.BindingTemplates bindingTemplates, - org.uddi.api_v3.BusinessService parent, Configuration config, UddiEntityPublisher publisher) - throws DispositionReportFaultMessage { - // Binding templates is optional - if (bindingTemplates == null) { - return; - } - - List bindingTemplateList = bindingTemplates.getBindingTemplate(); - if (bindingTemplateList == null || bindingTemplateList.size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.bindingtemplates.NoInput")); - } - - for (org.uddi.api_v3.BindingTemplate bindingTemplate : bindingTemplateList) { - validateBindingTemplate(em, bindingTemplate, parent, config, publisher); - } - - } - - public void validateBindingTemplate(EntityManager em, org.uddi.api_v3.BindingTemplate bindingTemplate, - org.uddi.api_v3.BusinessService parent, Configuration config, UddiEntityPublisher publisher) - throws DispositionReportFaultMessage { - - // A supplied bindingTemplate can't be null - if (bindingTemplate == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.bindingtemplate.NullInput")); - } - - // Retrieve the binding's passed key - String entityKey = bindingTemplate.getBindingKey(); - if (entityKey != null && entityKey.length() > 0) { - // Per section 4.4: keys must be case-folded - entityKey = entityKey.toLowerCase(); - bindingTemplate.setBindingKey(entityKey); - validateKeyLength(entityKey); - } - - // The parent key is either supplied or provided by the higher call to the parent entity save. If it is provided in both instances, if they differ, an - // error occurs. - String parentKey = bindingTemplate.getServiceKey(); - if (parentKey != null && parentKey.length() > 0) { - // Per section 4.4: keys must be case-folded - parentKey = parentKey.toLowerCase(); - bindingTemplate.setServiceKey(parentKey); - } - - if (parent != null) { - if (parentKey != null && parentKey.length() > 0) { - if (!parentKey.equalsIgnoreCase(parent.getServiceKey())) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.bindingtemplate.ParentMismatch", parentKey + ", " + parent.getBusinessKey())); - } - } else { - parentKey = parent.getServiceKey(); - } - } - - boolean entityExists = false; - if (entityKey == null || entityKey.length() == 0) { - validateNotSigned(bindingTemplate); - KeyGenerator keyGen = KeyGeneratorFactory.getKeyGenerator(); - entityKey = keyGen.generate(publisher); - bindingTemplate.setBindingKey(entityKey); - } else { - - Object obj = em.find(org.apache.juddi.model.BindingTemplate.class, entityKey); - if (obj != null) { - entityExists = true; - - org.apache.juddi.model.BindingTemplate bt = (org.apache.juddi.model.BindingTemplate) obj; - - // If the object exists, and the parentKey was not found to this point, then a save on an existing binding with a blank - // service key has occurred. It is set here and added to the entity being saved - a necessary step for the object to be - // persisted properly. (This condition makes some validation tests below unnecessary as the parent is "verified" but it's OK to - // still run them). - if (parentKey == null || parentKey.length() == 0) { - parentKey = bt.getBusinessService().getEntityKey(); - bindingTemplate.setServiceKey(parentKey); - } - - // If existing binding trying to be saved has a different parent key, then we have a problem - // TODO: moving bindings is allowed according to spec? - if (!parentKey.equalsIgnoreCase(bt.getBusinessService().getEntityKey())) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.bindingtemplate.ParentMismatch", parentKey + ", " + bt.getBusinessService().getEntityKey())); - } - - // Make sure publisher owns this entity. - AccessCheck(obj, entityKey); - //if (!publisher.isOwner((UddiEntity) obj)&& !((Publisher) publisher).isAdmin()) { -// throw new UserMismatchException(new ErrorMessage("errors.usermismatch.InvalidOwner", entityKey)); - // } - - } else { - // Inside this block, we have a key proposed by the publisher on a new entity - - // Validate key and then check to see that the proposed key is valid for this publisher - ValidateUDDIKey.validateUDDIv3Key(entityKey); - if (!publisher.isValidPublisherKey(em, entityKey)) { - throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", entityKey)); - } - - } - - } - - // Parent key must be passed if this is a new entity - if (!entityExists) { - if (parentKey == null || parentKey.length() == 0) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ParentServiceNotFound", parentKey)); - } - } - - // If parent key IS passed, whether new entity or not, it must be valid. Additionally, the current publisher must be the owner of the parent. Note that - // if a parent ENTITY was passed in, then we don't need to check for any of this since this is part of a higher call. - if (parentKey != null) { - if (parent == null) { - Object parentTemp = em.find(org.apache.juddi.model.BusinessService.class, parentKey); - if (parentTemp == null) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ParentBusinessNotFound", parentKey)); - } else if (!(parentTemp instanceof org.apache.juddi.model.BusinessService)) { - //JUDDI-848 - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ParentBusinessNotFound", parentKey)); - } - - // Make sure publisher owns this parent entity. - AccessCheck(parentTemp, parentKey); -// if (!publisher.isOwner((UddiEntity) parentTemp)) { -// throw new UserMismatchException(new ErrorMessage("errors.usermismatch.InvalidOwnerParent", parentKey)); -// } - - } - } - - if (!entityExists) { - // Check to make sure key isn't used by another entity. - if (!isUniqueKey(em, entityKey)) { - throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.KeyExists", entityKey)); - } - } - - //was TODO validate "checked" categories or category groups (see section 5.2.3 of spec)? optional to support - //at least one must be defined - if (bindingTemplate.getAccessPoint() == null && bindingTemplate.getHostingRedirector() == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.bindingtemplate.NoAccessPoint")); - } - //but not both - if (bindingTemplate.getAccessPoint() != null && bindingTemplate.getHostingRedirector() != null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.bindingtemplate.NoAccessPoint")); - } - validateCategoryBag(bindingTemplate.getCategoryBag(), config, false); - validateTModelInstanceDetails(bindingTemplate.getTModelInstanceDetails(), config, false); - validateAccessPoint(em, bindingTemplate.getAccessPoint(), config); - validateDescriptions(bindingTemplate.getDescription()); - validateHostingRedirector(em, bindingTemplate.getHostingRedirector(), config); - - validateSignaturesBinding(bindingTemplate, config); - //validateCheckedTModels(bindingTemplate, config); - } - - public void validateTModel(EntityManager em, org.uddi.api_v3.TModel tModel, Configuration config, UddiEntityPublisher publisher) throws DispositionReportFaultMessage { - // A supplied tModel can't be null - if (tModel == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.tmodel.NullInput")); - } - - boolean entityExists = false; - String entityKey = tModel.getTModelKey(); - if (entityKey == null || entityKey.length() == 0) { - KeyGenerator keyGen = KeyGeneratorFactory.getKeyGenerator(); - entityKey = keyGen.generate(publisher); - validateNotSigned(tModel); - tModel.setTModelKey(entityKey); - } else { - // Per section 4.4: keys must be case-folded - entityKey = entityKey.toLowerCase(); - tModel.setTModelKey(entityKey); - - Object obj = em.find(org.apache.juddi.model.Tmodel.class, entityKey); - if (obj != null) { - entityExists = true; - - // Make sure publisher owns this entity. - AccessCheck(obj, entityKey); - //if (!publisher.isOwner((UddiEntity) obj)&& !((Publisher) publisher).isAdmin()) { - // throw new UserMismatchException(new ErrorMessage("errors.usermismatch.InvalidOwner", entityKey)); - // } - } else { - // Inside this block, we have a key proposed by the publisher on a new entity - - // First test to see if this is a Key Generator tModel. The keyGenerator suffix appearing in the key is the indicator, since this is not - // allowed *unless* it's a key generator. - if (entityKey.toUpperCase().contains(KeyGenerator.KEYGENERATOR_SUFFIX.toUpperCase())) { - ValidateUDDIKey.validateUDDIv3KeyGeneratorTModel(tModel); - - // The root publisher is only allowed one key generator. This is published in the installation. - String rootPublisherStr = "root"; - try { - rootPublisherStr = AppConfig.getConfiguration().getString(Property.JUDDI_ROOT_PUBLISHER); - } catch (ConfigurationException ce) { - log.error("Could not read the root publisher setting in the configuration."); - } - if (publisher.getAuthorizedName().equals(rootPublisherStr)) { - throw new FatalErrorException(new ErrorMessage("errors.tmodel.keygenerator.RootKeyGen")); - } - - // It's a valid Key Generator, but is it available for this publisher? - if (!publisher.isKeyGeneratorAvailable(em, entityKey)) { - throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", entityKey)); - } - - } else { - // If not a key generator, then simply validate key and then check to see that the proposed key is valid for this publisher - ValidateUDDIKey.validateUDDIv3Key(entityKey); - //fix for JUDDI-851 - if (!entityKey.toUpperCase().startsWith("UUID:")) { - if (!publisher.isValidPublisherKey(em, entityKey)) { - throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", entityKey)); - } - } - } - } - } - - if (!entityExists) { - // Check to make sure key isn't used by another entity. - if (!isUniqueKey(em, entityKey)) { - throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.KeyExists", entityKey)); - } - } - validateKeyLength(entityKey); - - // TODO: validate "checked" categories or category groups (see section 5.2.3 of spec)? optional to support - if (tModel.getName() == null || tModel.getName().getValue() == null - || tModel.getName().getValue().equals("")) { - throw new ValueNotAllowedException(new ErrorMessage("errors.tmodel.NoName")); - } - - validateCategoryBag(tModel.getCategoryBag(), config, false); - validateIdentifierBag(tModel.getIdentifierBag(), config, false); - validateDescriptions(tModel.getDescription()); - validateNameLength(tModel.getName().getValue()); - validateLang(tModel.getName().getLang()); - List overviewDocList = tModel.getOverviewDoc(); - if (overviewDocList != null) { - for (org.uddi.api_v3.OverviewDoc overviewDoc : overviewDocList) { - validateOverviewDoc(overviewDoc); - } - } - validateSignaturesTModel(tModel, config); - - } - - public void validatePublisherAssertion(EntityManager em, org.uddi.api_v3.PublisherAssertion pubAssertion) throws DispositionReportFaultMessage { - // A supplied publisher assertion can't be null - if (pubAssertion == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.pubassertion.NullInput")); - } - - // The keyedRef must not be blank and every field must contain data. - org.uddi.api_v3.KeyedReference keyedRef = pubAssertion.getKeyedReference(); - if (keyedRef == null - || keyedRef.getTModelKey() == null || keyedRef.getTModelKey().length() == 0 - || keyedRef.getKeyName() == null || keyedRef.getKeyName().length() == 0 - || keyedRef.getKeyValue() == null || keyedRef.getKeyValue().length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.pubassertion.BlankKeyedRef")); - } - - String fromKey = pubAssertion.getFromKey(); - if (fromKey == null || fromKey.length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.pubassertion.BlankFromKey")); - } - - String toKey = pubAssertion.getToKey(); - if (toKey == null || toKey.length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.pubassertion.BlankToKey")); - } - - if (fromKey.equalsIgnoreCase(toKey)) { - throw new ValueNotAllowedException(new ErrorMessage("errors.pubassertion.SameBusinessKey")); - } - - // Per section 4.4: keys must be case-folded - fromKey = fromKey.toLowerCase(); - pubAssertion.setFromKey(fromKey); - toKey = toKey.toLowerCase(); - pubAssertion.setToKey(toKey); - validateKeyLength(toKey); - validateKeyLength(fromKey); - Object fromObj = em.find(org.apache.juddi.model.BusinessEntity.class, fromKey); - if (fromObj == null) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BusinessNotFound", fromKey)); - } - - Object toObj = em.find(org.apache.juddi.model.BusinessEntity.class, pubAssertion.getToKey()); - if (toObj == null) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BusinessNotFound", toKey)); - } - - if (!publisher.isOwner((UddiEntity) fromObj) && !publisher.isOwner((UddiEntity) toObj)) { - throw new UserMismatchException(new ErrorMessage("errors.pubassertion.UserMismatch", fromKey + " & " + toKey)); - } - - try { - validateKeyedReference(pubAssertion.getKeyedReference(), AppConfig.getConfiguration(), false); - } catch (ConfigurationException ce) { - log.error("Could not optain config. " + ce.getMessage(), ce); - } - } - - public void validateNames(List names) throws DispositionReportFaultMessage { - // At least one name is required - if (names == null || names.size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.names.NoInput")); - } - - for (Name n : names) { - if (n.getValue() == null || n.getValue().length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.names.NoValue")); - } - validateNameLength(n.getValue()); - validateLang(n.getLang()); - } - - } - - public void validateContacts(org.uddi.api_v3.Contacts contacts, Configuration config) throws DispositionReportFaultMessage { - // Contacts is optional - if (contacts == null) { - return; - } - - // If contacts do exist, at least one contact is required - List contactList = contacts.getContact(); - if (contactList == null || contactList.size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.contacts.NoInput")); - } - - for (org.uddi.api_v3.Contact contact : contactList) { - validateContact(contact, config); - } - - } - - public void validateContact(org.uddi.api_v3.Contact contact, Configuration config) throws DispositionReportFaultMessage { - if (log.isDebugEnabled()) { - log.debug("validateContact"); - } - // A supplied contact can't be null - if (contact == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.contact.NullInput")); - } - - // At least one personName is required - List pnameList = contact.getPersonName(); - if (pnameList == null || pnameList.size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.contact.NoPersonName")); - } - for (org.uddi.api_v3.PersonName pn : pnameList) { - if (pn.getValue() == null || pn.getValue().length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.contacts.NoPersonName")); - } - validateNameLength(pn.getValue()); - validateLang(pn.getLang()); - } - - List addressList = contact.getAddress(); - if (addressList != null) { - for (org.uddi.api_v3.Address address : addressList) { - if (address != null) { - validateSortCode(address.getSortCode()); - validateKeyLength(address.getTModelKey()); - validateLang(address.getLang()); - validateUseType(address.getUseType()); - boolean checked = true; - // Per section 4.4: keys must be case-folded - if (address.getTModelKey() != null) { - address.setTModelKey(address.getTModelKey().toLowerCase()); - validatedAddressLinesIfKeyDefined(address.getAddressLine()); - - checked = verifyTModelKeyExistsAndChecked(address.getTModelKey(), config); - - } - if (address.getAddressLine() == null || address.getAddressLine().size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.contact.NoAddressLine")); - } - - if (checked) { - validateAddressLines(address.getAddressLine(), config); - } - } - } - } - validateEmailAddress(contact.getEmail()); - validatePhone(contact.getPhone()); - validateDescriptions(contact.getDescription()); - validateUseType(contact.getUseType()); - } - - public void validateDiscoveryUrls(org.uddi.api_v3.DiscoveryURLs discUrls) throws DispositionReportFaultMessage { - // Discovery Urls is optional - if (discUrls == null) { - return; - } - - // If discUrls does exist, it must have at least one element - List discUrlList = discUrls.getDiscoveryURL(); - if (discUrlList == null || discUrlList.size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.discurls.NoInput")); - } - for (org.uddi.api_v3.DiscoveryURL url : discUrlList) { - if (url.getValue() == null || url.getValue().length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.discurls.NoInput")); - } - validateDiscoveryUrlLength(url); - } - } - - public void validateCategoryBag(org.uddi.api_v3.CategoryBag categories, Configuration config, boolean isRoot) throws DispositionReportFaultMessage { - - // Category bag is optional - if (categories == null) { - return; - } - - // If category bag does exist, it must have at least one element - List elems = categories.getKeyedReference(); - List groups = categories.getKeyedReferenceGroup(); - if (groups.size() == 0 && elems.size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.categorybag.NoInput")); - } - - for (KeyedReferenceGroup group : groups) { - validateKeyedReferenceGroup(group, config, isRoot); - } - - for (KeyedReference elem : elems) { - validateKeyedReference(elem, config, isRoot); - } - } - - public void validateIdentifierBag(org.uddi.api_v3.IdentifierBag identifiers, Configuration config, boolean isRoot) throws DispositionReportFaultMessage { - - // Identifier bag is optional - if (identifiers == null) { - return; - } - - // If category bag does exist, it must have at least one element - List keyedRefList = identifiers.getKeyedReference(); - if (keyedRefList == null || keyedRefList.size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.identifierbag.NoInput")); - } - - for (org.uddi.api_v3.KeyedReference keyedRef : keyedRefList) { - validateKeyedReference(keyedRef, config, isRoot); - } - } - - public void validateKeyedReferenceGroup(KeyedReferenceGroup krg, Configuration config, boolean isRoot) throws DispositionReportFaultMessage { - // Keyed reference groups must contain a tModelKey - if (log.isDebugEnabled()) { - log.debug("validateKeyedReferenceGroup"); - } - if (krg.getTModelKey() == null || krg.getTModelKey().length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.keyedreference.NoTModelKey")); - } - - // Per section 4.4: keys must be case-folded - String tmodelKey = krg.getTModelKey().toLowerCase(); - krg.setTModelKey(tmodelKey); - validateKeyLength(tmodelKey); - - boolean checkRef = false; - try { - checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false); - } catch (Exception ex) { - log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file", ex); - } - if (checkRef && !isRoot) { - this.verifyTModelKeyExists(tmodelKey); - } - - boolean checked = verifyTModelKeyExistsAndChecked(tmodelKey, config); - - if (checked) { - List keyedRefs = krg.getKeyedReference(); - // Should being empty raise an error? - if (keyedRefs != null && keyedRefs.size() > 0) { - for (KeyedReference keyedRef : keyedRefs) { - validateKeyedReference(keyedRef, config, isRoot); - } - } - } - } - - /** - * - * @param kr - * @param config - * @param isRoot true during install time, otherwise false - * @throws DispositionReportFaultMessage - */ - public void validateKeyedReference(KeyedReference kr, Configuration config, boolean isRoot) throws DispositionReportFaultMessage { - if (log.isDebugEnabled()) { - log.debug("validateKeyedReference"); - } - String tmodelKey = kr.getTModelKey(); - - if (tmodelKey == null || tmodelKey.length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.keyedreference.NoTModelKey")); - } - - // Per section 4.4: keys must be case-folded - tmodelKey = tmodelKey.toLowerCase(); - kr.setTModelKey(tmodelKey); - validateKeyLength(tmodelKey); - - if (kr.getKeyValue() == null || kr.getKeyValue().length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.keyedreference.NoKeyValue")); - } - validateKeyValue(kr.getKeyValue()); - validateKeyName(kr.getKeyName()); - - boolean checkRef = false; - try { - checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false); - } catch (Exception ex) { - log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file", ex); - } - if (checkRef && !isRoot) { - this.verifyTModelKeyExists(tmodelKey); - - } - - String rootPublisherStr = config.getString(Property.JUDDI_ROOT_PUBLISHER); - // Per section 6.2.2.1 of the specification, no publishers (except the root) are allowed to use the node categorization tmodelKey - if (Constants.NODE_CATEGORY_TMODEL.equalsIgnoreCase(kr.getTModelKey())) { - if (!rootPublisherStr.equals(publisher.getAuthorizedName())) { - throw new ValueNotAllowedException(new ErrorMessage("errors.keyedreference.NodeCategoryTModel", Constants.NODE_CATEGORY_TMODEL)); - } - } - } - - public void validateTModelInstanceDetails(org.uddi.api_v3.TModelInstanceDetails tmodelInstDetails, Configuration config, boolean isRoot) throws DispositionReportFaultMessage { - if (log.isDebugEnabled()) { - log.debug("validateTModelInstanceDetails"); - } - // tModel Instance Details is optional - if (tmodelInstDetails == null) { - return; - } - - // If tmodelInstDetails does exist, it must have at least one element - List tmodelInstInfoList = tmodelInstDetails.getTModelInstanceInfo(); - if (tmodelInstInfoList == null || tmodelInstInfoList.size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.tmodelinstdetails.NoInput")); - } - - for (org.uddi.api_v3.TModelInstanceInfo tmodelInstInfo : tmodelInstInfoList) { - validateTModelInstanceInfo(tmodelInstInfo, config, isRoot); - } - } - - public void validateTModelInstanceInfo(org.uddi.api_v3.TModelInstanceInfo tmodelInstInfo, Configuration config, boolean isRoot) throws DispositionReportFaultMessage { - // tModel Instance Info can't be null - if (tmodelInstInfo == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.tmodelinstinfo.NullInput")); - } - - // TModel key is required - if (tmodelInstInfo.getTModelKey() == null || tmodelInstInfo.getTModelKey().length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.tmodelinstinfo.NoTModelKey")); - } - - // Per section 4.4: keys must be case-folded - tmodelInstInfo.setTModelKey((tmodelInstInfo.getTModelKey().toLowerCase())); - - boolean checkRef = false; - try { - checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false); - } catch (Exception ex) { - log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file", ex); - } - if (checkRef && !isRoot) { - this.verifyTModelKeyExists(tmodelInstInfo.getTModelKey()); - } - - validateInstanceDetails(tmodelInstInfo.getInstanceDetails()); - if (log.isDebugEnabled()) { - log.debug("validateTModelInstanceInfo"); - } - - validateKeyLength(tmodelInstInfo.getTModelKey()); - validateDescriptions(tmodelInstInfo.getDescription()); - - } - - public void validateInstanceDetails(org.uddi.api_v3.InstanceDetails instDetails) throws DispositionReportFaultMessage { - // Instance Details is optional - if (instDetails == null) { - return; - } - - // At least one OverviewDoc or instanceParms must be supplied - List elems = instDetails.getOverviewDoc(); - if (instDetails.getInstanceParms() == null && elems.size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.instdetails.NoOverviewOrParms")); - } - for (int i = 0; i < elems.size(); i++) { - validateDescriptions(elems.get(i).getDescription()); - validateOverviewURL(elems.get(i).getOverviewURL()); - } - if (instDetails.getInstanceParms()!=null){ - if (instDetails.getInstanceParms().length()>8192){ - throw new ValueNotAllowedException(new ErrorMessage("errors.instdetails.MaxLength",instDetails.getInstanceParms().length()+"")); - } - } - } - - public void validateOverviewDoc(org.uddi.api_v3.OverviewDoc overviewDoc) throws DispositionReportFaultMessage { - // OverviewDoc can't be null - if (overviewDoc == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.overviewdoc.NullInput")); - } - - // At least one description or overview URL must be supplied - List elems = overviewDoc.getDescription(); - if ((elems == null || elems.size() == 0) && overviewDoc.getOverviewURL() == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.overviewdoc.NoDescOrUrl")); - } - for (int i = 0; i < elems.size(); i++) { - validateLang(elems.get(i).getLang()); - validateURL(elems.get(i).getValue()); - } - } - - public void validateRegisteredInfo(org.uddi.api_v3.GetRegisteredInfo body) throws DispositionReportFaultMessage { - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - // infoSelection is required - if (body.getInfoSelection() == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.getregisteredinfo.NoInfoSelection")); - } - - } - - /** - * Publishing API functions are specific to jUDDI. Requires - * administrative privilege - * - * @param em - * @param body - * @throws DispositionReportFaultMessage - */ - public void validateDeletePublisher(EntityManager em, DeletePublisher body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - // No null or empty list - List entityKeyList = body.getPublisherId(); - if (entityKeyList == null || entityKeyList.size() == 0) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); - } - - if (!((Publisher) publisher).isAdmin()) { - throw new UserMismatchException(new ErrorMessage("errors.deletepublisher.AdminReqd")); - } - - HashSet dupCheck = new HashSet(); - for (String entityKey : entityKeyList) { - validateKeyLength(entityKey); - boolean inserted = dupCheck.add(entityKey); - if (!inserted) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); - } - - Object obj = em.find(org.apache.juddi.model.Publisher.class, entityKey); - if (obj == null) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.PublisherNotFound", entityKey)); - } - - } - } - - public void validateSaveSubscriptionAdmin(EntityManager em, String publisherOrUsername, List subscriptions) throws DispositionReportFaultMessage { - - // No null input - if (subscriptions == null || subscriptions.isEmpty()) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - if (!((Publisher) publisher).isAdmin()) { - throw new UserMismatchException(new ErrorMessage("errors.deletepublisher.AdminReqd")); - } - UddiEntityPublisher user = new UddiEntityPublisher(publisherOrUsername); - ValidateSubscription vsub = new ValidateSubscription(user); - for (int i = 0; i < subscriptions.size(); i++) { - vsub.validateSubscriptions(em, subscriptions, user); - } - } - - public void validateSavePublisher(EntityManager em, SavePublisher body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - // No null or empty list - List entityList = body.getPublisher(); - if (entityList == null || entityList.size() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.savepublisher.NoInput")); - } - - if (!((Publisher) publisher).isAdmin()) { - throw new UserMismatchException(new ErrorMessage("errors.savepublisher.AdminReqd", publisher.getAuthorizedName())); - } - - for (org.apache.juddi.api_v3.Publisher entity : entityList) { - validatePublisher(em, entity); - } - } - - public void validatePublisher(EntityManager em, org.apache.juddi.api_v3.Publisher publisher) throws DispositionReportFaultMessage { - - // No null input - if (publisher == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.publisher.NullInput")); - } - - String authorizedName = publisher.getAuthorizedName(); - if (authorizedName == null || authorizedName.length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.publisher.NoAuthorizedName")); - } - - String publisherName = publisher.getPublisherName(); - if (publisherName == null || publisherName.length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.publisher.NoPublisherName")); - } -//TODO identify JUDDI restrictions on publisher name - } - - public void validateAdminDeleteTModel(EntityManager em, DeleteTModel body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) { - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - } - - // No null or empty list - List entityKeyList = body.getTModelKey(); - if (entityKeyList == null || entityKeyList.size() == 0) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); - } - - if (!((Publisher) publisher).isAdmin()) { - throw new UserMismatchException(new ErrorMessage("errors.AdminReqd")); - } - - HashSet dupCheck = new HashSet(); - for (String entityKey : entityKeyList) { - validateKeyLength(entityKey); - boolean inserted = dupCheck.add(entityKey); - if (!inserted) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); - } - - //removed a check for checking if the entity exists which was moved to the juddi api class - //why? because we were looking up the same object twice in the database and its just not efficient - } - } - //////////////////////////////////////////////////////////////////// - ////////////////////////// begin validation code - //////////////////////////////////////////////////////////////////// - - private static void validateDescription(String value) throws ValueNotAllowedException { - if (value != null && value.length() > ValidationConstants.MAX_description) { - throw new ValueNotAllowedException(new ErrorMessage("errors.DescriptionTooLong")); - } - } - - public static void validateLang(String lang) throws ValueNotAllowedException { - if (lang != null && lang.length() > ValidationConstants.MAX_xml_lang) { - throw new ValueNotAllowedException(new ErrorMessage("errors.names.LangTooLong")); - } - } - - private static void validateUseType(String useType) throws ValueNotAllowedException { - if (useType != null && useType.length() > ValidationConstants.MAX_useType) { - throw new ValueNotAllowedException(new ErrorMessage("errors.names.UseTypeTooLong")); - } - } - - public static void validateKeyLength(String value) throws ValueNotAllowedException { - if (value != null && value.length() > ValidationConstants.MAX_Key) { - throw new ValueNotAllowedException(new ErrorMessage("errors.keys.TooLong")); - } - } - - private void validateAccessPoint(EntityManager em, AccessPoint value, Configuration config) throws ValueNotAllowedException { - if (log.isDebugEnabled()) { - log.debug("validateAccessPoint"); - } - - if (value != null) { - if (value.getValue().length() > ValidationConstants.MAX_accessPoint) { - throw new ValueNotAllowedException(new ErrorMessage("errors.accessPoint.TooLong")); - } - - validateUseType(value.getUseType()); - if (value.getUseType() != null) { - if (value.getUseType().equalsIgnoreCase(AccessPointType.BINDING_TEMPLATE.toString())) { - //validate that the referenced binding key exists already - Object obj = em.find(org.apache.juddi.model.BindingTemplate.class, value.getValue()); - if (obj == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.accessPoint.bindingtemplateRedirect.keynotexist")); - } - - } else if (value.getUseType().equalsIgnoreCase(AccessPointType.HOSTING_REDIRECTOR.toString())) { - try { - //no validation necessary other than confirm that it's a URL - new URL(value.getValue()); - } catch (MalformedURLException ex) { - throw new ValueNotAllowedException(new ErrorMessage("errors.accessPoint.hostingRedirector.notaurl")); - } - } - //TODO determine if additional validation is required. - //potentials, if its a wsdl deployment, is the Value a valid URI - //if endpoint, is it a valid URI? - } - } - } - - private void validateHostingRedirector(EntityManager em, HostingRedirector hostingRedirector, Configuration config) throws ValueNotAllowedException { - if (log.isDebugEnabled()) { - log.debug("validateHostingRedirector"); - } - if (hostingRedirector == null) { - return; - } - - if (hostingRedirector.getBindingKey() == null || hostingRedirector.getBindingKey().length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.hostingredirector.noinput")); - } - if (hostingRedirector.getBindingKey().length() > ValidationConstants.MAX_Key) { - throw new ValueNotAllowedException(new ErrorMessage("errors.hostingredirector.TooLong")); - } - boolean checkRef = false; - try { - checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false); - } catch (Exception ex) { - log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file", ex); - } - if (checkRef) { - //TODO check the spec to confirm this is logically correct - /*Object obj = em.find(org.apache.juddi.model.BindingTemplate.class, hostingRedirector.getBindingKey()); - if (obj == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.hostingredirector.keynotexist")); - }*/ - } - - } - - private void validateNameLength(String value) throws ValueNotAllowedException { - if (value == null || value.length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.names.NoInput")); - } - if (value.length() > ValidationConstants.MAX_name) { - throw new ValueNotAllowedException(new ErrorMessage("errors.names.TooLong")); - } - - } - - private void validateSortCode(String value) throws ValueNotAllowedException { - if (value != null && value.length() > ValidationConstants.MAX_sortCode) { - throw new ValueNotAllowedException(new ErrorMessage("errors.sortCode.TooLong")); - } - } - - private void validateAddressLines(List addressLine, Configuration config) throws ValueNotAllowedException { - if (log.isDebugEnabled()) { - log.debug("validateAddressLines"); - } - if (addressLine != null) { - for (int i = 0; i < addressLine.size(); i++) { - validateKeyName(addressLine.get(i).getKeyName()); - verifyTModelKeyExistsAndChecked(addressLine.get(i).getKeyName(), config); - - validateKeyValue(addressLine.get(i).getKeyValue()); - if (addressLine.get(i).getValue() == null || addressLine.get(i).getValue().length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.addressline.noinput")); - } - if (addressLine.get(i).getValue().length() > ValidationConstants.MAX_addressLine) { - throw new ValueNotAllowedException(new ErrorMessage("errors.addressline.TooLong")); - } - } - } - } - - private void validateEmailAddress(List email) throws ValueNotAllowedException { - if (email != null) { - for (int i = 0; i < email.size(); i++) { - validateUseType(email.get(i).getUseType()); - if (email.get(i).getValue() == null || email.get(i).getValue().length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.email.noinput")); - } - if (email.get(i).getValue().length() > ValidationConstants.MAX_email) { - throw new ValueNotAllowedException(new ErrorMessage("errors.email.TooLong")); - } - } - } - } - - private void validatePhone(List phone) throws ValueNotAllowedException { - if (phone != null) { - for (int i = 0; i < phone.size(); i++) { - validateUseType(phone.get(i).getUseType()); - if (phone.get(i).getValue() == null - || phone.get(i).getValue().length() == 0) { - throw new ValueNotAllowedException(new ErrorMessage("errors.phone.noinput")); - } - if (phone.get(i).getValue().length() > ValidationConstants.MAX_phone) { - throw new ValueNotAllowedException(new ErrorMessage("errors.phone.TooLong")); - } - } - } - } - - private void validateDiscoveryUrlLength(DiscoveryURL url) throws ValueNotAllowedException { - if (url != null) { - validateUseType(url.getUseType()); - validateURL(url.getValue()); - } - } - - private void validateKeyValue(String value) throws ValueNotAllowedException { - if (value != null && value.length() > ValidationConstants.MAX_keyValue) { - throw new ValueNotAllowedException(new ErrorMessage("errors.keyvalue.TooLong")); - } - } - - private void validateKeyName(String value) throws ValueNotAllowedException { - if (value != null && value.length() > ValidationConstants.MAX_keyValue) { - throw new ValueNotAllowedException(new ErrorMessage("errors.keyname.TooLong")); - } - - } - - private void validateDescriptions(List description) throws ValueNotAllowedException { - for (int i = 0; i < description.size(); i++) { - if (description.get(i).getValue() == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.contact.EmptyDescription")); - } - - validateLang(description.get(i).getLang()); - validateDescription(description.get(i).getValue()); - } - } - - private void validateOverviewURL(OverviewURL overviewURL) throws ValueNotAllowedException { - if (overviewURL != null) { - validateUseType(overviewURL.getUseType()); - validateURL(overviewURL.getValue()); - } - } - - private void validateURL(String value) throws ValueNotAllowedException { - if (value != null && value.length() > ValidationConstants.MAX_overviewURL) { - throw new ValueNotAllowedException(new ErrorMessage("errors.url.overviewTooLong")); - } - } - - /** - * Validates that a tmodel key is registered Alex O'Ree - * - * @param tmodelKey - * @param em - * @throws ValueNotAllowedException - * @see org.apache.juddi.config.Install - * @since 3.1.5 - */ - private boolean verifyTModelKeyExistsAndChecked(String tmodelKey, Configuration config) throws ValueNotAllowedException { - boolean checked = true; - if (tmodelKey == null || tmodelKey.length() == 0) { - return false; - } - if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:categorization:types")) { - return false; - } - if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:categorization:nodes")) { - return false; - } - if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_inquiry")) { - return false; - } - if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_publication")) { - return false; - } - if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_security")) { - return false; - } - if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_ownership_transfer")) { - return false; - } - if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_subscription")) { - return false; - } - if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_subscriptionlistener")) { - return false; - } - - if (config == null) { - log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullConfig")); - return false; - } - boolean checkRef = false; - try { - checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false); - } catch (Exception ex) { - log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file", ex); - } - if (checkRef) { - if (log.isDebugEnabled()) { - log.debug("verifyTModelKeyExists " + tmodelKey); - } - EntityManager em = PersistenceManager.getEntityManager(); - - if (em == null) { - //this is normally the Install class firing up - log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullEM")); - } else { - //Collections.sort(buildInTmodels); - //if ((buildInTmodels, tmodelKey) == -1) - Tmodel modelTModel = null; - { - EntityTransaction tx = em.getTransaction(); - try { - - tx.begin(); - modelTModel = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey); - - if (modelTModel == null) { - checked = false; - } else { - if (modelTModel.getCategoryBag()!=null) - for (org.apache.juddi.model.KeyedReference ref : modelTModel.getCategoryBag().getKeyedReferences()) { - if ("uddi-org:types:unchecked".equalsIgnoreCase(ref.getKeyName())) { - checked = false; - break; - } - } - } - - tx.commit(); - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - if (modelTModel == null) { - throw new ValueNotAllowedException(new ErrorMessage("errors.tmodel.ReferencedKeyDoesNotExist", tmodelKey)); - } - } - } - } - return checked; - } - - private boolean verifyTModelKeyChecked(Tmodel modelTModel) { - boolean checked = true; - if (modelTModel == null) { - checked = false; - } else { - for (org.apache.juddi.model.KeyedReference ref : modelTModel.getCategoryBag().getKeyedReferences()) { - if ("uddi-org:types:unchecked".equalsIgnoreCase(ref.getTmodelKeyRef())) { - checked = false; - break; - } - } - } - return checked; - } - - /** - * throws if it doesn't exist, returns it if it does - * - * @param tmodelKey - * @return null, or a TModel object - * @throws ValueNotAllowedException - * @since 3.3 - */ - private TModel verifyTModelKeyExists(String tmodelKey) throws ValueNotAllowedException, DispositionReportFaultMessage { - TModel api = null; - EntityManager em = PersistenceManager.getEntityManager(); - boolean found = false; - if (em == null) { - log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullEM")); - } else { - Tmodel modelTModel = null; - { - EntityTransaction tx = em.getTransaction(); - try { - - tx.begin(); - modelTModel = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey); - - if (modelTModel != null) { - found = true; - api = new TModel(); - MappingModelToApi.mapTModel(modelTModel, api); - } - tx.commit(); - - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - } - } - if (!found) { - throw new ValueNotAllowedException(new ErrorMessage("errors.tmodel.ReferencedKeyDoesNotExist", tmodelKey)); - } - return api; - } - - private List GetBindingKeysCheckedTModelKeyedReferenceBT(Map cache, List obj) { - List ret = new ArrayList(); - - if (obj == null) { - return ret; - } - for (BindingTemplate bt : obj) { - if (bt.getCategoryBag() != null) { - for (int i = 0; i < bt.getCategoryBag().getKeyedReference().size(); i++) { - ret.addAll(GetBindingKeysCheckedTModelKeyedReference(cache, bt.getCategoryBag().getKeyedReference().get(i))); - } - } - } - - return ret; - } - - private List GetBindingKeysCheckedTModelKeyedReferenceBS(Map cache, List obj) { - List ret = new ArrayList(); - - if (obj == null) { - return ret; - } - for (BusinessService bt : obj) { - if (bt.getCategoryBag() != null) { - for (int i = 0; i < bt.getCategoryBag().getKeyedReference().size(); i++) { - ret.addAll(GetBindingKeysCheckedTModelKeyedReference(cache, bt.getCategoryBag().getKeyedReference().get(i))); - } - } - if (bt.getBindingTemplates() != null) { - ret.addAll(GetBindingKeysCheckedTModelKeyedReferenceBT(cache, bt.getBindingTemplates().getBindingTemplate())); - } - } - - return ret; - } - - private List GetBindingKeysCheckedTModelKeyedReferenceBE(Map cache, List obj) { - List ret = new ArrayList(); - - if (obj == null) { - return ret; - } - for (BusinessEntity bt : obj) { - if (bt.getCategoryBag() != null) { - for (int i = 0; i < bt.getCategoryBag().getKeyedReference().size(); i++) { - ret.addAll(GetBindingKeysCheckedTModelKeyedReference(cache, bt.getCategoryBag().getKeyedReference().get(i))); - } - } - if (bt.getIdentifierBag() != null) { - for (int i = 0; i < bt.getIdentifierBag().getKeyedReference().size(); i++) { - ret.addAll(GetBindingKeysCheckedTModelKeyedReference(cache, bt.getIdentifierBag().getKeyedReference().get(i))); - } - } - - if (bt.getBusinessServices() != null) { - ret.addAll(GetBindingKeysCheckedTModelKeyedReferenceBS(cache, bt.getBusinessServices().getBusinessService())); - } - } - return ret; - } - - private List GetBindingKeysCheckedTModelKeyedReferenceTM(Map cache, List obj) { - List ret = new ArrayList(); - - if (obj == null) { - return ret; - } - for (TModel bt : obj) { - if (bt.getCategoryBag() != null) { - for (int i = 0; i < bt.getCategoryBag().getKeyedReference().size(); i++) { - ret.addAll(GetBindingKeysCheckedTModelKeyedReference(cache, bt.getCategoryBag().getKeyedReference().get(i))); - } - } - if (bt.getIdentifierBag() != null) { - for (int i = 0; i < bt.getIdentifierBag().getKeyedReference().size(); i++) { - ret.addAll(GetBindingKeysCheckedTModelKeyedReference(cache, bt.getIdentifierBag().getKeyedReference().get(i))); - } - } - } - return ret; - } - - /** - * this should return a list of binding keys, only if the referenced kr - * contains is validated by - * - * @param cache - * @param get - * @return - */ - private List GetBindingKeysCheckedTModelKeyedReference(Map cache, KeyedReference get) { - List ret = new ArrayList(); - TModel ref = null; - log.debug("looking for is validated by for keyedref " + get.getTModelKey()); - if (cache.containsKey(get.getTModelKey())) { - ref = cache.get(get.getTModelKey()); - } - if (ref == null) { - try { - ref = verifyTModelKeyExists(get.getTModelKey()); - cache.put(get.getTModelKey(), ref); - } catch (Exception ex) { - log.error("unexpected error loading tmodel " + get.getTModelKey(), ex); - } - } - if (ref != null) { - - ret.addAll(TModelContains(UDDIConstants.IS_VALIDATED_BY, ref)); - ret.addAll(TModelContains(UDDIConstantsV2.IS_VALIDATED_BY, ref)); - - } - return ret; - } - - /** - * returns all keyvalues from ref.catbag and identbag where the tmodel - * key matches - * - * @param key - * @param ref - * @return - */ - private List TModelContains(String key, TModel ref) { - - if (key == null) { - return null; - } - if (ref == null || ref.getTModelKey()==null) { - return null; - } - log.debug("looking for key=" + key + " from tModel " + ref.getTModelKey()); - List ret = new ArrayList(); - - if (ref.getCategoryBag() != null) { - for (int i = 0; i < ref.getCategoryBag().getKeyedReference().size(); i++) { - if (ref.getCategoryBag().getKeyedReference().get(i).getTModelKey().equalsIgnoreCase(key)) { - log.debug("found reference for key=" + key + " from tModel " + ref.getTModelKey() + " validation endpoint " + ref.getCategoryBag().getKeyedReference().get(i).getKeyValue()); - ret.add(ref.getCategoryBag().getKeyedReference().get(i).getKeyValue()); - } - } - for (int i = 0; i < ref.getCategoryBag().getKeyedReferenceGroup().size(); i++) { - for (int k = 0; k < ref.getCategoryBag().getKeyedReferenceGroup().get(i).getKeyedReference().size(); k++) { - if (ref.getCategoryBag().getKeyedReferenceGroup().get(i).getKeyedReference().get(k).getTModelKey().equalsIgnoreCase(key)) { - log.debug("found reference for key=" + key + " from tModel " + ref.getTModelKey() + " validation endpoint " + ref.getCategoryBag().getKeyedReferenceGroup().get(i).getKeyedReference().get(k).getKeyValue()); - ret.add(ref.getCategoryBag().getKeyedReferenceGroup().get(i).getKeyedReference().get(k).getKeyValue()); - } - } - } - } - if (ref.getIdentifierBag() != null) { - for (int i = 0; i < ref.getIdentifierBag().getKeyedReference().size(); i++) { - if (ref.getIdentifierBag().getKeyedReference().get(i).getTModelKey().equalsIgnoreCase(key)) { - log.debug("found reference for key=" + key + " from tModel " + ref.getTModelKey() + " validation endpoint " + ref.getIdentifierBag().getKeyedReference().get(i).getKeyValue()); - ret.add(ref.getIdentifierBag().getKeyedReference().get(i).getKeyValue()); - } - } - } - return ret; - } - - /** - * JUDDI-849 Each addressLine element MAY be adorned with two optional - * descriptive attributes, keyName and keyValue. Both attributes MUST be - * present in each address line if a tModelKey is specified in the - * address structure. When no tModelKey is provided for the address - * structure, the keyName and keyValue attributes have no defined - * meaning. - * - * @param addressLine - */ - private void validatedAddressLinesIfKeyDefined(List addressLine) throws ValueNotAllowedException { - StringBuilder err = new StringBuilder(); - for (int i = 0; i < addressLine.size(); i++) { - - if (addressLine.get(i).getKeyName() == null - || addressLine.get(i).getKeyName().trim().length() == 0) { - err.append("addressLine(").append(i).append(").keyName,"); - } - if (addressLine.get(i).getKeyValue() == null - || addressLine.get(i).getKeyValue().trim().length() == 0) { - err.append("addressLine(").append(i).append(").keyValue,"); - } - if (addressLine.get(i).getValue() == null - || addressLine.get(i).getValue().trim().length() == 0) { - err.append("addressLine(").append(i).append(").value,"); - } - } - if (err.length() > 0) { - throw new ValueNotAllowedException(new ErrorMessage("E_invalidValueAddressLine", err.toString())); - } - } - - private void validateCheckedTModelsBT(List bindingTemplate, Configuration config) throws ValueNotAllowedException { - - boolean checkRef = false; - try { - checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false); - } catch (Exception ex) { - log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file", ex); - } - - if (!checkRef) { - return; - } - Map cache = new HashMap(); - List bindings = GetBindingKeysCheckedTModelKeyedReferenceBT(cache, bindingTemplate); - - if (!bindings.isEmpty()) { - //get a unique list - bindings = new ArrayList(new HashSet(bindings)); - for (int i = 0; i < bindings.size(); i++) { - //load binding from database - EntityManager em = PersistenceManager.getEntityManager(); - org.apache.juddi.model.BindingTemplate find = em.find(org.apache.juddi.model.BindingTemplate.class, bindings.get(i)); - if (find != null) { - //parse endpoint - String url = find.getAccessPointUrl(); - if (url == null) { - url = find.getHostingRedirector(); - } - if (url != null) { - //call ValidateValuesFromWebService - //optimization for localhost? - ValidateValuesFromWebService.ValidateBinding(Rectify(url, config), bindingTemplate); - } - - } - } - } - } - - private void validateCheckedTModelsBS(List bizlist, Configuration config) throws ValueNotAllowedException { - boolean checkRef = false; - try { - checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false); - } catch (Exception ex) { - log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file", ex); - } - if (!checkRef) { - return; - } - Map cache = new HashMap(); - List bindings = GetBindingKeysCheckedTModelKeyedReferenceBS(cache, bizlist); - - if (!bindings.isEmpty()) { - //get a unique list - bindings = new ArrayList(new HashSet(bindings)); - for (int i = 0; i < bindings.size(); i++) { - //load binding from database - EntityManager em = PersistenceManager.getEntityManager(); - org.apache.juddi.model.BindingTemplate find = em.find(org.apache.juddi.model.BindingTemplate.class, bindings.get(i)); - if (find != null) { - //parse endpoint - String url = find.getAccessPointUrl(); - if (url == null) { - url = find.getHostingRedirector(); - } - if (url != null) { - //call ValidateValuesFromWebService - //optimization for localhost? - ValidateValuesFromWebService.ValidateService(Rectify(url, config), bizlist); - } - - } - } - } - } - - private void validateCheckedTModelsBE(List entity, Configuration config) throws ValueNotAllowedException { - boolean checkRef = false; - try { - checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false); - } catch (Exception ex) { - log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file", ex); - } - if (!checkRef) { - return; - } - Map cache = new HashMap(); - List bindings = GetBindingKeysCheckedTModelKeyedReferenceBE(cache, entity); - - if (!bindings.isEmpty()) { - //get a unique list - bindings = new ArrayList(new HashSet(bindings)); - for (int i = 0; i < bindings.size(); i++) { - //load binding from database - EntityManager em = PersistenceManager.getEntityManager(); - org.apache.juddi.model.BindingTemplate find = em.find(org.apache.juddi.model.BindingTemplate.class, bindings.get(i)); - if (find != null) { - //parse endpoint - String url = find.getAccessPointUrl(); - if (url == null) { - url = find.getHostingRedirector(); - } - if (url != null) { - //call ValidateValuesFromWebService - //optimization for localhost? - ValidateValuesFromWebService.ValidateBusiness(Rectify(url, config), entity); - } - - } - } - } - } - - private void validateCheckedTModelsTM(List entity, Configuration config) throws ValueNotAllowedException { - boolean checkRef = false; - try { - checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false); - } catch (Exception ex) { - log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file", ex); - } - if (!checkRef) { - return; - } - Map cache = new HashMap(); - List bindings = GetBindingKeysCheckedTModelKeyedReferenceTM(cache, entity); - - if (!bindings.isEmpty()) { - //get a unique list - bindings = new ArrayList(new HashSet(bindings)); - for (int i = 0; i < bindings.size(); i++) { - //load binding from database - EntityManager em = PersistenceManager.getEntityManager(); - org.apache.juddi.model.BindingTemplate find = em.find(org.apache.juddi.model.BindingTemplate.class, bindings.get(i)); - if (find != null) { - //parse endpoint - String url = find.getAccessPointUrl(); - if (url == null) { - url = find.getHostingRedirector(); - } - if (url != null) { - log.debug("attempting vsv from " + url); - //call ValidateValuesFromWebService - //optimization for localhost? - ValidateValuesFromWebService.ValidateTModel(Rectify(url, config), entity); - } - - } - } - } - } - - private String Rectify(String url, Configuration config) { - //${juddi.server.baseurl} - Properties p = new Properties(); - p.put("juddi.server.baseurl", config.getString("juddi.server.baseurl", Property.DEFAULT_BASE_URL)); - - return TokenResolver.replaceTokens(url, p); - } - - public void validateDeleteNode(EntityManager em, DeleteNode nodeID, ReplicationConfiguration cfg) throws DispositionReportFaultMessage { - if (nodeID == null) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.deleteClerk.NoInput")); - } - if (!((Publisher) publisher).isAdmin()) { - throw new UserMismatchException(new ErrorMessage("errors.deletepublisher.AdminReqd")); - } - if (nodeID.getNodeID() == null || nodeID.getNodeID().trim().equalsIgnoreCase("")) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.deleteNode.NoInput")); - } - //get the latest replication config - if (cfg != null) { - if (cfg.getCommunicationGraph() != null) { - for (String node : cfg.getCommunicationGraph().getNode()) { - if (node.equals(nodeID.getNodeID())) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.deleteNode.InReplicationConfig", nodeID.getNodeID())); - } - } - for (int i = 0; i < cfg.getCommunicationGraph().getEdge().size(); i++) { - if (nodeID.getNodeID().equals(cfg.getCommunicationGraph().getEdge().get(i).getMessageReceiver())) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.deleteNode.InReplicationConfig", nodeID.getNodeID())); - } - if (nodeID.getNodeID().equals(cfg.getCommunicationGraph().getEdge().get(i).getMessageSender())) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.deleteNode.InReplicationConfig", nodeID.getNodeID())); - } - - } - } - } - - } - - public void validateDeleteClerk(EntityManager em, DeleteClerk clerkID) throws DispositionReportFaultMessage { - if (clerkID == null) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.deleteClerk.NoInput")); - } - if (!((Publisher) publisher).isAdmin()) { - throw new UserMismatchException(new ErrorMessage("errors.deletepublisher.AdminReqd")); - } - if (clerkID.getClerkID() == null || clerkID.getClerkID().trim().equalsIgnoreCase("")) { - throw new InvalidKeyPassedException(new ErrorMessage("errors.deleteClerk.NoInput")); - } - - } - - public void validateGetAllNodes() throws DispositionReportFaultMessage { - if (!((Publisher) publisher).isAdmin()) { - throw new UserMismatchException(new ErrorMessage("errors.deletepublisher.AdminReqd")); - } - } - - private org.apache.juddi.v3.client.cryptor.DigSigUtil ds = null; - - private synchronized void initDigSig(Configuration config) { - if (ds == null) { - - Properties p = new Properties(); - /** - * truststore.jks - * JKS - * password - * - * true - * true - * true - */ - p.put(DigSigUtil.TRUSTSTORE_FILE, config.getString(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_PREFIX + "trustStorePath", "")); - p.put(DigSigUtil.TRUSTSTORE_FILETYPE, config.getString(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_PREFIX + "trustStoreType", "")); - - String enc = config.getString(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_PREFIX + "trustStorePassword", ""); - if (config.getBoolean(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_PREFIX + "trustStorePassword[@isPasswordEncrypted]", false)) { - log.debug("trust password is encrypted, decrypting..."); - - String prov = config.getString(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_PREFIX + "trustStorePassword[@cryptoProvider]", ""); - try { - p.setProperty(DigSigUtil.TRUSTSTORE_FILE_PASSWORD, CryptorFactory.getCryptor(prov).decrypt(enc)); - } catch (Exception ex) { - log.warn("unable to decrypt trust store password " + ex.getMessage()); - log.debug("unable to decrypt trust store password " + ex.getMessage(), ex); - } - - } else if (!"".equals(enc)){ - log.warn("Hey, you should consider encrypting your trust store password!"); - p.setProperty(DigSigUtil.TRUSTSTORE_FILE_PASSWORD, enc); - } - - p.put(DigSigUtil.CHECK_REVOCATION_STATUS_CRL, config.getString(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_PREFIX + "checkRevocationCRL", "true")); - p.put(DigSigUtil.CHECK_TRUST_CHAIN, config.getString(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_PREFIX + "checkTrust", "true")); - p.put(DigSigUtil.CHECK_TIMESTAMPS, config.getString(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_PREFIX + "checkTimestamps", "true")); - - try { - ds = new DigSigUtil(p); - } catch (CertificateException ex) { - log.error("", ex); - } - //System.out.println("loaded from " + AppConfig.getConfigFileURL()); - //p.list(System.out); - } - } - - private void validateSignaturesBinding(BindingTemplate bindingTemplate, Configuration config) throws FatalErrorException { - boolean shouldcheck = config.getBoolean(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_ENABLE, false); - initDigSig(config); - if (shouldcheck && !bindingTemplate.getSignature().isEmpty() && ds != null) { - AtomicReference outmsg = new AtomicReference(); - boolean ok = ds.verifySignedUddiEntity(bindingTemplate, outmsg); - if (!ok) { - throw new FatalErrorException(new ErrorMessage("errors.digitalsignature.validationfailure", bindingTemplate.getBindingKey() + " " + outmsg.get())); - } - - } - } - - private void validateSignaturesService(BusinessService businessService, Configuration config) throws FatalErrorException { - boolean shouldcheck = config.getBoolean(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_ENABLE, false); - initDigSig(config); - if (shouldcheck && !businessService.getSignature().isEmpty() && ds != null) { - AtomicReference outmsg = new AtomicReference(); - boolean ok = ds.verifySignedUddiEntity(businessService, outmsg); - if (!ok) { - throw new FatalErrorException(new ErrorMessage("errors.digitalsignature.validationfailure", businessService.getServiceKey() + " " + outmsg.get())); - } - - } - } - - private void validateSignaturesTModel(TModel tModel, Configuration config) throws FatalErrorException { - boolean shouldcheck = config.getBoolean(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_ENABLE, false); - initDigSig(config); - if (shouldcheck && !tModel.getSignature().isEmpty() && ds != null) { - AtomicReference outmsg = new AtomicReference(); - boolean ok = ds.verifySignedUddiEntity(tModel, outmsg); - if (!ok) { - throw new FatalErrorException(new ErrorMessage("errors.digitalsignature.validationfailure", tModel.getTModelKey() + " " + outmsg.get())); - } - - } - } - - private void validateSignaturesBusiness(BusinessEntity businessEntity, Configuration config) throws FatalErrorException { - boolean shouldcheck = config.getBoolean(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_ENABLE, false); - initDigSig(config); - if (shouldcheck && !businessEntity.getSignature().isEmpty() && ds != null) { - AtomicReference outmsg = new AtomicReference(); - boolean ok = ds.verifySignedUddiEntity(businessEntity, outmsg); - if (!ok) { - throw new FatalErrorException(new ErrorMessage("errors.digitalsignature.validationfailure", businessEntity.getBusinessKey() + " " + outmsg.get())); - } - - } - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.validation; + +import java.net.MalformedURLException; +import java.net.URL; +import java.security.cert.CertificateException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicReference; + +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.xml.ws.Holder; + +import org.apache.commons.configuration.Configuration; +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.api_v3.AccessPointType; +import org.apache.juddi.api_v3.DeleteClerk; +import org.apache.juddi.api_v3.DeleteNode; +import org.apache.juddi.api_v3.DeletePublisher; +import org.apache.juddi.api_v3.SavePublisher; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.Constants; +import org.apache.juddi.config.Install; +import org.apache.juddi.config.PersistenceManager; +import org.apache.juddi.config.Property; +import org.apache.juddi.keygen.KeyGenerator; +import org.apache.juddi.keygen.KeyGeneratorFactory; +import org.apache.juddi.mapping.MappingModelToApi; +import org.apache.juddi.model.Publisher; +import org.apache.juddi.model.Tmodel; +import org.apache.juddi.model.UddiEntity; +import org.apache.juddi.model.UddiEntityPublisher; +import org.apache.juddi.query.FindBusinessByPublisherQuery; +import org.apache.juddi.query.FindTModelByPublisherQuery; +import org.apache.juddi.v3.client.UDDIConstants; +import org.apache.juddi.v3.client.UDDIConstantsV2; +import org.apache.juddi.v3.client.config.TokenResolver; +import org.apache.juddi.v3.client.cryptor.CryptorFactory; +import org.apache.juddi.v3.client.cryptor.DigSigUtil; +import org.apache.juddi.v3.error.AssertionNotFoundException; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.FatalErrorException; +import org.apache.juddi.v3.error.InvalidKeyPassedException; +import org.apache.juddi.v3.error.InvalidProjectionException; +import org.apache.juddi.v3.error.KeyUnavailableException; +import org.apache.juddi.v3.error.MaxEntitiesExceededException; +import org.apache.juddi.v3.error.UserMismatchException; +import org.apache.juddi.v3.error.ValueNotAllowedException; +import org.uddi.api_v3.AccessPoint; +import org.uddi.api_v3.AddPublisherAssertions; +import org.uddi.api_v3.AddressLine; +import org.uddi.api_v3.BindingTemplate; +import org.uddi.api_v3.BusinessEntity; +import org.uddi.api_v3.BusinessService; +import org.uddi.api_v3.DeleteBinding; +import org.uddi.api_v3.DeleteBusiness; +import org.uddi.api_v3.DeletePublisherAssertions; +import org.uddi.api_v3.DeleteService; +import org.uddi.api_v3.DeleteTModel; +import org.uddi.api_v3.Description; +import org.uddi.api_v3.DiscoveryURL; +import org.uddi.api_v3.Email; +import org.uddi.api_v3.HostingRedirector; +import org.uddi.api_v3.KeyedReference; +import org.uddi.api_v3.KeyedReferenceGroup; +import org.uddi.api_v3.Name; +import org.uddi.api_v3.OverviewDoc; +import org.uddi.api_v3.OverviewURL; +import org.uddi.api_v3.Phone; +import org.uddi.api_v3.SaveBinding; +import org.uddi.api_v3.SaveBusiness; +import org.uddi.api_v3.SaveService; +import org.uddi.api_v3.SaveTModel; +import org.uddi.api_v3.TModel; +import org.uddi.repl_v3.ReplicationConfiguration; +import org.uddi.sub_v3.Subscription; +import org.uddi.v3_service.DispositionReportFaultMessage; + +/** + * Provides validation of publish requests to Juddi + * + * @author Jeff Faath + * @author Tom Cunningham + * @author Alex O'Ree Modified March + * 2013 to validate string length and ref integrity + * + * Advisory, be careful calling AppConfig.getConfiguration() from within + * validation functions, it may inadvertently cause infinite loops during the + * Install phase + * @see Install + */ +public class ValidatePublish extends ValidateUDDIApi { + + private static final Log log = LogFactory.getLog(ValidatePublish.class); + + /** + * used from Install class + * + * @param publisher + * @param nodeid + * @see Install + */ + public ValidatePublish(UddiEntityPublisher publisher, String nodeid) { + super(publisher, nodeid); + } + + public ValidatePublish(UddiEntityPublisher publisher) { + super(publisher); + } + + public void validateDeleteBusiness(EntityManager em, DeleteBusiness body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + // No null or empty list + List entityKeyList = body.getBusinessKey(); + if (entityKeyList == null || entityKeyList.size() == 0) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); + } + + HashSet dupCheck = new HashSet(); + int i = 0; + for (String entityKey : entityKeyList) { + + // Per section 4.4: keys must be case-folded + entityKey = entityKey.toLowerCase(); + entityKeyList.set(i, entityKey); + + boolean inserted = dupCheck.add(entityKey); + if (!inserted) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); + } + + Object obj = em.find(org.apache.juddi.model.BusinessEntity.class, entityKey); + if (obj == null) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BusinessNotFound", entityKey)); + } + + if (!publisher.isOwner((UddiEntity) obj) && !((Publisher) publisher).isAdmin()) { + throw new UserMismatchException(new ErrorMessage("errors.usermismatch.InvalidOwner", entityKey)); + } + + i++; + } + } + + public void validateDeleteService(EntityManager em, DeleteService body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + // No null or empty list + List entityKeyList = body.getServiceKey(); + if (entityKeyList == null || entityKeyList.size() == 0) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); + } + + HashSet dupCheck = new HashSet(); + int i = 0; + for (String entityKey : entityKeyList) { + + // Per section 4.4: keys must be case-folded + entityKey = entityKey.toLowerCase(); + entityKeyList.set(i, entityKey); + + boolean inserted = dupCheck.add(entityKey); + if (!inserted) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); + } + + Object obj = em.find(org.apache.juddi.model.BusinessService.class, entityKey); + if (obj == null) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ServiceNotFound", entityKey)); + } + + //if you're are the owner, access granted + //if you are an admin && this item belongs to this node, access granted + //else denied + AccessCheck(obj, entityKey); + i++; + } + } + + public void validateDeleteBinding(EntityManager em, DeleteBinding body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + // No null or empty list + List entityKeyList = body.getBindingKey(); + if (entityKeyList == null || entityKeyList.size() == 0) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); + } + + // Checking for duplicates and existence + HashSet dupCheck = new HashSet(); + int i = 0; + for (String entityKey : entityKeyList) { + validateKeyLength(entityKey); + // Per section 4.4: keys must be case-folded + entityKey = entityKey.toLowerCase(); + entityKeyList.set(i, entityKey); + + boolean inserted = dupCheck.add(entityKey); + if (!inserted) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); + } + + Object obj = em.find(org.apache.juddi.model.BindingTemplate.class, entityKey); + if (obj == null) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BindingTemplateNotFound", entityKey)); + } + + AccessCheck(obj, entityKey); + + i++; + } + } + + public void validateDeleteTModel(EntityManager em, DeleteTModel body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + // No null or empty list + List entityKeyList = body.getTModelKey(); + if (entityKeyList == null || entityKeyList.size() == 0) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); + } + + HashSet dupCheck = new HashSet(); + int i = 0; + for (String entityKey : entityKeyList) { + validateKeyLength(entityKey); + // Per section 4.4: keys must be case-folded + entityKey = entityKey.toLowerCase(); + entityKeyList.set(i, entityKey); + + boolean inserted = dupCheck.add(entityKey); + if (!inserted) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); + } + + Object obj = em.find(org.apache.juddi.model.Tmodel.class, entityKey); + if (obj == null) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.TModelNotFound", entityKey)); + } + + AccessCheck(obj, entityKey); + + i++; + } + } + + private void AccessCheck(Object obj, String entityKey) throws UserMismatchException { + boolean accessCheck = false; //assume access denied + if (!((UddiEntity) obj).getNodeId().equals(nodeID)) { + //prevent changes to data owned by another node in a replicated environment + //even if you're the boss + throw new UserMismatchException(new ErrorMessage("errors.usermismatch.InvalidNode", entityKey + " Owning Node: " + ((UddiEntity) obj).getNodeId() + + ", this node: " + nodeID)); + } + + if (publisher.isOwner((UddiEntity) obj) && nodeID.equals(((UddiEntity) obj).getNodeId())) { + accessCheck = true; + + } + //if i'm an admin, let me edit stuff on this node, but only stuff that's owned by this node + if (((Publisher) publisher).isAdmin() + && nodeID.equals(((UddiEntity) obj).getNodeId())) { + accessCheck = true; + } + + if (!accessCheck) { + throw new UserMismatchException(new ErrorMessage("errors.usermismatch.InvalidOwner", entityKey)); + } + + } + + public void validateDeletePublisherAssertions(EntityManager em, DeletePublisherAssertions body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + // No null or empty list + List entityList = body.getPublisherAssertion(); + if (entityList == null || entityList.size() == 0) { + throw new AssertionNotFoundException(new ErrorMessage("errors.pubassertion.NoPubAssertions")); + } + + for (org.uddi.api_v3.PublisherAssertion entity : entityList) { + validateKeyLength(entity.getFromKey()); + validateKeyLength(entity.getToKey()); + validatePublisherAssertion(em, entity); + + org.apache.juddi.model.PublisherAssertionId pubAssertionId = new org.apache.juddi.model.PublisherAssertionId(entity.getFromKey(), entity.getToKey()); + Object obj = em.find(org.apache.juddi.model.PublisherAssertion.class, pubAssertionId); + if (obj == null) { + throw new AssertionNotFoundException(new ErrorMessage("errors.pubassertion.AssertionNotFound", entity.getFromKey() + ", " + entity.getToKey())); + } else { + org.apache.juddi.model.PublisherAssertion pubAssertion = (org.apache.juddi.model.PublisherAssertion) obj; + org.uddi.api_v3.KeyedReference keyedRef = entity.getKeyedReference(); + if (keyedRef == null) { + throw new AssertionNotFoundException(new ErrorMessage("errors.pubassertion.AssertionNotFound", entity.getFromKey() + ", " + entity.getToKey())); + } + + if (!pubAssertion.getTmodelKey().equalsIgnoreCase(keyedRef.getTModelKey()) + || !pubAssertion.getKeyName().equalsIgnoreCase(keyedRef.getKeyName()) + || !pubAssertion.getKeyValue().equalsIgnoreCase(keyedRef.getKeyValue())) { + throw new AssertionNotFoundException(new ErrorMessage("errors.pubassertion.AssertionNotFound", entity.getFromKey() + ", " + entity.getToKey())); + } + //JUDDI-908 + if (!publisher.isOwner(pubAssertion.getBusinessEntityByToKey()) + && !publisher.isOwner(pubAssertion.getBusinessEntityByFromKey())) { + throw new UserMismatchException(new ErrorMessage("errors.usermismatch.assertion")); + } + + } + + } + } + + public void validateSaveBusiness(EntityManager em, SaveBusiness body, Configuration config, UddiEntityPublisher publisher) throws DispositionReportFaultMessage { + + if (config == null) { + try { + config = AppConfig.getConfiguration(); + } catch (ConfigurationException ce) { + log.error("Could not optain config. " + ce.getMessage(), ce); + } + } + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + // No null or empty list + List entityList = body.getBusinessEntity(); + if (entityList == null || entityList.size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.savebusiness.NoInput")); + } + + for (org.uddi.api_v3.BusinessEntity entity : entityList) { + validateBusinessEntity(em, entity, config, publisher); + + } + validateCheckedTModelsBE(entityList, config); + } + + public void validateSaveBusinessMax(EntityManager em) throws DispositionReportFaultMessage { + + //Obtain the maxSettings for this publisher or get the defaults + Publisher publisher = em.find(Publisher.class, getPublisher().getAuthorizedName()); + Integer maxBusinesses = publisher.getMaxBusinesses(); + try { + if (maxBusinesses == null) { + if (AppConfig.getConfiguration().containsKey(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER)) { + maxBusinesses = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1); + } else { + maxBusinesses = -1; + } + } + } catch (ConfigurationException e) { + log.error(e.getMessage(), e); + maxBusinesses = -1; //in case the configuration is not available + } + //if we have the maxBusinesses set for this publisher then we need to make sure we did not exceed it. + if (maxBusinesses > 0) { + //get the businesses owned by this publisher + List businessKeysFound = FindBusinessByPublisherQuery.select(em, null, publisher, null); + if (businessKeysFound != null && businessKeysFound.size() > maxBusinesses) { + throw new MaxEntitiesExceededException(new ErrorMessage("errors.save.maxBusinessesExceeded")); + } + } + + } + + public void validateSaveService(EntityManager em, SaveService body, Configuration config, UddiEntityPublisher publisher) throws DispositionReportFaultMessage { + + if (config == null) { + try { + config = AppConfig.getConfiguration(); + } catch (ConfigurationException ce) { + log.error("Could not optain config. " + ce.getMessage(), ce); + } + } + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + // No null or empty list + List entityList = body.getBusinessService(); + if (entityList == null || entityList.size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.saveservice.NoInput")); + } + + for (org.uddi.api_v3.BusinessService entity : entityList) { + // Entity specific data validation + validateBusinessService(em, entity, null, config, publisher); + + } + validateCheckedTModelsBS(entityList, config); + } + + public void validateSaveServiceMax(EntityManager em, String businessKey) throws DispositionReportFaultMessage { + + //Obtain the maxSettings for this publisher or get the defaults + Publisher publisher = em.find(Publisher.class, getPublisher().getAuthorizedName()); + Integer maxServices = publisher.getMaxBusinesses(); + try { + if (maxServices == null) { + if (AppConfig.getConfiguration().containsKey(Property.JUDDI_MAX_SERVICES_PER_BUSINESS)) { + maxServices = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_SERVICES_PER_BUSINESS, -1); + } else { + maxServices = -1; + } + } + } catch (ConfigurationException e) { + log.error(e.getMessage(), e); + maxServices = -1; //incase the configuration isn't available + } + //if we have the maxServices set for a business then we need to make sure we did not exceed it. + if (maxServices > 0) { + //get the businesses owned by this publisher + org.apache.juddi.model.BusinessEntity modelBusinessEntity = em.find(org.apache.juddi.model.BusinessEntity.class, businessKey); + if (modelBusinessEntity.getBusinessServices() != null && modelBusinessEntity.getBusinessServices().size() > maxServices) { + throw new MaxEntitiesExceededException(new ErrorMessage("errors.save.maxServicesExceeded")); + } + } + } + + public void validateSaveBinding(EntityManager em, SaveBinding body, Configuration config, UddiEntityPublisher publisher) throws DispositionReportFaultMessage { + + if (config == null) { + try { + config = AppConfig.getConfiguration(); + } catch (ConfigurationException ce) { + log.error("Could not optain config. " + ce.getMessage(), ce); + } + } + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + // No null or empty list + List entityList = body.getBindingTemplate(); + if (entityList == null || entityList.size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.savebinding.NoInput")); + } + + for (org.uddi.api_v3.BindingTemplate entity : entityList) { + validateBindingTemplate(em, entity, null, config, publisher); + + } + validateCheckedTModelsBT(entityList, config); + } + + public void validateSaveBindingMax(EntityManager em, String serviceKey) throws DispositionReportFaultMessage { + + //Obtain the maxSettings for this publisher or get the defaults + Publisher publisher = em.find(Publisher.class, getPublisher().getAuthorizedName()); + Integer maxBindings = publisher.getMaxBindingsPerService(); + try { + if (maxBindings == null) { + if (AppConfig.getConfiguration().containsKey(Property.JUDDI_MAX_BINDINGS_PER_SERVICE)) { + maxBindings = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_BINDINGS_PER_SERVICE, -1); + } else { + maxBindings = -1; + } + } + } catch (ConfigurationException e) { + log.error(e.getMessage(), e); + maxBindings = -1; //incase the config isn't available + } + //if we have the maxBindings set for a service then we need to make sure we did not exceed it. + if (maxBindings > 0) { + //get the bindings owned by this service + org.apache.juddi.model.BusinessService modelBusinessService = em.find(org.apache.juddi.model.BusinessService.class, serviceKey); + if (modelBusinessService.getBindingTemplates() != null && modelBusinessService.getBindingTemplates().size() > maxBindings) { + throw new MaxEntitiesExceededException(new ErrorMessage("errors.save.maxBindingsExceeded")); + } + } + } + + public void validateSaveTModel(EntityManager em, SaveTModel body, Configuration config, UddiEntityPublisher publisher) throws DispositionReportFaultMessage { + + if (config == null) { + try { + config = AppConfig.getConfiguration(); + } catch (ConfigurationException ce) { + log.error("Could not optain config. " + ce.getMessage(), ce); + } + } + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + // No null or empty list + List entityList = body.getTModel(); + if (entityList == null || entityList.size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.savetmodel.NoInput")); + } + + for (org.uddi.api_v3.TModel entity : entityList) { + validateTModel(em, entity, config, publisher); + + } + validateCheckedTModelsTM(entityList, config); + } + + public void validateSaveTModelMax(EntityManager em) throws DispositionReportFaultMessage { + + //Obtain the maxSettings for this publisher or get the defaults + Publisher publisher = em.find(Publisher.class, getPublisher().getAuthorizedName()); + Integer maxTModels = publisher.getMaxTmodels(); + try { + if (maxTModels == null) { + if (AppConfig.getConfiguration().containsKey(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER)) { + maxTModels = AppConfig.getConfiguration().getInteger(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1); + } else { + maxTModels = -1; + } + } + } catch (ConfigurationException e) { + log.error(e.getMessage(), e); + maxTModels = -1; //incase the config isn't available + } + //if we have the TModels set for a publisher then we need to make sure we did not exceed it. + if (maxTModels > 0) { + //get the tmodels owned by this publisher + List tmodelKeysFound = FindTModelByPublisherQuery.select(em, null, publisher, null); + if (tmodelKeysFound != null && tmodelKeysFound.size() > maxTModels) { + throw new MaxEntitiesExceededException(new ErrorMessage("errors.save.maxTModelsExceeded")); + } + } + } + + public void validateAddPublisherAssertions(EntityManager em, AddPublisherAssertions body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + // No null or empty list + List entityList = body.getPublisherAssertion(); + if (entityList == null || entityList.size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.addpublisherassertions.NoInput")); + } + + for (org.uddi.api_v3.PublisherAssertion entity : entityList) { + validatePublisherAssertion(em, entity); + } + } + + public void validateSetPublisherAssertions(EntityManager em, Holder> body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + // Assertion list can be null or empty - it signifies that publisher is deleting all their assertions + List entityList = body.value; + if (entityList != null && entityList.size() > 0) { + + for (org.uddi.api_v3.PublisherAssertion entity : entityList) { + validatePublisherAssertion(em, entity); + } + } + } + + void validateNotSigned(org.uddi.api_v3.BusinessEntity item) throws ValueNotAllowedException { + if (item == null) { + return; + } + if (item.getBusinessKey() == null && !item.getSignature().isEmpty()) { + throw new ValueNotAllowedException(new ErrorMessage("errors.entity.SignedButNoKey", "businessKey")); + } + if (item.getBusinessServices() != null && !item.getSignature().isEmpty()) { + for (int i = 0; i < item.getBusinessServices().getBusinessService().size(); i++) { + if (item.getBusinessServices().getBusinessService().get(i).getBusinessKey() == null + || item.getBusinessServices().getBusinessService().get(i).getBusinessKey().length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.entity.SignedButNoKey", "business/Service(" + i + ")/businessKey")); + } + if (item.getBusinessServices().getBusinessService().get(i).getServiceKey() == null + || item.getBusinessServices().getBusinessService().get(i).getServiceKey().length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.entity.SignedButNoKey", "business/Service(" + i + ")/serviceKey")); + } + if (item.getBusinessServices().getBusinessService().get(i).getBindingTemplates() != null) { + for (int k = 0; k < item.getBusinessServices().getBusinessService().get(i).getBindingTemplates().getBindingTemplate().size(); k++) { + if (item.getBusinessServices().getBusinessService().get(i).getBindingTemplates().getBindingTemplate().get(k).getBindingKey() == null + || item.getBusinessServices().getBusinessService().get(i).getBindingTemplates().getBindingTemplate().get(k).getBindingKey().length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.entity.SignedButNoKey", "business/Service(" + i + ")/bindingTemplate)" + k + ")/bindingKey")); + } + } + } + } + } + } + + void validateNotSigned(org.uddi.api_v3.BindingTemplate item) throws ValueNotAllowedException { + if (item == null) { + return; + } + if (item.getBindingKey() == null && !item.getSignature().isEmpty()) { + throw new ValueNotAllowedException(new ErrorMessage("errors.entity.SignedButNoKey", "bindingKey")); + } + if (item.getServiceKey() == null && !item.getSignature().isEmpty()) { + throw new ValueNotAllowedException(new ErrorMessage("errors.entity.SignedButNoKey", "serviceKey")); + } + } + + void validateNotSigned(org.uddi.api_v3.TModel item) throws ValueNotAllowedException { + if (item == null) { + return; + } + if (item.getTModelKey() == null && !item.getSignature().isEmpty()) { + throw new ValueNotAllowedException(new ErrorMessage("errors.entity.SignedButNoKey", "tModelKey")); + } + } + + void validateNotSigned(org.uddi.api_v3.BusinessService item) throws ValueNotAllowedException { + if (item == null) { + return; + } + if (item.getBusinessKey() == null && !item.getSignature().isEmpty()) { + throw new ValueNotAllowedException(new ErrorMessage("errors.entity.SignedButNoKey", "businessKey")); + } + if (item.getServiceKey() == null && !item.getSignature().isEmpty()) { + throw new ValueNotAllowedException(new ErrorMessage("errors.entity.SignedButNoKey", "serviceKey")); + } + //if i'm signed and a key isn't defined in a bt + if (item.getBindingTemplates() != null && !item.getSignature().isEmpty()) { + for (int i = 0; i < item.getBindingTemplates().getBindingTemplate().size(); i++) { + if (item.getBindingTemplates().getBindingTemplate().get(i).getBindingKey() == null + || item.getBindingTemplates().getBindingTemplate().get(i).getBindingKey().length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.entity.SignedButNoKey", "businessService/bindingTemplate(" + i + ")/bindingKey")); + } + } + } + } + + public void validateBusinessEntity(EntityManager em, org.uddi.api_v3.BusinessEntity businessEntity, + Configuration config, UddiEntityPublisher publisher) throws DispositionReportFaultMessage { + + // A supplied businessEntity can't be null + if (businessEntity == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.businessentity.NullInput")); + } + + boolean entityExists = false; + validateNotSigned(businessEntity); + String entityKey = businessEntity.getBusinessKey(); + if (entityKey == null || entityKey.length() == 0) { + KeyGenerator keyGen = KeyGeneratorFactory.getKeyGenerator(); + entityKey = keyGen.generate(publisher); + businessEntity.setBusinessKey(entityKey); + } else { + // Per section 4.4: keys must be case-folded + entityKey = entityKey.toLowerCase(); + businessEntity.setBusinessKey(entityKey); + validateKeyLength(entityKey); + Object obj = em.find(org.apache.juddi.model.BusinessEntity.class, entityKey); + if (obj != null) { + entityExists = true; + + // Make sure publisher owns this entity. + AccessCheck(obj, entityKey); + + } else { + // Inside this block, we have a key proposed by the publisher on a new entity + + // Validate key and then check to see that the proposed key is valid for this publisher + ValidateUDDIKey.validateUDDIv3Key(entityKey); + if (!publisher.isValidPublisherKey(em, entityKey)) { + throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", entityKey)); + } + + } + } + + if (!entityExists) { + // Check to make sure key isn't used by another entity. + if (!isUniqueKey(em, entityKey)) { + throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.KeyExists", entityKey)); + } + } + + // was TODO: validate "checked" categories or category groups (see section 5.2.3 of spec)? optional to support + //covered by ref integrity checks + validateNames(businessEntity.getName()); + validateDiscoveryUrls(businessEntity.getDiscoveryURLs()); + validateContacts(businessEntity.getContacts(), config); + validateCategoryBag(businessEntity.getCategoryBag(), config, false); + validateIdentifierBag(businessEntity.getIdentifierBag(), config, false); + validateDescriptions(businessEntity.getDescription()); + validateBusinessServices(em, businessEntity.getBusinessServices(), businessEntity, config, publisher); + validateSignaturesBusiness(businessEntity, config); + + } + + public void validateBusinessServices(EntityManager em, org.uddi.api_v3.BusinessServices businessServices, + org.uddi.api_v3.BusinessEntity parent, Configuration config, UddiEntityPublisher publisher) + throws DispositionReportFaultMessage { + // Business services is optional + if (businessServices == null) { + return; + } + List businessServiceList = businessServices.getBusinessService(); + if (businessServiceList == null || businessServiceList.size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.businessservices.NoInput")); + } + + for (org.uddi.api_v3.BusinessService businessService : businessServiceList) { + validateBusinessService(em, businessService, parent, config, publisher); + } + + } + + public void validateBusinessService(EntityManager em, org.uddi.api_v3.BusinessService businessService, + org.uddi.api_v3.BusinessEntity parent, Configuration config, UddiEntityPublisher publisher) + throws DispositionReportFaultMessage { + + // A supplied businessService can't be null + if (businessService == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.businessservice.NullInput")); + } + + validateNotSigned(businessService); + // Retrieve the service's passed key + String entityKey = businessService.getServiceKey(); + if (entityKey != null && entityKey.length() > 0) { + // Per section 4.4: keys must be case-folded + entityKey = entityKey.toLowerCase(); + validateKeyLength(entityKey); + businessService.setServiceKey(entityKey); + } + + // The parent key is either supplied or provided by the higher call to the parent entity save. If the passed-in parent's business key differs from + // the (non-null) business key retrieved from the service, then we have a possible service projection. + String parentKey = businessService.getBusinessKey(); + if (parentKey != null && parentKey.length() > 0) { + // Per section 4.4: keys must be case-folded + parentKey = parentKey.toLowerCase(); + businessService.setBusinessKey(parentKey); + } + + boolean isProjection = false; + if (parent != null) { + if (parentKey != null && parentKey.length() > 0) { + if (!parentKey.equalsIgnoreCase(parent.getBusinessKey())) { + // Possible projected service - if we have differing parent businesses but a service key was not provided, this is an error as it is not possible + // for the business that doesn't "own" the service to generate the key for it. + if (entityKey == null || entityKey.length() == 0) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ServiceKeyNotProvidedWithProjection", parentKey + ", " + parent.getBusinessKey())); + } + + isProjection = true; + } + } else { + parentKey = parent.getBusinessKey(); + } + } + + // Projections don't require as rigorous testing as only the projected service's business key and service key are examined for validity. + if (isProjection) { + + Object obj = em.find(org.apache.juddi.model.BusinessService.class, entityKey); + // Can't project a service that doesn't exist! + if (obj == null) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ProjectedServiceNotFound", parentKey + ", " + entityKey)); + } else { + // If the supplied business key doesn't match the existing service's business key, the projection is invalid. + org.apache.juddi.model.BusinessService bs = (org.apache.juddi.model.BusinessService) obj; + if (!businessService.getBusinessKey().equalsIgnoreCase(bs.getBusinessEntity().getEntityKey())) { + throw new InvalidProjectionException(new ErrorMessage("errors.invalidprojection.ParentMismatch", businessService.getBusinessKey() + ", " + bs.getBusinessEntity().getEntityKey())); + } + } + obj = null; + } else { + boolean entityExists = false; + if (entityKey == null || entityKey.length() == 0) { + KeyGenerator keyGen = KeyGeneratorFactory.getKeyGenerator(); + entityKey = keyGen.generate(publisher); + businessService.setServiceKey(entityKey); + } else { + + Object obj = em.find(org.apache.juddi.model.BusinessService.class, entityKey); + if (obj != null) { + entityExists = true; + + org.apache.juddi.model.BusinessService bs = (org.apache.juddi.model.BusinessService) obj; + + // If the object exists, and the parentKey was not found to this point, then a save on an existing service with a blank + // business key has occurred. It is set here and added to the entity being saved - a necessary step for the object to be + // persisted properly. (This condition makes some validation tests below unnecessary as the parent is "verified" but it's OK to + // still run them). + if (parentKey == null || parentKey.length() == 0) { + parentKey = bs.getBusinessEntity().getEntityKey(); + businessService.setBusinessKey(parentKey); + } + + // Make sure publisher owns this entity. + AccessCheck(obj, entityKey); + + // If existing service trying to be saved has a different parent key, then we have a problem + if (!parentKey.equalsIgnoreCase(bs.getBusinessEntity().getEntityKey())) { + // if both businesses are owned by this publisher then we allow it. + // we already check the current business is owned, lets see if the old one is too + if (!publisher.isOwner(bs.getBusinessEntity())) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.businessservice.ParentMismatch", parentKey + ", " + bs.getBusinessEntity().getEntityKey())); + } else { + if (log.isDebugEnabled()) { + log.debug("Services moved from business " + bs.getBusinessEntity() + " to " + businessService.getBusinessKey()); + } + } + } + + } else { + // Inside this block, we have a key proposed by the publisher on a new entity + + // Validate key and then check to see that the proposed key is valid for this publisher + ValidateUDDIKey.validateUDDIv3Key(entityKey); + if (!publisher.isValidPublisherKey(em, entityKey)) { + throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", entityKey)); + } + + } + + } + + // Parent key must be passed if this is a new entity + if (!entityExists) { + if (parentKey == null || parentKey.length() == 0) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ParentBusinessNotFound", parentKey)); + } + } + + // If parent key IS passed, whether new entity or not, it must be valid. Additionally, the current publisher must be the owner of the parent. Note that + // if a parent ENTITY was passed in, then we don't need to check for any of this since this is part of a higher call. + if (parentKey != null) { + if (parent == null) { + Object parentTemp = em.find(org.apache.juddi.model.BusinessEntity.class, parentKey); + if (parentTemp == null) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ParentBusinessNotFound", parentKey)); + } + + // Make sure publisher owns this parent entity. + AccessCheck(parentTemp, parentKey); + // if (!publisher.isOwner((UddiEntity) parentTemp)) { + // throw new UserMismatchException(new ErrorMessage("errors.usermismatch.InvalidOwnerParent", parentKey)); + //} + } + } + + if (!entityExists) { + // Check to make sure key isn't used by another entity. + if (!isUniqueKey(em, entityKey)) { + throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.KeyExists", entityKey)); + } + } + + // TODO: validate "checked" categories or category groups (see section 5.2.3 of spec)? optional to support + validateNames(businessService.getName()); + validateCategoryBag(businessService.getCategoryBag(), config, false); + validateDescriptions(businessService.getDescription()); + validateBindingTemplates(em, businessService.getBindingTemplates(), businessService, config, publisher); + validateSignaturesService(businessService, config); + } + + } + + public void validateBindingTemplates(EntityManager em, org.uddi.api_v3.BindingTemplates bindingTemplates, + org.uddi.api_v3.BusinessService parent, Configuration config, UddiEntityPublisher publisher) + throws DispositionReportFaultMessage { + // Binding templates is optional + if (bindingTemplates == null) { + return; + } + + List bindingTemplateList = bindingTemplates.getBindingTemplate(); + if (bindingTemplateList == null || bindingTemplateList.size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.bindingtemplates.NoInput")); + } + + for (org.uddi.api_v3.BindingTemplate bindingTemplate : bindingTemplateList) { + validateBindingTemplate(em, bindingTemplate, parent, config, publisher); + } + + } + + public void validateBindingTemplate(EntityManager em, org.uddi.api_v3.BindingTemplate bindingTemplate, + org.uddi.api_v3.BusinessService parent, Configuration config, UddiEntityPublisher publisher) + throws DispositionReportFaultMessage { + + // A supplied bindingTemplate can't be null + if (bindingTemplate == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.bindingtemplate.NullInput")); + } + + // Retrieve the binding's passed key + String entityKey = bindingTemplate.getBindingKey(); + if (entityKey != null && entityKey.length() > 0) { + // Per section 4.4: keys must be case-folded + entityKey = entityKey.toLowerCase(); + bindingTemplate.setBindingKey(entityKey); + validateKeyLength(entityKey); + } + + // The parent key is either supplied or provided by the higher call to the parent entity save. If it is provided in both instances, if they differ, an + // error occurs. + String parentKey = bindingTemplate.getServiceKey(); + if (parentKey != null && parentKey.length() > 0) { + // Per section 4.4: keys must be case-folded + parentKey = parentKey.toLowerCase(); + bindingTemplate.setServiceKey(parentKey); + } + + if (parent != null) { + if (parentKey != null && parentKey.length() > 0) { + if (!parentKey.equalsIgnoreCase(parent.getServiceKey())) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.bindingtemplate.ParentMismatch", parentKey + ", " + parent.getBusinessKey())); + } + } else { + parentKey = parent.getServiceKey(); + } + } + + boolean entityExists = false; + if (entityKey == null || entityKey.length() == 0) { + validateNotSigned(bindingTemplate); + KeyGenerator keyGen = KeyGeneratorFactory.getKeyGenerator(); + entityKey = keyGen.generate(publisher); + bindingTemplate.setBindingKey(entityKey); + } else { + + Object obj = em.find(org.apache.juddi.model.BindingTemplate.class, entityKey); + if (obj != null) { + entityExists = true; + + org.apache.juddi.model.BindingTemplate bt = (org.apache.juddi.model.BindingTemplate) obj; + + // If the object exists, and the parentKey was not found to this point, then a save on an existing binding with a blank + // service key has occurred. It is set here and added to the entity being saved - a necessary step for the object to be + // persisted properly. (This condition makes some validation tests below unnecessary as the parent is "verified" but it's OK to + // still run them). + if (parentKey == null || parentKey.length() == 0) { + parentKey = bt.getBusinessService().getEntityKey(); + bindingTemplate.setServiceKey(parentKey); + } + + // If existing binding trying to be saved has a different parent key, then we have a problem + // TODO: moving bindings is allowed according to spec? + if (!parentKey.equalsIgnoreCase(bt.getBusinessService().getEntityKey())) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.bindingtemplate.ParentMismatch", parentKey + ", " + bt.getBusinessService().getEntityKey())); + } + + // Make sure publisher owns this entity. + AccessCheck(obj, entityKey); + //if (!publisher.isOwner((UddiEntity) obj)&& !((Publisher) publisher).isAdmin()) { +// throw new UserMismatchException(new ErrorMessage("errors.usermismatch.InvalidOwner", entityKey)); + // } + + } else { + // Inside this block, we have a key proposed by the publisher on a new entity + + // Validate key and then check to see that the proposed key is valid for this publisher + ValidateUDDIKey.validateUDDIv3Key(entityKey); + if (!publisher.isValidPublisherKey(em, entityKey)) { + throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", entityKey)); + } + + } + + } + + // Parent key must be passed if this is a new entity + if (!entityExists) { + if (parentKey == null || parentKey.length() == 0) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ParentServiceNotFound", parentKey)); + } + } + + // If parent key IS passed, whether new entity or not, it must be valid. Additionally, the current publisher must be the owner of the parent. Note that + // if a parent ENTITY was passed in, then we don't need to check for any of this since this is part of a higher call. + if (parentKey != null) { + if (parent == null) { + Object parentTemp = em.find(org.apache.juddi.model.BusinessService.class, parentKey); + if (parentTemp == null) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ParentBusinessNotFound", parentKey)); + } else if (!(parentTemp instanceof org.apache.juddi.model.BusinessService)) { + //JUDDI-848 + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ParentBusinessNotFound", parentKey)); + } + + // Make sure publisher owns this parent entity. + AccessCheck(parentTemp, parentKey); +// if (!publisher.isOwner((UddiEntity) parentTemp)) { +// throw new UserMismatchException(new ErrorMessage("errors.usermismatch.InvalidOwnerParent", parentKey)); +// } + + } + } + + if (!entityExists) { + // Check to make sure key isn't used by another entity. + if (!isUniqueKey(em, entityKey)) { + throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.KeyExists", entityKey)); + } + } + + //was TODO validate "checked" categories or category groups (see section 5.2.3 of spec)? optional to support + //at least one must be defined + if (bindingTemplate.getAccessPoint() == null && bindingTemplate.getHostingRedirector() == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.bindingtemplate.NoAccessPoint")); + } + //but not both + if (bindingTemplate.getAccessPoint() != null && bindingTemplate.getHostingRedirector() != null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.bindingtemplate.NoAccessPoint")); + } + validateCategoryBag(bindingTemplate.getCategoryBag(), config, false); + validateTModelInstanceDetails(bindingTemplate.getTModelInstanceDetails(), config, false); + validateAccessPoint(em, bindingTemplate.getAccessPoint(), config); + validateDescriptions(bindingTemplate.getDescription()); + validateHostingRedirector(em, bindingTemplate.getHostingRedirector(), config); + + validateSignaturesBinding(bindingTemplate, config); + //validateCheckedTModels(bindingTemplate, config); + } + + public void validateTModel(EntityManager em, org.uddi.api_v3.TModel tModel, Configuration config, UddiEntityPublisher publisher) throws DispositionReportFaultMessage { + // A supplied tModel can't be null + if (tModel == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.tmodel.NullInput")); + } + + boolean entityExists = false; + String entityKey = tModel.getTModelKey(); + if (entityKey == null || entityKey.length() == 0) { + KeyGenerator keyGen = KeyGeneratorFactory.getKeyGenerator(); + entityKey = keyGen.generate(publisher); + validateNotSigned(tModel); + tModel.setTModelKey(entityKey); + } else { + // Per section 4.4: keys must be case-folded + entityKey = entityKey.toLowerCase(); + tModel.setTModelKey(entityKey); + + Object obj = em.find(org.apache.juddi.model.Tmodel.class, entityKey); + if (obj != null) { + entityExists = true; + + // Make sure publisher owns this entity. + AccessCheck(obj, entityKey); + //if (!publisher.isOwner((UddiEntity) obj)&& !((Publisher) publisher).isAdmin()) { + // throw new UserMismatchException(new ErrorMessage("errors.usermismatch.InvalidOwner", entityKey)); + // } + } else { + // Inside this block, we have a key proposed by the publisher on a new entity + + // First test to see if this is a Key Generator tModel. The keyGenerator suffix appearing in the key is the indicator, since this is not + // allowed *unless* it's a key generator. + if (entityKey.toUpperCase().contains(KeyGenerator.KEYGENERATOR_SUFFIX.toUpperCase())) { + ValidateUDDIKey.validateUDDIv3KeyGeneratorTModel(tModel); + + // The root publisher is only allowed one key generator. This is published in the installation. + String rootPublisherStr = "root"; + try { + rootPublisherStr = AppConfig.getConfiguration().getString(Property.JUDDI_ROOT_PUBLISHER); + } catch (ConfigurationException ce) { + log.error("Could not read the root publisher setting in the configuration."); + } + if (publisher.getAuthorizedName().equals(rootPublisherStr)) { + throw new FatalErrorException(new ErrorMessage("errors.tmodel.keygenerator.RootKeyGen")); + } + + // It's a valid Key Generator, but is it available for this publisher? + if (!publisher.isKeyGeneratorAvailable(em, entityKey)) { + throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", entityKey)); + } + + } else { + // If not a key generator, then simply validate key and then check to see that the proposed key is valid for this publisher + ValidateUDDIKey.validateUDDIv3Key(entityKey); + //fix for JUDDI-851 + if (!entityKey.toUpperCase().startsWith("UUID:")) { + if (!publisher.isValidPublisherKey(em, entityKey)) { + throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", entityKey)); + } + } + } + } + } + + if (!entityExists) { + // Check to make sure key isn't used by another entity. + if (!isUniqueKey(em, entityKey)) { + throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.KeyExists", entityKey)); + } + } + validateKeyLength(entityKey); + + // TODO: validate "checked" categories or category groups (see section 5.2.3 of spec)? optional to support + if (tModel.getName() == null || tModel.getName().getValue() == null + || tModel.getName().getValue().equals("")) { + throw new ValueNotAllowedException(new ErrorMessage("errors.tmodel.NoName")); + } + + validateCategoryBag(tModel.getCategoryBag(), config, false); + validateIdentifierBag(tModel.getIdentifierBag(), config, false); + validateDescriptions(tModel.getDescription()); + validateNameLength(tModel.getName().getValue()); + validateLang(tModel.getName().getLang()); + List overviewDocList = tModel.getOverviewDoc(); + if (overviewDocList != null) { + for (org.uddi.api_v3.OverviewDoc overviewDoc : overviewDocList) { + validateOverviewDoc(overviewDoc); + } + } + validateSignaturesTModel(tModel, config); + + } + + public void validatePublisherAssertion(EntityManager em, org.uddi.api_v3.PublisherAssertion pubAssertion) throws DispositionReportFaultMessage { + // A supplied publisher assertion can't be null + if (pubAssertion == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.pubassertion.NullInput")); + } + + // The keyedRef must not be blank and every field must contain data. + org.uddi.api_v3.KeyedReference keyedRef = pubAssertion.getKeyedReference(); + if (keyedRef == null + || keyedRef.getTModelKey() == null || keyedRef.getTModelKey().length() == 0 + || keyedRef.getKeyName() == null || keyedRef.getKeyName().length() == 0 + || keyedRef.getKeyValue() == null || keyedRef.getKeyValue().length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.pubassertion.BlankKeyedRef")); + } + + String fromKey = pubAssertion.getFromKey(); + if (fromKey == null || fromKey.length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.pubassertion.BlankFromKey")); + } + + String toKey = pubAssertion.getToKey(); + if (toKey == null || toKey.length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.pubassertion.BlankToKey")); + } + + if (fromKey.equalsIgnoreCase(toKey)) { + throw new ValueNotAllowedException(new ErrorMessage("errors.pubassertion.SameBusinessKey")); + } + + // Per section 4.4: keys must be case-folded + fromKey = fromKey.toLowerCase(); + pubAssertion.setFromKey(fromKey); + toKey = toKey.toLowerCase(); + pubAssertion.setToKey(toKey); + validateKeyLength(toKey); + validateKeyLength(fromKey); + Object fromObj = em.find(org.apache.juddi.model.BusinessEntity.class, fromKey); + if (fromObj == null) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BusinessNotFound", fromKey)); + } + + Object toObj = em.find(org.apache.juddi.model.BusinessEntity.class, pubAssertion.getToKey()); + if (toObj == null) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BusinessNotFound", toKey)); + } + + if (!publisher.isOwner((UddiEntity) fromObj) && !publisher.isOwner((UddiEntity) toObj)) { + throw new UserMismatchException(new ErrorMessage("errors.pubassertion.UserMismatch", fromKey + " & " + toKey)); + } + + try { + validateKeyedReference(pubAssertion.getKeyedReference(), AppConfig.getConfiguration(), false); + } catch (ConfigurationException ce) { + log.error("Could not optain config. " + ce.getMessage(), ce); + } + } + + public void validateNames(List names) throws DispositionReportFaultMessage { + // At least one name is required + if (names == null || names.size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.names.NoInput")); + } + + for (Name n : names) { + if (n.getValue() == null || n.getValue().length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.names.NoValue")); + } + validateNameLength(n.getValue()); + validateLang(n.getLang()); + } + + } + + public void validateContacts(org.uddi.api_v3.Contacts contacts, Configuration config) throws DispositionReportFaultMessage { + // Contacts is optional + if (contacts == null) { + return; + } + + // If contacts do exist, at least one contact is required + List contactList = contacts.getContact(); + if (contactList == null || contactList.size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.contacts.NoInput")); + } + + for (org.uddi.api_v3.Contact contact : contactList) { + validateContact(contact, config); + } + + } + + public void validateContact(org.uddi.api_v3.Contact contact, Configuration config) throws DispositionReportFaultMessage { + if (log.isDebugEnabled()) { + log.debug("validateContact"); + } + // A supplied contact can't be null + if (contact == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.contact.NullInput")); + } + + // At least one personName is required + List pnameList = contact.getPersonName(); + if (pnameList == null || pnameList.size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.contact.NoPersonName")); + } + for (org.uddi.api_v3.PersonName pn : pnameList) { + if (pn.getValue() == null || pn.getValue().length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.contacts.NoPersonName")); + } + validateNameLength(pn.getValue()); + validateLang(pn.getLang()); + } + + List addressList = contact.getAddress(); + if (addressList != null) { + for (org.uddi.api_v3.Address address : addressList) { + if (address != null) { + validateSortCode(address.getSortCode()); + validateKeyLength(address.getTModelKey()); + validateLang(address.getLang()); + validateUseType(address.getUseType()); + boolean checked = true; + // Per section 4.4: keys must be case-folded + if (address.getTModelKey() != null) { + address.setTModelKey(address.getTModelKey().toLowerCase()); + validatedAddressLinesIfKeyDefined(address.getAddressLine()); + + checked = verifyTModelKeyExistsAndChecked(address.getTModelKey(), config); + + } + if (address.getAddressLine() == null || address.getAddressLine().size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.contact.NoAddressLine")); + } + + if (checked) { + validateAddressLines(address.getAddressLine(), config); + } + } + } + } + validateEmailAddress(contact.getEmail()); + validatePhone(contact.getPhone()); + validateDescriptions(contact.getDescription()); + validateUseType(contact.getUseType()); + } + + public void validateDiscoveryUrls(org.uddi.api_v3.DiscoveryURLs discUrls) throws DispositionReportFaultMessage { + // Discovery Urls is optional + if (discUrls == null) { + return; + } + + // If discUrls does exist, it must have at least one element + List discUrlList = discUrls.getDiscoveryURL(); + if (discUrlList == null || discUrlList.size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.discurls.NoInput")); + } + for (org.uddi.api_v3.DiscoveryURL url : discUrlList) { + if (url.getValue() == null || url.getValue().length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.discurls.NoInput")); + } + validateDiscoveryUrlLength(url); + } + } + + public void validateCategoryBag(org.uddi.api_v3.CategoryBag categories, Configuration config, boolean isRoot) throws DispositionReportFaultMessage { + + // Category bag is optional + if (categories == null) { + return; + } + + // If category bag does exist, it must have at least one element + List elems = categories.getKeyedReference(); + List groups = categories.getKeyedReferenceGroup(); + if (groups.size() == 0 && elems.size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.categorybag.NoInput")); + } + + for (KeyedReferenceGroup group : groups) { + validateKeyedReferenceGroup(group, config, isRoot); + } + + for (KeyedReference elem : elems) { + validateKeyedReference(elem, config, isRoot); + } + } + + public void validateIdentifierBag(org.uddi.api_v3.IdentifierBag identifiers, Configuration config, boolean isRoot) throws DispositionReportFaultMessage { + + // Identifier bag is optional + if (identifiers == null) { + return; + } + + // If category bag does exist, it must have at least one element + List keyedRefList = identifiers.getKeyedReference(); + if (keyedRefList == null || keyedRefList.size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.identifierbag.NoInput")); + } + + for (org.uddi.api_v3.KeyedReference keyedRef : keyedRefList) { + validateKeyedReference(keyedRef, config, isRoot); + } + } + + public void validateKeyedReferenceGroup(KeyedReferenceGroup krg, Configuration config, boolean isRoot) throws DispositionReportFaultMessage { + // Keyed reference groups must contain a tModelKey + if (log.isDebugEnabled()) { + log.debug("validateKeyedReferenceGroup"); + } + if (krg.getTModelKey() == null || krg.getTModelKey().length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.keyedreference.NoTModelKey")); + } + + // Per section 4.4: keys must be case-folded + String tmodelKey = krg.getTModelKey().toLowerCase(); + krg.setTModelKey(tmodelKey); + validateKeyLength(tmodelKey); + + boolean checkRef = false; + try { + checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false); + } catch (Exception ex) { + log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file", ex); + } + if (checkRef && !isRoot) { + this.verifyTModelKeyExists(tmodelKey); + } + + boolean checked = verifyTModelKeyExistsAndChecked(tmodelKey, config); + + if (checked) { + List keyedRefs = krg.getKeyedReference(); + // Should being empty raise an error? + if (keyedRefs != null && keyedRefs.size() > 0) { + for (KeyedReference keyedRef : keyedRefs) { + validateKeyedReference(keyedRef, config, isRoot); + } + } + } + } + + /** + * + * @param kr + * @param config + * @param isRoot true during install time, otherwise false + * @throws DispositionReportFaultMessage + */ + public void validateKeyedReference(KeyedReference kr, Configuration config, boolean isRoot) throws DispositionReportFaultMessage { + if (log.isDebugEnabled()) { + log.debug("validateKeyedReference"); + } + String tmodelKey = kr.getTModelKey(); + + if (tmodelKey == null || tmodelKey.length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.keyedreference.NoTModelKey")); + } + + // Per section 4.4: keys must be case-folded + tmodelKey = tmodelKey.toLowerCase(); + kr.setTModelKey(tmodelKey); + validateKeyLength(tmodelKey); + + if (kr.getKeyValue() == null || kr.getKeyValue().length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.keyedreference.NoKeyValue")); + } + validateKeyValue(kr.getKeyValue()); + validateKeyName(kr.getKeyName()); + + boolean checkRef = false; + try { + checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false); + } catch (Exception ex) { + log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file", ex); + } + if (checkRef && !isRoot) { + this.verifyTModelKeyExists(tmodelKey); + + } + + String rootPublisherStr = config.getString(Property.JUDDI_ROOT_PUBLISHER); + // Per section 6.2.2.1 of the specification, no publishers (except the root) are allowed to use the node categorization tmodelKey + if (Constants.NODE_CATEGORY_TMODEL.equalsIgnoreCase(kr.getTModelKey())) { + if (!rootPublisherStr.equals(publisher.getAuthorizedName())) { + throw new ValueNotAllowedException(new ErrorMessage("errors.keyedreference.NodeCategoryTModel", Constants.NODE_CATEGORY_TMODEL)); + } + } + } + + public void validateTModelInstanceDetails(org.uddi.api_v3.TModelInstanceDetails tmodelInstDetails, Configuration config, boolean isRoot) throws DispositionReportFaultMessage { + if (log.isDebugEnabled()) { + log.debug("validateTModelInstanceDetails"); + } + // tModel Instance Details is optional + if (tmodelInstDetails == null) { + return; + } + + // If tmodelInstDetails does exist, it must have at least one element + List tmodelInstInfoList = tmodelInstDetails.getTModelInstanceInfo(); + if (tmodelInstInfoList == null || tmodelInstInfoList.size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.tmodelinstdetails.NoInput")); + } + + for (org.uddi.api_v3.TModelInstanceInfo tmodelInstInfo : tmodelInstInfoList) { + validateTModelInstanceInfo(tmodelInstInfo, config, isRoot); + } + } + + public void validateTModelInstanceInfo(org.uddi.api_v3.TModelInstanceInfo tmodelInstInfo, Configuration config, boolean isRoot) throws DispositionReportFaultMessage { + // tModel Instance Info can't be null + if (tmodelInstInfo == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.tmodelinstinfo.NullInput")); + } + + // TModel key is required + if (tmodelInstInfo.getTModelKey() == null || tmodelInstInfo.getTModelKey().length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.tmodelinstinfo.NoTModelKey")); + } + + // Per section 4.4: keys must be case-folded + tmodelInstInfo.setTModelKey((tmodelInstInfo.getTModelKey().toLowerCase())); + + boolean checkRef = false; + try { + checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false); + } catch (Exception ex) { + log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file", ex); + } + if (checkRef && !isRoot) { + this.verifyTModelKeyExists(tmodelInstInfo.getTModelKey()); + } + + validateInstanceDetails(tmodelInstInfo.getInstanceDetails()); + if (log.isDebugEnabled()) { + log.debug("validateTModelInstanceInfo"); + } + + validateKeyLength(tmodelInstInfo.getTModelKey()); + validateDescriptions(tmodelInstInfo.getDescription()); + + } + + public void validateInstanceDetails(org.uddi.api_v3.InstanceDetails instDetails) throws DispositionReportFaultMessage { + // Instance Details is optional + if (instDetails == null) { + return; + } + + // At least one OverviewDoc or instanceParms must be supplied + List elems = instDetails.getOverviewDoc(); + if (instDetails.getInstanceParms() == null && elems.size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.instdetails.NoOverviewOrParms")); + } + for (int i = 0; i < elems.size(); i++) { + validateDescriptions(elems.get(i).getDescription()); + validateOverviewURL(elems.get(i).getOverviewURL()); + } + if (instDetails.getInstanceParms()!=null){ + if (instDetails.getInstanceParms().length()>8192){ + throw new ValueNotAllowedException(new ErrorMessage("errors.instdetails.MaxLength",instDetails.getInstanceParms().length()+"")); + } + } + } + + public void validateOverviewDoc(org.uddi.api_v3.OverviewDoc overviewDoc) throws DispositionReportFaultMessage { + // OverviewDoc can't be null + if (overviewDoc == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.overviewdoc.NullInput")); + } + + // At least one description or overview URL must be supplied + List elems = overviewDoc.getDescription(); + if ((elems == null || elems.size() == 0) && overviewDoc.getOverviewURL() == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.overviewdoc.NoDescOrUrl")); + } + for (int i = 0; i < elems.size(); i++) { + validateLang(elems.get(i).getLang()); + validateURL(elems.get(i).getValue()); + } + } + + public void validateRegisteredInfo(org.uddi.api_v3.GetRegisteredInfo body) throws DispositionReportFaultMessage { + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + // infoSelection is required + if (body.getInfoSelection() == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.getregisteredinfo.NoInfoSelection")); + } + + } + + /** + * Publishing API functions are specific to jUDDI. Requires + * administrative privilege + * + * @param em + * @param body + * @throws DispositionReportFaultMessage + */ + public void validateDeletePublisher(EntityManager em, DeletePublisher body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + // No null or empty list + List entityKeyList = body.getPublisherId(); + if (entityKeyList == null || entityKeyList.size() == 0) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); + } + + if (!((Publisher) publisher).isAdmin()) { + throw new UserMismatchException(new ErrorMessage("errors.deletepublisher.AdminReqd")); + } + + HashSet dupCheck = new HashSet(); + for (String entityKey : entityKeyList) { + validateKeyLength(entityKey); + boolean inserted = dupCheck.add(entityKey); + if (!inserted) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); + } + + Object obj = em.find(org.apache.juddi.model.Publisher.class, entityKey); + if (obj == null) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.PublisherNotFound", entityKey)); + } + + } + } + + public void validateSaveSubscriptionAdmin(EntityManager em, String publisherOrUsername, List subscriptions) throws DispositionReportFaultMessage { + + // No null input + if (subscriptions == null || subscriptions.isEmpty()) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + if (!((Publisher) publisher).isAdmin()) { + throw new UserMismatchException(new ErrorMessage("errors.deletepublisher.AdminReqd")); + } + UddiEntityPublisher user = new UddiEntityPublisher(publisherOrUsername); + ValidateSubscription vsub = new ValidateSubscription(user); + for (int i = 0; i < subscriptions.size(); i++) { + vsub.validateSubscriptions(em, subscriptions, user); + } + } + + public void validateSavePublisher(EntityManager em, SavePublisher body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + // No null or empty list + List entityList = body.getPublisher(); + if (entityList == null || entityList.size() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.savepublisher.NoInput")); + } + + if (!((Publisher) publisher).isAdmin()) { + throw new UserMismatchException(new ErrorMessage("errors.savepublisher.AdminReqd", publisher.getAuthorizedName())); + } + + for (org.apache.juddi.api_v3.Publisher entity : entityList) { + validatePublisher(em, entity); + } + } + + public void validatePublisher(EntityManager em, org.apache.juddi.api_v3.Publisher publisher) throws DispositionReportFaultMessage { + + // No null input + if (publisher == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.publisher.NullInput")); + } + + String authorizedName = publisher.getAuthorizedName(); + if (authorizedName == null || authorizedName.length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.publisher.NoAuthorizedName")); + } + + String publisherName = publisher.getPublisherName(); + if (publisherName == null || publisherName.length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.publisher.NoPublisherName")); + } +//TODO identify JUDDI restrictions on publisher name + } + + public void validateAdminDeleteTModel(EntityManager em, DeleteTModel body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) { + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + } + + // No null or empty list + List entityKeyList = body.getTModelKey(); + if (entityKeyList == null || entityKeyList.size() == 0) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); + } + + if (!((Publisher) publisher).isAdmin()) { + throw new UserMismatchException(new ErrorMessage("errors.AdminReqd")); + } + + HashSet dupCheck = new HashSet(); + for (String entityKey : entityKeyList) { + validateKeyLength(entityKey); + boolean inserted = dupCheck.add(entityKey); + if (!inserted) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); + } + + //removed a check for checking if the entity exists which was moved to the juddi api class + //why? because we were looking up the same object twice in the database and its just not efficient + } + } + //////////////////////////////////////////////////////////////////// + ////////////////////////// begin validation code + //////////////////////////////////////////////////////////////////// + + private static void validateDescription(String value) throws ValueNotAllowedException { + if (value != null && value.length() > ValidationConstants.MAX_description) { + throw new ValueNotAllowedException(new ErrorMessage("errors.DescriptionTooLong")); + } + } + + public static void validateLang(String lang) throws ValueNotAllowedException { + if (lang != null && lang.length() > ValidationConstants.MAX_xml_lang) { + throw new ValueNotAllowedException(new ErrorMessage("errors.names.LangTooLong")); + } + } + + private static void validateUseType(String useType) throws ValueNotAllowedException { + if (useType != null && useType.length() > ValidationConstants.MAX_useType) { + throw new ValueNotAllowedException(new ErrorMessage("errors.names.UseTypeTooLong")); + } + } + + public static void validateKeyLength(String value) throws ValueNotAllowedException { + if (value != null && value.length() > ValidationConstants.MAX_Key) { + throw new ValueNotAllowedException(new ErrorMessage("errors.keys.TooLong")); + } + } + + private void validateAccessPoint(EntityManager em, AccessPoint value, Configuration config) throws ValueNotAllowedException { + if (log.isDebugEnabled()) { + log.debug("validateAccessPoint"); + } + + if (value != null) { + if (value.getValue().length() > ValidationConstants.MAX_accessPoint) { + throw new ValueNotAllowedException(new ErrorMessage("errors.accessPoint.TooLong")); + } + + validateUseType(value.getUseType()); + if (value.getUseType() != null) { + if (value.getUseType().equalsIgnoreCase(AccessPointType.BINDING_TEMPLATE.toString())) { + //validate that the referenced binding key exists already + Object obj = em.find(org.apache.juddi.model.BindingTemplate.class, value.getValue()); + if (obj == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.accessPoint.bindingtemplateRedirect.keynotexist")); + } + + } else if (value.getUseType().equalsIgnoreCase(AccessPointType.HOSTING_REDIRECTOR.toString())) { + try { + //no validation necessary other than confirm that it's a URL + new URL(value.getValue()); + } catch (MalformedURLException ex) { + throw new ValueNotAllowedException(new ErrorMessage("errors.accessPoint.hostingRedirector.notaurl")); + } + } + //TODO determine if additional validation is required. + //potentials, if its a wsdl deployment, is the Value a valid URI + //if endpoint, is it a valid URI? + } + } + } + + private void validateHostingRedirector(EntityManager em, HostingRedirector hostingRedirector, Configuration config) throws ValueNotAllowedException { + if (log.isDebugEnabled()) { + log.debug("validateHostingRedirector"); + } + if (hostingRedirector == null) { + return; + } + + if (hostingRedirector.getBindingKey() == null || hostingRedirector.getBindingKey().length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.hostingredirector.noinput")); + } + if (hostingRedirector.getBindingKey().length() > ValidationConstants.MAX_Key) { + throw new ValueNotAllowedException(new ErrorMessage("errors.hostingredirector.TooLong")); + } + boolean checkRef = false; + try { + checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false); + } catch (Exception ex) { + log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file", ex); + } + if (checkRef) { + //TODO check the spec to confirm this is logically correct + /*Object obj = em.find(org.apache.juddi.model.BindingTemplate.class, hostingRedirector.getBindingKey()); + if (obj == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.hostingredirector.keynotexist")); + }*/ + } + + } + + private void validateNameLength(String value) throws ValueNotAllowedException { + if (value == null || value.length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.names.NoInput")); + } + if (value.length() > ValidationConstants.MAX_name) { + throw new ValueNotAllowedException(new ErrorMessage("errors.names.TooLong")); + } + + } + + private void validateSortCode(String value) throws ValueNotAllowedException { + if (value != null && value.length() > ValidationConstants.MAX_sortCode) { + throw new ValueNotAllowedException(new ErrorMessage("errors.sortCode.TooLong")); + } + } + + private void validateAddressLines(List addressLine, Configuration config) throws ValueNotAllowedException { + if (log.isDebugEnabled()) { + log.debug("validateAddressLines"); + } + if (addressLine != null) { + for (int i = 0; i < addressLine.size(); i++) { + validateKeyName(addressLine.get(i).getKeyName()); + verifyTModelKeyExistsAndChecked(addressLine.get(i).getKeyName(), config); + + validateKeyValue(addressLine.get(i).getKeyValue()); + if (addressLine.get(i).getValue() == null || addressLine.get(i).getValue().length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.addressline.noinput")); + } + if (addressLine.get(i).getValue().length() > ValidationConstants.MAX_addressLine) { + throw new ValueNotAllowedException(new ErrorMessage("errors.addressline.TooLong")); + } + } + } + } + + private void validateEmailAddress(List email) throws ValueNotAllowedException { + if (email != null) { + for (int i = 0; i < email.size(); i++) { + validateUseType(email.get(i).getUseType()); + if (email.get(i).getValue() == null || email.get(i).getValue().length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.email.noinput")); + } + if (email.get(i).getValue().length() > ValidationConstants.MAX_email) { + throw new ValueNotAllowedException(new ErrorMessage("errors.email.TooLong")); + } + } + } + } + + private void validatePhone(List phone) throws ValueNotAllowedException { + if (phone != null) { + for (int i = 0; i < phone.size(); i++) { + validateUseType(phone.get(i).getUseType()); + if (phone.get(i).getValue() == null + || phone.get(i).getValue().length() == 0) { + throw new ValueNotAllowedException(new ErrorMessage("errors.phone.noinput")); + } + if (phone.get(i).getValue().length() > ValidationConstants.MAX_phone) { + throw new ValueNotAllowedException(new ErrorMessage("errors.phone.TooLong")); + } + } + } + } + + private void validateDiscoveryUrlLength(DiscoveryURL url) throws ValueNotAllowedException { + if (url != null) { + validateUseType(url.getUseType()); + validateURL(url.getValue()); + } + } + + private void validateKeyValue(String value) throws ValueNotAllowedException { + if (value != null && value.length() > ValidationConstants.MAX_keyValue) { + throw new ValueNotAllowedException(new ErrorMessage("errors.keyvalue.TooLong")); + } + } + + private void validateKeyName(String value) throws ValueNotAllowedException { + if (value != null && value.length() > ValidationConstants.MAX_keyValue) { + throw new ValueNotAllowedException(new ErrorMessage("errors.keyname.TooLong")); + } + + } + + private void validateDescriptions(List description) throws ValueNotAllowedException { + for (int i = 0; i < description.size(); i++) { + if (description.get(i).getValue() == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.contact.EmptyDescription")); + } + + validateLang(description.get(i).getLang()); + validateDescription(description.get(i).getValue()); + } + } + + private void validateOverviewURL(OverviewURL overviewURL) throws ValueNotAllowedException { + if (overviewURL != null) { + validateUseType(overviewURL.getUseType()); + validateURL(overviewURL.getValue()); + } + } + + private void validateURL(String value) throws ValueNotAllowedException { + if (value != null && value.length() > ValidationConstants.MAX_overviewURL) { + throw new ValueNotAllowedException(new ErrorMessage("errors.url.overviewTooLong")); + } + } + + /** + * Validates that a tmodel key is registered Alex O'Ree + * + * @param tmodelKey + * @param em + * @throws ValueNotAllowedException + * @see org.apache.juddi.config.Install + * @since 3.1.5 + */ + private boolean verifyTModelKeyExistsAndChecked(String tmodelKey, Configuration config) throws ValueNotAllowedException { + boolean checked = true; + if (tmodelKey == null || tmodelKey.length() == 0) { + return false; + } + if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:categorization:types")) { + return false; + } + if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:categorization:nodes")) { + return false; + } + if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_inquiry")) { + return false; + } + if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_publication")) { + return false; + } + if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_security")) { + return false; + } + if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_ownership_transfer")) { + return false; + } + if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_subscription")) { + return false; + } + if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_subscriptionlistener")) { + return false; + } + + if (config == null) { + log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullConfig")); + return false; + } + boolean checkRef = false; + try { + checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false); + } catch (Exception ex) { + log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file", ex); + } + if (checkRef) { + if (log.isDebugEnabled()) { + log.debug("verifyTModelKeyExists " + tmodelKey); + } + EntityManager em = PersistenceManager.getEntityManager(); + + if (em == null) { + //this is normally the Install class firing up + log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullEM")); + } else { + //Collections.sort(buildInTmodels); + //if ((buildInTmodels, tmodelKey) == -1) + Tmodel modelTModel = null; + { + EntityTransaction tx = em.getTransaction(); + try { + + tx.begin(); + modelTModel = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey); + + if (modelTModel == null) { + checked = false; + } else { + if (modelTModel.getCategoryBag()!=null) + for (org.apache.juddi.model.KeyedReference ref : modelTModel.getCategoryBag().getKeyedReferences()) { + if ("uddi-org:types:unchecked".equalsIgnoreCase(ref.getKeyName())) { + checked = false; + break; + } + } + } + + tx.commit(); + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + if (modelTModel == null) { + throw new ValueNotAllowedException(new ErrorMessage("errors.tmodel.ReferencedKeyDoesNotExist", tmodelKey)); + } + } + } + } + return checked; + } + + private boolean verifyTModelKeyChecked(Tmodel modelTModel) { + boolean checked = true; + if (modelTModel == null) { + checked = false; + } else { + for (org.apache.juddi.model.KeyedReference ref : modelTModel.getCategoryBag().getKeyedReferences()) { + if ("uddi-org:types:unchecked".equalsIgnoreCase(ref.getTmodelKeyRef())) { + checked = false; + break; + } + } + } + return checked; + } + + /** + * throws if it doesn't exist, returns it if it does + * + * @param tmodelKey + * @return null, or a TModel object + * @throws ValueNotAllowedException + * @since 3.3 + */ + private TModel verifyTModelKeyExists(String tmodelKey) throws ValueNotAllowedException, DispositionReportFaultMessage { + TModel api = null; + EntityManager em = PersistenceManager.getEntityManager(); + boolean found = false; + if (em == null) { + log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullEM")); + } else { + Tmodel modelTModel = null; + { + EntityTransaction tx = em.getTransaction(); + try { + + tx.begin(); + modelTModel = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey); + + if (modelTModel != null) { + found = true; + api = new TModel(); + MappingModelToApi.mapTModel(modelTModel, api); + } + tx.commit(); + + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + } + } + if (!found) { + throw new ValueNotAllowedException(new ErrorMessage("errors.tmodel.ReferencedKeyDoesNotExist", tmodelKey)); + } + return api; + } + + private List GetBindingKeysCheckedTModelKeyedReferenceBT(Map cache, List obj) { + List ret = new ArrayList(); + + if (obj == null) { + return ret; + } + for (BindingTemplate bt : obj) { + if (bt.getCategoryBag() != null) { + for (int i = 0; i < bt.getCategoryBag().getKeyedReference().size(); i++) { + ret.addAll(GetBindingKeysCheckedTModelKeyedReference(cache, bt.getCategoryBag().getKeyedReference().get(i))); + } + } + } + + return ret; + } + + private List GetBindingKeysCheckedTModelKeyedReferenceBS(Map cache, List obj) { + List ret = new ArrayList(); + + if (obj == null) { + return ret; + } + for (BusinessService bt : obj) { + if (bt.getCategoryBag() != null) { + for (int i = 0; i < bt.getCategoryBag().getKeyedReference().size(); i++) { + ret.addAll(GetBindingKeysCheckedTModelKeyedReference(cache, bt.getCategoryBag().getKeyedReference().get(i))); + } + } + if (bt.getBindingTemplates() != null) { + ret.addAll(GetBindingKeysCheckedTModelKeyedReferenceBT(cache, bt.getBindingTemplates().getBindingTemplate())); + } + } + + return ret; + } + + private List GetBindingKeysCheckedTModelKeyedReferenceBE(Map cache, List obj) { + List ret = new ArrayList(); + + if (obj == null) { + return ret; + } + for (BusinessEntity bt : obj) { + if (bt.getCategoryBag() != null) { + for (int i = 0; i < bt.getCategoryBag().getKeyedReference().size(); i++) { + ret.addAll(GetBindingKeysCheckedTModelKeyedReference(cache, bt.getCategoryBag().getKeyedReference().get(i))); + } + } + if (bt.getIdentifierBag() != null) { + for (int i = 0; i < bt.getIdentifierBag().getKeyedReference().size(); i++) { + ret.addAll(GetBindingKeysCheckedTModelKeyedReference(cache, bt.getIdentifierBag().getKeyedReference().get(i))); + } + } + + if (bt.getBusinessServices() != null) { + ret.addAll(GetBindingKeysCheckedTModelKeyedReferenceBS(cache, bt.getBusinessServices().getBusinessService())); + } + } + return ret; + } + + private List GetBindingKeysCheckedTModelKeyedReferenceTM(Map cache, List obj) { + List ret = new ArrayList(); + + if (obj == null) { + return ret; + } + for (TModel bt : obj) { + if (bt.getCategoryBag() != null) { + for (int i = 0; i < bt.getCategoryBag().getKeyedReference().size(); i++) { + ret.addAll(GetBindingKeysCheckedTModelKeyedReference(cache, bt.getCategoryBag().getKeyedReference().get(i))); + } + } + if (bt.getIdentifierBag() != null) { + for (int i = 0; i < bt.getIdentifierBag().getKeyedReference().size(); i++) { + ret.addAll(GetBindingKeysCheckedTModelKeyedReference(cache, bt.getIdentifierBag().getKeyedReference().get(i))); + } + } + } + return ret; + } + + /** + * this should return a list of binding keys, only if the referenced kr + * contains is validated by + * + * @param cache + * @param get + * @return + */ + private List GetBindingKeysCheckedTModelKeyedReference(Map cache, KeyedReference get) { + List ret = new ArrayList(); + TModel ref = null; + log.debug("looking for is validated by for keyedref " + get.getTModelKey()); + if (cache.containsKey(get.getTModelKey())) { + ref = cache.get(get.getTModelKey()); + } + if (ref == null) { + try { + ref = verifyTModelKeyExists(get.getTModelKey()); + cache.put(get.getTModelKey(), ref); + } catch (Exception ex) { + log.error("unexpected error loading tmodel " + get.getTModelKey(), ex); + } + } + if (ref != null) { + + ret.addAll(TModelContains(UDDIConstants.IS_VALIDATED_BY, ref)); + ret.addAll(TModelContains(UDDIConstantsV2.IS_VALIDATED_BY, ref)); + + } + return ret; + } + + /** + * returns all keyvalues from ref.catbag and identbag where the tmodel + * key matches + * + * @param key + * @param ref + * @return + */ + private List TModelContains(String key, TModel ref) { + + if (key == null) { + return null; + } + if (ref == null || ref.getTModelKey()==null) { + return null; + } + log.debug("looking for key=" + key + " from tModel " + ref.getTModelKey()); + List ret = new ArrayList(); + + if (ref.getCategoryBag() != null) { + for (int i = 0; i < ref.getCategoryBag().getKeyedReference().size(); i++) { + if (ref.getCategoryBag().getKeyedReference().get(i).getTModelKey().equalsIgnoreCase(key)) { + log.debug("found reference for key=" + key + " from tModel " + ref.getTModelKey() + " validation endpoint " + ref.getCategoryBag().getKeyedReference().get(i).getKeyValue()); + ret.add(ref.getCategoryBag().getKeyedReference().get(i).getKeyValue()); + } + } + for (int i = 0; i < ref.getCategoryBag().getKeyedReferenceGroup().size(); i++) { + for (int k = 0; k < ref.getCategoryBag().getKeyedReferenceGroup().get(i).getKeyedReference().size(); k++) { + if (ref.getCategoryBag().getKeyedReferenceGroup().get(i).getKeyedReference().get(k).getTModelKey().equalsIgnoreCase(key)) { + log.debug("found reference for key=" + key + " from tModel " + ref.getTModelKey() + " validation endpoint " + ref.getCategoryBag().getKeyedReferenceGroup().get(i).getKeyedReference().get(k).getKeyValue()); + ret.add(ref.getCategoryBag().getKeyedReferenceGroup().get(i).getKeyedReference().get(k).getKeyValue()); + } + } + } + } + if (ref.getIdentifierBag() != null) { + for (int i = 0; i < ref.getIdentifierBag().getKeyedReference().size(); i++) { + if (ref.getIdentifierBag().getKeyedReference().get(i).getTModelKey().equalsIgnoreCase(key)) { + log.debug("found reference for key=" + key + " from tModel " + ref.getTModelKey() + " validation endpoint " + ref.getIdentifierBag().getKeyedReference().get(i).getKeyValue()); + ret.add(ref.getIdentifierBag().getKeyedReference().get(i).getKeyValue()); + } + } + } + return ret; + } + + /** + * JUDDI-849 Each addressLine element MAY be adorned with two optional + * descriptive attributes, keyName and keyValue. Both attributes MUST be + * present in each address line if a tModelKey is specified in the + * address structure. When no tModelKey is provided for the address + * structure, the keyName and keyValue attributes have no defined + * meaning. + * + * @param addressLine + */ + private void validatedAddressLinesIfKeyDefined(List addressLine) throws ValueNotAllowedException { + StringBuilder err = new StringBuilder(); + for (int i = 0; i < addressLine.size(); i++) { + + if (addressLine.get(i).getKeyName() == null + || addressLine.get(i).getKeyName().trim().length() == 0) { + err.append("addressLine(").append(i).append(").keyName,"); + } + if (addressLine.get(i).getKeyValue() == null + || addressLine.get(i).getKeyValue().trim().length() == 0) { + err.append("addressLine(").append(i).append(").keyValue,"); + } + if (addressLine.get(i).getValue() == null + || addressLine.get(i).getValue().trim().length() == 0) { + err.append("addressLine(").append(i).append(").value,"); + } + } + if (err.length() > 0) { + throw new ValueNotAllowedException(new ErrorMessage("E_invalidValueAddressLine", err.toString())); + } + } + + private void validateCheckedTModelsBT(List bindingTemplate, Configuration config) throws ValueNotAllowedException { + + boolean checkRef = false; + try { + checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false); + } catch (Exception ex) { + log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file", ex); + } + + if (!checkRef) { + return; + } + Map cache = new HashMap(); + List bindings = GetBindingKeysCheckedTModelKeyedReferenceBT(cache, bindingTemplate); + + if (!bindings.isEmpty()) { + //get a unique list + bindings = new ArrayList(new HashSet(bindings)); + for (int i = 0; i < bindings.size(); i++) { + //load binding from database + EntityManager em = PersistenceManager.getEntityManager(); + org.apache.juddi.model.BindingTemplate find = em.find(org.apache.juddi.model.BindingTemplate.class, bindings.get(i)); + if (find != null) { + //parse endpoint + String url = find.getAccessPointUrl(); + if (url == null) { + url = find.getHostingRedirector(); + } + if (url != null) { + //call ValidateValuesFromWebService + //optimization for localhost? + ValidateValuesFromWebService.ValidateBinding(Rectify(url, config), bindingTemplate); + } + + } + } + } + } + + private void validateCheckedTModelsBS(List bizlist, Configuration config) throws ValueNotAllowedException { + boolean checkRef = false; + try { + checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false); + } catch (Exception ex) { + log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file", ex); + } + if (!checkRef) { + return; + } + Map cache = new HashMap(); + List bindings = GetBindingKeysCheckedTModelKeyedReferenceBS(cache, bizlist); + + if (!bindings.isEmpty()) { + //get a unique list + bindings = new ArrayList(new HashSet(bindings)); + for (int i = 0; i < bindings.size(); i++) { + //load binding from database + EntityManager em = PersistenceManager.getEntityManager(); + org.apache.juddi.model.BindingTemplate find = em.find(org.apache.juddi.model.BindingTemplate.class, bindings.get(i)); + if (find != null) { + //parse endpoint + String url = find.getAccessPointUrl(); + if (url == null) { + url = find.getHostingRedirector(); + } + if (url != null) { + //call ValidateValuesFromWebService + //optimization for localhost? + ValidateValuesFromWebService.ValidateService(Rectify(url, config), bizlist); + } + + } + } + } + } + + private void validateCheckedTModelsBE(List entity, Configuration config) throws ValueNotAllowedException { + boolean checkRef = false; + try { + checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false); + } catch (Exception ex) { + log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file", ex); + } + if (!checkRef) { + return; + } + Map cache = new HashMap(); + List bindings = GetBindingKeysCheckedTModelKeyedReferenceBE(cache, entity); + + if (!bindings.isEmpty()) { + //get a unique list + bindings = new ArrayList(new HashSet(bindings)); + for (int i = 0; i < bindings.size(); i++) { + //load binding from database + EntityManager em = PersistenceManager.getEntityManager(); + org.apache.juddi.model.BindingTemplate find = em.find(org.apache.juddi.model.BindingTemplate.class, bindings.get(i)); + if (find != null) { + //parse endpoint + String url = find.getAccessPointUrl(); + if (url == null) { + url = find.getHostingRedirector(); + } + if (url != null) { + //call ValidateValuesFromWebService + //optimization for localhost? + ValidateValuesFromWebService.ValidateBusiness(Rectify(url, config), entity); + } + + } + } + } + } + + private void validateCheckedTModelsTM(List entity, Configuration config) throws ValueNotAllowedException { + boolean checkRef = false; + try { + checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false); + } catch (Exception ex) { + log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file", ex); + } + if (!checkRef) { + return; + } + Map cache = new HashMap(); + List bindings = GetBindingKeysCheckedTModelKeyedReferenceTM(cache, entity); + + if (!bindings.isEmpty()) { + //get a unique list + bindings = new ArrayList(new HashSet(bindings)); + for (int i = 0; i < bindings.size(); i++) { + //load binding from database + EntityManager em = PersistenceManager.getEntityManager(); + org.apache.juddi.model.BindingTemplate find = em.find(org.apache.juddi.model.BindingTemplate.class, bindings.get(i)); + if (find != null) { + //parse endpoint + String url = find.getAccessPointUrl(); + if (url == null) { + url = find.getHostingRedirector(); + } + if (url != null) { + log.debug("attempting vsv from " + url); + //call ValidateValuesFromWebService + //optimization for localhost? + ValidateValuesFromWebService.ValidateTModel(Rectify(url, config), entity); + } + + } + } + } + } + + private String Rectify(String url, Configuration config) { + //${juddi.server.baseurl} + Properties p = new Properties(); + p.put("juddi.server.baseurl", config.getString("juddi.server.baseurl", Property.DEFAULT_BASE_URL)); + + return TokenResolver.replaceTokens(url, p); + } + + public void validateDeleteNode(EntityManager em, DeleteNode nodeID, ReplicationConfiguration cfg) throws DispositionReportFaultMessage { + if (nodeID == null) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.deleteClerk.NoInput")); + } + if (!((Publisher) publisher).isAdmin()) { + throw new UserMismatchException(new ErrorMessage("errors.deletepublisher.AdminReqd")); + } + if (nodeID.getNodeID() == null || nodeID.getNodeID().trim().equalsIgnoreCase("")) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.deleteNode.NoInput")); + } + //get the latest replication config + if (cfg != null) { + if (cfg.getCommunicationGraph() != null) { + for (String node : cfg.getCommunicationGraph().getNode()) { + if (node.equals(nodeID.getNodeID())) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.deleteNode.InReplicationConfig", nodeID.getNodeID())); + } + } + for (int i = 0; i < cfg.getCommunicationGraph().getEdge().size(); i++) { + if (nodeID.getNodeID().equals(cfg.getCommunicationGraph().getEdge().get(i).getMessageReceiver())) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.deleteNode.InReplicationConfig", nodeID.getNodeID())); + } + if (nodeID.getNodeID().equals(cfg.getCommunicationGraph().getEdge().get(i).getMessageSender())) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.deleteNode.InReplicationConfig", nodeID.getNodeID())); + } + + } + } + } + + } + + public void validateDeleteClerk(EntityManager em, DeleteClerk clerkID) throws DispositionReportFaultMessage { + if (clerkID == null) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.deleteClerk.NoInput")); + } + if (!((Publisher) publisher).isAdmin()) { + throw new UserMismatchException(new ErrorMessage("errors.deletepublisher.AdminReqd")); + } + if (clerkID.getClerkID() == null || clerkID.getClerkID().trim().equalsIgnoreCase("")) { + throw new InvalidKeyPassedException(new ErrorMessage("errors.deleteClerk.NoInput")); + } + + } + + public void validateGetAllNodes() throws DispositionReportFaultMessage { + if (!((Publisher) publisher).isAdmin()) { + throw new UserMismatchException(new ErrorMessage("errors.deletepublisher.AdminReqd")); + } + } + + private org.apache.juddi.v3.client.cryptor.DigSigUtil ds = null; + + private synchronized void initDigSig(Configuration config) { + if (ds == null) { + + Properties p = new Properties(); + /** + * truststore.jks + * JKS + * password + * + * true + * true + * true + */ + p.put(DigSigUtil.TRUSTSTORE_FILE, config.getString(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_PREFIX + "trustStorePath", "")); + p.put(DigSigUtil.TRUSTSTORE_FILETYPE, config.getString(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_PREFIX + "trustStoreType", "")); + + String enc = config.getString(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_PREFIX + "trustStorePassword", ""); + if (config.getBoolean(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_PREFIX + "trustStorePassword[@isPasswordEncrypted]", false)) { + log.debug("trust password is encrypted, decrypting..."); + + String prov = config.getString(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_PREFIX + "trustStorePassword[@cryptoProvider]", ""); + try { + p.setProperty(DigSigUtil.TRUSTSTORE_FILE_PASSWORD, CryptorFactory.getCryptor(prov).decrypt(enc)); + } catch (Exception ex) { + log.warn("unable to decrypt trust store password " + ex.getMessage()); + log.debug("unable to decrypt trust store password " + ex.getMessage(), ex); + } + + } else if (!"".equals(enc)){ + log.warn("Hey, you should consider encrypting your trust store password!"); + p.setProperty(DigSigUtil.TRUSTSTORE_FILE_PASSWORD, enc); + } + + p.put(DigSigUtil.CHECK_REVOCATION_STATUS_CRL, config.getString(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_PREFIX + "checkRevocationCRL", "true")); + p.put(DigSigUtil.CHECK_TRUST_CHAIN, config.getString(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_PREFIX + "checkTrust", "true")); + p.put(DigSigUtil.CHECK_TIMESTAMPS, config.getString(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_PREFIX + "checkTimestamps", "true")); + + try { + ds = new DigSigUtil(p); + } catch (CertificateException ex) { + log.error("", ex); + } + //System.out.println("loaded from " + AppConfig.getConfigFileURL()); + //p.list(System.out); + } + } + + private void validateSignaturesBinding(BindingTemplate bindingTemplate, Configuration config) throws FatalErrorException { + boolean shouldcheck = config.getBoolean(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_ENABLE, false); + initDigSig(config); + if (shouldcheck && !bindingTemplate.getSignature().isEmpty() && ds != null) { + AtomicReference outmsg = new AtomicReference(); + boolean ok = ds.verifySignedUddiEntity(bindingTemplate, outmsg); + if (!ok) { + throw new FatalErrorException(new ErrorMessage("errors.digitalsignature.validationfailure", bindingTemplate.getBindingKey() + " " + outmsg.get())); + } + + } + } + + private void validateSignaturesService(BusinessService businessService, Configuration config) throws FatalErrorException { + boolean shouldcheck = config.getBoolean(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_ENABLE, false); + initDigSig(config); + if (shouldcheck && !businessService.getSignature().isEmpty() && ds != null) { + AtomicReference outmsg = new AtomicReference(); + boolean ok = ds.verifySignedUddiEntity(businessService, outmsg); + if (!ok) { + throw new FatalErrorException(new ErrorMessage("errors.digitalsignature.validationfailure", businessService.getServiceKey() + " " + outmsg.get())); + } + + } + } + + private void validateSignaturesTModel(TModel tModel, Configuration config) throws FatalErrorException { + boolean shouldcheck = config.getBoolean(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_ENABLE, false); + initDigSig(config); + if (shouldcheck && !tModel.getSignature().isEmpty() && ds != null) { + AtomicReference outmsg = new AtomicReference(); + boolean ok = ds.verifySignedUddiEntity(tModel, outmsg); + if (!ok) { + throw new FatalErrorException(new ErrorMessage("errors.digitalsignature.validationfailure", tModel.getTModelKey() + " " + outmsg.get())); + } + + } + } + + private void validateSignaturesBusiness(BusinessEntity businessEntity, Configuration config) throws FatalErrorException { + boolean shouldcheck = config.getBoolean(Property.JUDDI_REJECT_ENTITIES_WITH_INVALID_SIG_ENABLE, false); + initDigSig(config); + if (shouldcheck && !businessEntity.getSignature().isEmpty() && ds != null) { + AtomicReference outmsg = new AtomicReference(); + boolean ok = ds.verifySignedUddiEntity(businessEntity, outmsg); + if (!ok) { + throw new FatalErrorException(new ErrorMessage("errors.digitalsignature.validationfailure", businessEntity.getBusinessKey() + " " + outmsg.get())); + } + + } + } + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/ValidatePublisher.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidatePublisher.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/validation/ValidatePublisher.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidatePublisher.java index 0129119d1..0235abda0 100644 --- a/juddi-core/src/main/java/org/apache/juddi/validation/ValidatePublisher.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidatePublisher.java @@ -1,144 +1,144 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.validation; - -import java.util.HashSet; -import java.util.List; - -import javax.persistence.EntityManager; - -import org.apache.juddi.api_v3.DeletePublisher; -import org.apache.juddi.api_v3.GetAllPublisherDetail; -import org.apache.juddi.api_v3.GetPublisherDetail; -import org.apache.juddi.api_v3.SavePublisher; -import org.apache.juddi.model.Publisher; -import org.apache.juddi.model.UddiEntityPublisher; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.FatalErrorException; -import org.apache.juddi.v3.error.InvalidKeyPassedException; -import org.apache.juddi.v3.error.UserMismatchException; -import org.apache.juddi.v3.error.ValueNotAllowedException; -import org.uddi.v3_service.DispositionReportFaultMessage; - - -/** - * @author Jeff Faath - */ -public class ValidatePublisher extends ValidateUDDIApi { - - public ValidatePublisher(UddiEntityPublisher publisher) { - super(publisher); - } - - - - /*------------------------------------------------------------------- - Publisher functions are specific to jUDDI. - --------------------------------------------------------------------*/ - - public void validateDeletePublisher(EntityManager em, DeletePublisher body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - - // No null or empty list - List entityKeyList = body.getPublisherId(); - if (entityKeyList == null || entityKeyList.size() == 0) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); - - if (!((Publisher)publisher).isAdmin()) - throw new UserMismatchException(new ErrorMessage("errors.deletepublisher.AdminReqd")); - - HashSet dupCheck = new HashSet(); - for (String entityKey : entityKeyList) { - boolean inserted = dupCheck.add(entityKey); - if (!inserted) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); - - Object obj = em.find(org.apache.juddi.model.Publisher.class, entityKey); - if (obj == null) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.PublisherNotFound", entityKey)); - - } - } - - public void validateSavePublisher(EntityManager em, SavePublisher body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - - // No null or empty list - List entityList = body.getPublisher(); - if (entityList == null || entityList.size() == 0) - throw new ValueNotAllowedException(new ErrorMessage("errors.savepublisher.NoInput")); - - if (!((Publisher)publisher).isAdmin()) - throw new UserMismatchException(new ErrorMessage("errors.savepublisher.AdminReqd")); - - for (org.apache.juddi.api_v3.Publisher entity : entityList) { - validatePublisher(em, entity); - } - } - - public void validatePublisher(EntityManager em, org.apache.juddi.api_v3.Publisher publisher) throws DispositionReportFaultMessage { - - // No null input - if (publisher == null) - throw new ValueNotAllowedException(new ErrorMessage("errors.publisher.NullInput")); - - String authorizedName = publisher.getAuthorizedName(); - if (authorizedName == null || authorizedName.length() == 0) - throw new ValueNotAllowedException(new ErrorMessage("errors.publisher.NoAuthorizedName")); - - String publisherName = publisher.getPublisherName(); - if (publisherName == null || publisherName.length() == 0) - throw new ValueNotAllowedException(new ErrorMessage("errors.publisher.NoPublisherName")); - - } - - public void validateGetPublisherDetail(GetPublisherDetail body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - - // No null or empty list - List publisherIdList = body.getPublisherId(); - if (publisherIdList == null || publisherIdList.size() == 0) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); - - HashSet dupCheck = new HashSet(); - for (String publisherId : publisherIdList) { - boolean inserted = dupCheck.add(publisherId); - if (!inserted) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", publisherId)); - } - } - - public void validateGetAllPublisherDetail(GetAllPublisherDetail body) throws DispositionReportFaultMessage { - - // No null input - if (body == null) - throw new FatalErrorException(new ErrorMessage("errors.NullInput")); - - } - - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.validation; + +import java.util.HashSet; +import java.util.List; + +import javax.persistence.EntityManager; + +import org.apache.juddi.api_v3.DeletePublisher; +import org.apache.juddi.api_v3.GetAllPublisherDetail; +import org.apache.juddi.api_v3.GetPublisherDetail; +import org.apache.juddi.api_v3.SavePublisher; +import org.apache.juddi.model.Publisher; +import org.apache.juddi.model.UddiEntityPublisher; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.FatalErrorException; +import org.apache.juddi.v3.error.InvalidKeyPassedException; +import org.apache.juddi.v3.error.UserMismatchException; +import org.apache.juddi.v3.error.ValueNotAllowedException; +import org.uddi.v3_service.DispositionReportFaultMessage; + + +/** + * @author Jeff Faath + */ +public class ValidatePublisher extends ValidateUDDIApi { + + public ValidatePublisher(UddiEntityPublisher publisher) { + super(publisher); + } + + + + /*------------------------------------------------------------------- + Publisher functions are specific to jUDDI. + --------------------------------------------------------------------*/ + + public void validateDeletePublisher(EntityManager em, DeletePublisher body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + + // No null or empty list + List entityKeyList = body.getPublisherId(); + if (entityKeyList == null || entityKeyList.size() == 0) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); + + if (!((Publisher)publisher).isAdmin()) + throw new UserMismatchException(new ErrorMessage("errors.deletepublisher.AdminReqd")); + + HashSet dupCheck = new HashSet(); + for (String entityKey : entityKeyList) { + boolean inserted = dupCheck.add(entityKey); + if (!inserted) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey)); + + Object obj = em.find(org.apache.juddi.model.Publisher.class, entityKey); + if (obj == null) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.PublisherNotFound", entityKey)); + + } + } + + public void validateSavePublisher(EntityManager em, SavePublisher body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + + // No null or empty list + List entityList = body.getPublisher(); + if (entityList == null || entityList.size() == 0) + throw new ValueNotAllowedException(new ErrorMessage("errors.savepublisher.NoInput")); + + if (!((Publisher)publisher).isAdmin()) + throw new UserMismatchException(new ErrorMessage("errors.savepublisher.AdminReqd")); + + for (org.apache.juddi.api_v3.Publisher entity : entityList) { + validatePublisher(em, entity); + } + } + + public void validatePublisher(EntityManager em, org.apache.juddi.api_v3.Publisher publisher) throws DispositionReportFaultMessage { + + // No null input + if (publisher == null) + throw new ValueNotAllowedException(new ErrorMessage("errors.publisher.NullInput")); + + String authorizedName = publisher.getAuthorizedName(); + if (authorizedName == null || authorizedName.length() == 0) + throw new ValueNotAllowedException(new ErrorMessage("errors.publisher.NoAuthorizedName")); + + String publisherName = publisher.getPublisherName(); + if (publisherName == null || publisherName.length() == 0) + throw new ValueNotAllowedException(new ErrorMessage("errors.publisher.NoPublisherName")); + + } + + public void validateGetPublisherDetail(GetPublisherDetail body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + + // No null or empty list + List publisherIdList = body.getPublisherId(); + if (publisherIdList == null || publisherIdList.size() == 0) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys")); + + HashSet dupCheck = new HashSet(); + for (String publisherId : publisherIdList) { + boolean inserted = dupCheck.add(publisherId); + if (!inserted) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", publisherId)); + } + } + + public void validateGetAllPublisherDetail(GetAllPublisherDetail body) throws DispositionReportFaultMessage { + + // No null input + if (body == null) + throw new FatalErrorException(new ErrorMessage("errors.NullInput")); + + } + + +} diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateReplication.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateReplication.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/ValidateReplication.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateReplication.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateSecurity.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateSecurity.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/ValidateSecurity.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateSecurity.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateSubscription.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateSubscription.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/ValidateSubscription.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateSubscription.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateSubscriptionListener.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateSubscriptionListener.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/validation/ValidateSubscriptionListener.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateSubscriptionListener.java index 208499bfd..768718966 100644 --- a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateSubscriptionListener.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateSubscriptionListener.java @@ -1,40 +1,40 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.validation; - -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.FatalErrorException; -import org.uddi.subr_v3.NotifySubscriptionListener; - -/** - * @author Jeff Faath - * @author Tom Cunningham - */ -public class ValidateSubscriptionListener extends ValidateUDDIApi { - - public ValidateSubscriptionListener() { - super(null); - } - - public void validateNotification(NotifySubscriptionListener body) throws - FatalErrorException { - if (body == null) { - throw new FatalErrorException(new ErrorMessage("Subscription Listener Body was null")); - } - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.validation; + +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.FatalErrorException; +import org.uddi.subr_v3.NotifySubscriptionListener; + +/** + * @author Jeff Faath + * @author Tom Cunningham + */ +public class ValidateSubscriptionListener extends ValidateUDDIApi { + + public ValidateSubscriptionListener() { + super(null); + } + + public void validateNotification(NotifySubscriptionListener body) throws + FatalErrorException { + if (body == null) { + throw new FatalErrorException(new ErrorMessage("Subscription Listener Body was null")); + } + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateUDDIApi.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateUDDIApi.java similarity index 96% rename from juddi-core/src/main/java/org/apache/juddi/validation/ValidateUDDIApi.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateUDDIApi.java index 6ffcfebc0..184c3bca6 100644 --- a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateUDDIApi.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateUDDIApi.java @@ -1,86 +1,86 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.validation; - - -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.persistence.EntityManager; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.Property; - -import org.apache.juddi.model.Subscription; -import org.apache.juddi.model.UddiEntity; -import org.apache.juddi.model.UddiEntityPublisher; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.UnsupportedException; -import org.uddi.v3_service.DispositionReportFaultMessage; - -/** - * @author Jeff Faath - */ -public abstract class ValidateUDDIApi { - - protected UddiEntityPublisher publisher; - protected String nodeID=null; - - /** - * This is used only during the install process to prevent infinite loops - * @param publisher - * @param nodeid - */ - public ValidateUDDIApi(UddiEntityPublisher publisher, String nodeid) { - this.publisher = publisher; - this.nodeID = nodeid; - } - - public ValidateUDDIApi(UddiEntityPublisher publisher) { - this.publisher = publisher; - try { - this.nodeID = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID); - } catch (ConfigurationException ex) { - Logger.getLogger(ValidateUDDIApi.class.getName()).log(Level.SEVERE, "unable to get the current node id, this may cause access control problems" - + " and must be fixed. set " + Property.JUDDI_NODE_ID + " in juddiv3.xml", ex); - } - } - - public UddiEntityPublisher getPublisher() { - return publisher; - } - - public void setPublisher(UddiEntityPublisher publisher) { - this.publisher = publisher; - } - - public static void unsupportedAPICall() throws DispositionReportFaultMessage { - throw new UnsupportedException(new ErrorMessage("errors.Unsupported")); - } - - public static boolean isUniqueKey(EntityManager em, String entityKey) { - Object obj = em.find(UddiEntity.class, entityKey); - if (obj != null) - return false; - - obj = em.find(Subscription.class, entityKey); - if (obj != null) - return false; - - return true; - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.validation; + + +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.persistence.EntityManager; +import org.apache.commons.configuration.ConfigurationException; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.Property; + +import org.apache.juddi.model.Subscription; +import org.apache.juddi.model.UddiEntity; +import org.apache.juddi.model.UddiEntityPublisher; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.UnsupportedException; +import org.uddi.v3_service.DispositionReportFaultMessage; + +/** + * @author Jeff Faath + */ +public abstract class ValidateUDDIApi { + + protected UddiEntityPublisher publisher; + protected String nodeID=null; + + /** + * This is used only during the install process to prevent infinite loops + * @param publisher + * @param nodeid + */ + public ValidateUDDIApi(UddiEntityPublisher publisher, String nodeid) { + this.publisher = publisher; + this.nodeID = nodeid; + } + + public ValidateUDDIApi(UddiEntityPublisher publisher) { + this.publisher = publisher; + try { + this.nodeID = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID); + } catch (ConfigurationException ex) { + Logger.getLogger(ValidateUDDIApi.class.getName()).log(Level.SEVERE, "unable to get the current node id, this may cause access control problems" + + " and must be fixed. set " + Property.JUDDI_NODE_ID + " in juddiv3.xml", ex); + } + } + + public UddiEntityPublisher getPublisher() { + return publisher; + } + + public void setPublisher(UddiEntityPublisher publisher) { + this.publisher = publisher; + } + + public static void unsupportedAPICall() throws DispositionReportFaultMessage { + throw new UnsupportedException(new ErrorMessage("errors.Unsupported")); + } + + public static boolean isUniqueKey(EntityManager em, String entityKey) { + Object obj = em.find(UddiEntity.class, entityKey); + if (obj != null) + return false; + + obj = em.find(Subscription.class, entityKey); + if (obj != null) + return false; + + return true; + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateUDDIKey.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateUDDIKey.java similarity index 97% rename from juddi-core/src/main/java/org/apache/juddi/validation/ValidateUDDIKey.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateUDDIKey.java index ad4148db4..44a0afe05 100644 --- a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateUDDIKey.java +++ b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateUDDIKey.java @@ -1,160 +1,160 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.validation; - -import java.util.List; -import java.util.StringTokenizer; - -import org.apache.juddi.keygen.KeyGenerator; -import org.apache.juddi.v3.error.ErrorMessage; -import org.apache.juddi.v3.error.InvalidKeyPassedException; -import org.apache.juddi.v3.error.ValueNotAllowedException; -import org.uddi.v3_service.DispositionReportFaultMessage; - -/** - * @author Jeff Faath - * @author Tom Cunningham - */ -public class ValidateUDDIKey { - - public static void validateUDDIv3Key(String key) throws DispositionReportFaultMessage { - if (key == null) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NullKey")); - if (key.toLowerCase().startsWith("uuid:")) { - return; - } - if (! key.contains(KeyGenerator.PARTITION_SEPARATOR)) return; //v2 style key; no other validation rules apply - - String keyToTest = key.trim(); - if (keyToTest.endsWith(KeyGenerator.PARTITION_SEPARATOR)) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.MalformedKey", key)); - - StringTokenizer tokenizer = new StringTokenizer(key.toLowerCase(), KeyGenerator.PARTITION_SEPARATOR); - - for(int count = 0; tokenizer.hasMoreTokens(); count++) { - String nextToken = tokenizer.nextToken(); - - if (count == 0) { - if (!ValidateUDDIKey.isValidUDDIScheme(nextToken)) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.MalformedKey", key)); - } - else if (count == 1) { - if(!ValidateUDDIKey.isValidDomainKey(nextToken)) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.MalformedKey", key)); - } - else { - if (!isValidKSS(nextToken)) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.MalformedKey", key)); - } - } - } - - public static void validateUDDIv3KeyGeneratorKey(String key) throws DispositionReportFaultMessage { - if (key == null) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NullKeys")); - - if ( !(key.toUpperCase().endsWith(KeyGenerator.KEYGENERATOR_SUFFIX.toUpperCase())) ) - throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.KeyGenSuffix", key)); - - validateUDDIv3Key(key.substring(0, key.lastIndexOf(KeyGenerator.PARTITION_SEPARATOR))); - } - - public static void validateUDDIv3KeyGeneratorTModel(org.uddi.api_v3.TModel tModel) throws DispositionReportFaultMessage { - if (tModel == null) - throw new ValueNotAllowedException(new ErrorMessage("errors.tmodel.NullInput")); - - validateUDDIv3KeyGeneratorKey(tModel.getTModelKey()); - - // A key generator key should have exactly one category and it's key value should be 'keyGenerator' - org.uddi.api_v3.CategoryBag categories = tModel.getCategoryBag(); - if (categories != null) { - List elems = categories.getKeyedReference(); - if (elems != null && elems.size() == 1) { - org.uddi.api_v3.KeyedReference elem = elems.get(0); - if (elem != null) { - if (elem instanceof org.uddi.api_v3.KeyedReference) { - String keyedValue = elem.getKeyValue(); - if (keyedValue != null) { - if (keyedValue.equalsIgnoreCase(KeyGenerator.KEYGENERATOR_SUFFIX)) - return; - } - } - } - } - } - - throw new ValueNotAllowedException(new ErrorMessage("errors.tmodel.keygenerator.BadCategory")); - } - - public static boolean isValidUDDIScheme(String token) { - if (token == null) - return false; - - if (!KeyGenerator.UDDI_SCHEME.equalsIgnoreCase(token)) - return false; - - return true; - - } - - public static boolean isValidDomainKey(String token) { - if(token.indexOf("..") != -1) - return false; - - StringTokenizer tokenizer = new StringTokenizer(token, "."); - int tokensCount = tokenizer.countTokens(); - for(int i = 0; tokenizer.hasMoreTokens(); i++) { - String domainPart = tokenizer.nextToken(); - if(i == tokensCount - 1) { - if(!isValidTopLabel(domainPart)) { - return false; - } - } else if(!isValidDomainLabel(domainPart)) { - return false; - } - } - return true; - } - - - private static boolean isValidDomainLabel(String token) { - char[] chars = token.toCharArray(); - for(int i = 0; i < chars.length; i++) { - char c = chars[i]; - if(c != '-' && !Character.isLetterOrDigit(c)) { - return false; - } - } - return true; - } - - private static boolean isValidTopLabel(String token) { - return Character.isLetter(token.charAt(0)) && (token.length() == 1 || isValidDomainLabel(token.substring(1))); - } - - public static boolean isValidKSS(String token) { - if (token.length() == 0) - return false; - - // The key generator suffix is a reserved word and cannot be found in any part of the KSS - if (token.equalsIgnoreCase(KeyGenerator.KEYGENERATOR_SUFFIX)) - return false; - - return true; - } -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.validation; + +import java.util.List; +import java.util.StringTokenizer; + +import org.apache.juddi.keygen.KeyGenerator; +import org.apache.juddi.v3.error.ErrorMessage; +import org.apache.juddi.v3.error.InvalidKeyPassedException; +import org.apache.juddi.v3.error.ValueNotAllowedException; +import org.uddi.v3_service.DispositionReportFaultMessage; + +/** + * @author Jeff Faath + * @author Tom Cunningham + */ +public class ValidateUDDIKey { + + public static void validateUDDIv3Key(String key) throws DispositionReportFaultMessage { + if (key == null) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NullKey")); + if (key.toLowerCase().startsWith("uuid:")) { + return; + } + if (! key.contains(KeyGenerator.PARTITION_SEPARATOR)) return; //v2 style key; no other validation rules apply + + String keyToTest = key.trim(); + if (keyToTest.endsWith(KeyGenerator.PARTITION_SEPARATOR)) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.MalformedKey", key)); + + StringTokenizer tokenizer = new StringTokenizer(key.toLowerCase(), KeyGenerator.PARTITION_SEPARATOR); + + for(int count = 0; tokenizer.hasMoreTokens(); count++) { + String nextToken = tokenizer.nextToken(); + + if (count == 0) { + if (!ValidateUDDIKey.isValidUDDIScheme(nextToken)) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.MalformedKey", key)); + } + else if (count == 1) { + if(!ValidateUDDIKey.isValidDomainKey(nextToken)) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.MalformedKey", key)); + } + else { + if (!isValidKSS(nextToken)) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.MalformedKey", key)); + } + } + } + + public static void validateUDDIv3KeyGeneratorKey(String key) throws DispositionReportFaultMessage { + if (key == null) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NullKeys")); + + if ( !(key.toUpperCase().endsWith(KeyGenerator.KEYGENERATOR_SUFFIX.toUpperCase())) ) + throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.KeyGenSuffix", key)); + + validateUDDIv3Key(key.substring(0, key.lastIndexOf(KeyGenerator.PARTITION_SEPARATOR))); + } + + public static void validateUDDIv3KeyGeneratorTModel(org.uddi.api_v3.TModel tModel) throws DispositionReportFaultMessage { + if (tModel == null) + throw new ValueNotAllowedException(new ErrorMessage("errors.tmodel.NullInput")); + + validateUDDIv3KeyGeneratorKey(tModel.getTModelKey()); + + // A key generator key should have exactly one category and it's key value should be 'keyGenerator' + org.uddi.api_v3.CategoryBag categories = tModel.getCategoryBag(); + if (categories != null) { + List elems = categories.getKeyedReference(); + if (elems != null && elems.size() == 1) { + org.uddi.api_v3.KeyedReference elem = elems.get(0); + if (elem != null) { + if (elem instanceof org.uddi.api_v3.KeyedReference) { + String keyedValue = elem.getKeyValue(); + if (keyedValue != null) { + if (keyedValue.equalsIgnoreCase(KeyGenerator.KEYGENERATOR_SUFFIX)) + return; + } + } + } + } + } + + throw new ValueNotAllowedException(new ErrorMessage("errors.tmodel.keygenerator.BadCategory")); + } + + public static boolean isValidUDDIScheme(String token) { + if (token == null) + return false; + + if (!KeyGenerator.UDDI_SCHEME.equalsIgnoreCase(token)) + return false; + + return true; + + } + + public static boolean isValidDomainKey(String token) { + if(token.indexOf("..") != -1) + return false; + + StringTokenizer tokenizer = new StringTokenizer(token, "."); + int tokensCount = tokenizer.countTokens(); + for(int i = 0; tokenizer.hasMoreTokens(); i++) { + String domainPart = tokenizer.nextToken(); + if(i == tokensCount - 1) { + if(!isValidTopLabel(domainPart)) { + return false; + } + } else if(!isValidDomainLabel(domainPart)) { + return false; + } + } + return true; + } + + + private static boolean isValidDomainLabel(String token) { + char[] chars = token.toCharArray(); + for(int i = 0; i < chars.length; i++) { + char c = chars[i]; + if(c != '-' && !Character.isLetterOrDigit(c)) { + return false; + } + } + return true; + } + + private static boolean isValidTopLabel(String token) { + return Character.isLetter(token.charAt(0)) && (token.length() == 1 || isValidDomainLabel(token.substring(1))); + } + + public static boolean isValidKSS(String token) { + if (token.length() == 0) + return false; + + // The key generator suffix is a reserved word and cannot be found in any part of the KSS + if (token.equalsIgnoreCase(KeyGenerator.KEYGENERATOR_SUFFIX)) + return false; + + return true; + } +} diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateUDDIv2Inquiry.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateUDDIv2Inquiry.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/ValidateUDDIv2Inquiry.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateUDDIv2Inquiry.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateValueSetCaching.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateValueSetCaching.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/ValidateValueSetCaching.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateValueSetCaching.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateValueSetValidation.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateValueSetValidation.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/ValidateValueSetValidation.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateValueSetValidation.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/ValidateValuesFromWebService.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateValuesFromWebService.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/ValidateValuesFromWebService.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidateValuesFromWebService.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/ValidationConstants.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidationConstants.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/ValidationConstants.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/ValidationConstants.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/package-info.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/package-info.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/package-info.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/package-info.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/vsv/AbstractSimpleValidator.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/AbstractSimpleValidator.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/vsv/AbstractSimpleValidator.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/AbstractSimpleValidator.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationderivedfrom.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationderivedfrom.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationderivedfrom.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationderivedfrom.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationentitykeyvalues.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationentitykeyvalues.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationentitykeyvalues.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationentitykeyvalues.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationnodes.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationnodes.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationnodes.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationnodes.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationowningbusiness.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationowningbusiness.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationowningbusiness.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationowningbusiness.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationtypes.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationtypes.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationtypes.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationtypes.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationvalidatedby.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationvalidatedby.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationvalidatedby.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgcategorizationvalidatedby.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgidentifierisreplacedby.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgidentifierisreplacedby.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgidentifierisreplacedby.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgidentifierisreplacedby.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgrelationships.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgrelationships.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgrelationships.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uddiuddiorgrelationships.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uuid25b22e3e3dfa3024b02a3438b9050b59.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uuid25b22e3e3dfa3024b02a3438b9050b59.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uuid25b22e3e3dfa3024b02a3438b9050b59.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uuid25b22e3e3dfa3024b02a3438b9050b59.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uuid327a56f032994461bc235cd513e95c55.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uuid327a56f032994461bc235cd513e95c55.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uuid327a56f032994461bc235cd513e95c55.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uuid327a56f032994461bc235cd513e95c55.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uuid4064c0646d144f3589539652106476a9.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uuid4064c0646d144f3589539652106476a9.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uuid4064c0646d144f3589539652106476a9.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uuid4064c0646d144f3589539652106476a9.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uuid5678dd4ff95d35f99ea6f79a7dd64656.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uuid5678dd4ff95d35f99ea6f79a7dd64656.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uuid5678dd4ff95d35f99ea6f79a7dd64656.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uuid5678dd4ff95d35f99ea6f79a7dd64656.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uuid807a2c6aee22470dadc7e0424a337c03.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uuid807a2c6aee22470dadc7e0424a337c03.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uuid807a2c6aee22470dadc7e0424a337c03.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uuid807a2c6aee22470dadc7e0424a337c03.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uuid916b87bf075639198eae97dfa325e5a4.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uuid916b87bf075639198eae97dfa325e5a4.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uuid916b87bf075639198eae97dfa325e5a4.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uuid916b87bf075639198eae97dfa325e5a4.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uuidc1acf26d967244049d7039b756e62ab4.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uuidc1acf26d967244049d7039b756e62ab4.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uuidc1acf26d967244049d7039b756e62ab4.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uuidc1acf26d967244049d7039b756e62ab4.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uuide59ae32077a511d5b8980004ac49cc1e.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uuide59ae32077a511d5b8980004ac49cc1e.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/vsv/Uuide59ae32077a511d5b8980004ac49cc1e.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/Uuide59ae32077a511d5b8980004ac49cc1e.java diff --git a/juddi-core/src/main/java/org/apache/juddi/validation/vsv/ValueSetValidator.java b/juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/ValueSetValidator.java similarity index 100% rename from juddi-core/src/main/java/org/apache/juddi/validation/vsv/ValueSetValidator.java rename to juddi-core-openjpa/src/main/java/org/apache/juddi/validation/vsv/ValueSetValidator.java diff --git a/juddi-core/src/main/resources/juddi_install_data/UDDI_Publisher.xml b/juddi-core-openjpa/src/main/resources/juddi_install_data/UDDI_Publisher.xml similarity index 97% rename from juddi-core/src/main/resources/juddi_install_data/UDDI_Publisher.xml rename to juddi-core-openjpa/src/main/resources/juddi_install_data/UDDI_Publisher.xml index 7f7195057..0bfd8156a 100644 --- a/juddi-core/src/main/resources/juddi_install_data/UDDI_Publisher.xml +++ b/juddi-core-openjpa/src/main/resources/juddi_install_data/UDDI_Publisher.xml @@ -1,22 +1,22 @@ - - - - UDDI publisher - false - - + + + + UDDI publisher + false + + diff --git a/juddi-core/src/main/resources/juddi_install_data/UDDI_tModels.xml b/juddi-core-openjpa/src/main/resources/juddi_install_data/UDDI_tModels.xml similarity index 97% rename from juddi-core/src/main/resources/juddi_install_data/UDDI_tModels.xml rename to juddi-core-openjpa/src/main/resources/juddi_install_data/UDDI_tModels.xml index 2ec74dcdf..475ad16d0 100644 --- a/juddi-core/src/main/resources/juddi_install_data/UDDI_tModels.xml +++ b/juddi-core-openjpa/src/main/resources/juddi_install_data/UDDI_tModels.xml @@ -1,2426 +1,2426 @@ - - - - - - - - - uddi-org:keyGenerator - UDDI domain key generator - - - http://uddi.org/pubs/uddi_v3.htm#keyGen - - - - - - - - uddi-org:categorization:keyGenerator - - Key Generator for UDDI Categorization tModels - - - - http://uddi.org/pubs/uddi_v3.htm#categorizationKeyGen - - - - - - - - uddi-org:types - UDDI Type Category System - - - http://uddi.org/pubs/uddi_v3.htm#UDDITypes - - - - - - - - - - - uddi-org:general_keywords - Category system consisting of namespace - identifiers and the keywords associated with - the namespaces. - - - - http://uddi.org/pubs/uddi_v3.htm#GenKW - - - - - - - - - uddi-org:sortorder:keyGenerator - - Key Generator for UDDI Sort Order tModels - - - - http://uddi.org/pubs/uddi_v3.htm#sortorderKeyGen - - - - - - - - uddi-org:transport:keyGenerator - - Key Generator for UDDI Transport tModels - - - http://uddi.org/pubs/uddi_v3.htm#transportKeyGen - - - - - - - - uddi-org:protocol:keyGenerator - Key Generator for UDDI Protocol tModels - - - http://uddi.org/pubs/uddi_v3.htm#protocolKeyGen - - - - - - - - uddi-org:inquiry_v3 - UDDI Inquiry API V3.0 - - - http://uddi.org/wsdl/uddi_api_v3_binding.wsdl#UDDI_Inquiry_SoapBinding - - - - - http://uddi.org/pubs/uddi_v3.htm#InqV3 - - - - - - - - - - - uddi-org:nodes - Category system for identifying the nodes - of a registry. - - - - http://uddi.org/pubs/uddi_v3.htm#Nodes - - - - - - - - - - - - uddi-org:publication_v3 - UDDI Publication API V3.0 - - - http://uddi.org/wsdl/uddi_api_v3_binding.wsdl#UDDI_Publication_SoapBinding - - - - - http://uddi.org/pubs/uddi_v3.htm#PubV3 - - - - - - - - - - - uddi-org:security_v3 - UDDI Security API V3.0 - - - http://uddi.org/wsdl/uddi_api_v3_binding.wsdl#UDDI_Security_SoapBinding - - - - - http://uddi.org/pubs/uddi_v3.htm#SecV3 - - - - - - - - - - - - uddi-org:relationships - Basic types of business relationships - - - - http://uddi.org/pubs/uddi_v3.htm#Relationships - - - - - - - - - - uddi-org:owningBusiness_v3 - Category system used to point to the - businessEntity - associated with the publisher of the tModel. - - - - http://uddi.org/pubs/uddi_v3.htm#owningBusiness - - - - - - - - - - - - uddi-org:isReplacedBy - Identifier system used to point to the UDDI - entity, - using UDDI keys, that is the logical replacement - for the one in which isReplacedBy is used. - - - - http://uddi.org/pubs/uddi_v3.htm#IsReplacedBy - - - - - - - - - - - - - - Tax ID - The Tax Identifier for this business - - - - http://uddi.org/pubs/uddi-v3.0.2-20041019.htm#_Toc515847032 - - - - - - - - - - - - - - - - uddi-org:validatedBy - Category system used to point a value set or - category - group system tModel to associated value set Web service - implementations. - - This is typically used on tModels to validate tModel Instances via the Value Set Validation service. The keyValue - should be an existing binding key pointing to that service. - - - - http://uddi.org/pubs/uddi_v3.htm#validatedBy - - - - - - - - - - - - - - - - uddi-org:derivedFrom - Category system for referring tModels to other - tModels for the purpose of reuse. - - - - http://uddi.org/pubs/uddi_v3.htm#DerivedFrom - - - - - - - - - - - - - - uddi-org:derivedFrom - Category system for referring tModels to other - tModels for the purpose of reuse. - - - - http://uddi.org/pubs/uddi_v3.htm#DerivedFrom - - - - - - - - - - - - - - - - uddi-org:entityKeyValues - Category system used to declare that a value set - uses entity keys as valid values. - - - - http://uddi.org/pubs/uddi_v3.htm#entityKeyValues - - - - - - - - - - - - uddi-org:entityKeyValues - Category system used to declare that a value set - uses entity keys as valid values. - - - - http://uddi.org/pubs/uddi_v3.htm#entityKeyValues - - - - - - - - - - - - - - uddi-org:serverAuthenticatedSSL3 - Secure Sockets Layer Version 3.0 with Server - Authentication - - - - http://uddi.org/pubs/uddi_v3.htm#serverSSL3 - - - - - - - - - uddi-org:mutualAuthenticatedSSL3 - - Secure Sockets Layer Version 3.0 with Mutual - Authentication - - - - http://uddi.org/pubs/uddi_v3.htm#mutualSSL3 - - - - - - - - - uddi-org:mutualAuthenticatedSSL3 - - Secure Sockets Layer Version 3.0 with Mutual - Authentication - - - - http://uddi.org/pubs/uddi_v3.htm#mutualSSL3 - - - - - - - - - - uddi-org:http - A Web service that uses HTTP transport - - - http://uddi.org/pubs/uddi_v3.htm#overHTTP - - - - - - - - - uddi-org:http - A Web service that uses HTTP transport - - - http://uddi.org/pubs/uddi_v3.htm#overHTTP - - - - - - - - - - uddi-org:smtp - E-mail based Web service - - - http://uddi.org/pubs/uddi_v3.htm#overSMTP - - - - - - - - - uddi-org:smtp - E-mail based Web service - - - http://uddi.org/pubs/uddi_v3.htm#overSMTP - - - - - - - - - - Human Readable SMTP Email Deliveries - This is a jUDDI extension for providing SMTP based subscription alerts in a human readable fashion. - - - - - - - - - uddi-org:ftp - File Transfer Protocol (FTP) based Web service - - - - http://uddi.org/pubs/uddi_v3.htm#overFTP - - - - - - - - - uddi-org:ftp - File Transfer Protocol (FTP) based Web service - - - - http://uddi.org/pubs/uddi_v3.htm#overFTP - - - - - - - - - uddi-org:fax - Fax-based Web service - - - http://uddi.org/pubs/uddi_v3.htm#overFax - - - - - - - - uddi-org:telephone - Telephone based service - - - http://uddi.org/pubs/uddi_v3.htm#overPhone - - - - - - - - - - - uddi-org:amqp - A Web service that uses the AMQP transport - - - http://www.amqp.org/ - - - - - - - - - - uddi-org:omgdds - A Web service that uses the OMG DDS transport - - - http://portals.omg.org/dds/ - - - - - - - - - - uddi-org:udp - A Web service that uses the UDP transport - - - http://docs.oasis-open.org/ws-dd/soapoverudp/1.1/os/wsdd-soapoverudp-1.1-spec-os.html - - - - - - - - - uddi-org:jms - A Web service that uses the JMS API - - - http://docs.oasis-open.org/ws-dd/soapoverudp/1.1/os/wsdd-soapoverudp-1.1-spec-os.html - - - - - - - - - uddi-org:protocol:rest - A tModel that represents the Representational State Transfer architectural style - - - http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm - - - - - - - - - - - - uddi-org:approximateMatch:SQL99 - - UDDI approximate matching find qualifier - - - - http://uddi.org/pubs/uddi_v3.htm#wildcard - - - - - - - - uddi-org:exactMatch - UDDI exact name matching findQualifier - - - - http://uddi.org/pubs/uddi_v3.htm#exactmatch - - - - - - - - uddi-org:caseInsensitiveMatch - - UDDI case insensitive matching find qualifier - - - - http://uddi.org/pubs/uddi_v3.htm#caseinsens - - - - - - - - uddi-org:caseSensitiveMatch - UDDI Case Sensitive Matching find qualifier - - - - http://uddi.org/pubs/uddi_v3.htm#casesens - - - - - - - - uddi-org:diacriticsInsensitiveMatch - - UDDI Diacritics Insensitive Matching find qualifier - - - - http://uddi.org/pubs/uddi_v3.htm#diacritInsens - - - - - - - - uddi-org:diacriticsSensitiveMatch - - UDDI Diacritics Sensitive Matching find qualifier - - - - http://uddi.org/pubs/uddi_v3.htm#diacritSens - - - - - - - - uddi-org:binarySort - UDDI binary sort sortOrder qualifier - - - - http://uddi.org/pubs/uddi_v3.htm#sortOrd - - - - - - - - - uddi-org:UTS-10 - UDDI Unicode Technical Standard #10 sort - collation sequence find qualifier - - - - http://uddi.org/pubs/uddi_v3.htm#UCASort - - - - - - - - - uddi-org:caseInsensitiveSort - UDDI sort qualifier used to sort results without - regard to case - - - - http://uddi.org/pubs/uddi_v3.htm#caseInsensSort - - - - - - - - uddi-org:caseSensitiveSort - UDDI sort qualifier used to sort results using - case sensitivity - - - - http://uddi.org/pubs/uddi_v3.htm#caseSensSort - - - - - - - - - - uddi-org:sortByNameAsc - UDDI sort qualifier used to sort results by name - in ascending order - - - - http://uddi.org/pubs/uddi_v3.htm#nameAsc - - - - - - - - uddi-org:sortByNameDesc - UDDI sort qualifier used to sort results by - name in descending order - - - - http://uddi.org/pubs/uddi_v3.htm#nameDesc - - - - - - - - uddi-org:sortByDateAsc - UDDI sort qualifier used to sort results by date in - ascending order - - - - http://uddi.org/pubs/uddi_v3.htm#dateAsc - - - - - - - - uddi-org:sortByDateDesc - UDDI sort qualifier used to sort results - by date in descending order - - - - http://uddi.org/pubs/uddi_v3.htm#dateDesc - - - - - - - - uddi-org:andAllKeys - UDDI find qualifier used to request that a - logical AND be performed on bag contents - prior to a search - - - - http://uddi.org/pubs/uddi_v3.htm#andAll - - - - - - - - uddi-org:orAllKeys - UDDI find qualifier used to request that a - logical OR be performed on bag contents - prior to a search - - - - http://uddi.org/pubs/uddi_v3.htm#orAll - - - - - - - - uddi-org:orLikeKeys - UDDI find qualifier used to find entities - that reference one of the values from each - referenced value set - - - - http://uddi.org/pubs/uddi_v3.htm#orLike - - - - - - - - uddi-org:combineCategoryBags - UDDI find qualifier used to treat all of the - categoryBags within a businessEntity as if - they were one during inquiry - - - - http://uddi.org/pubs/uddi_v3.htm#combineCatBags - - - - - - - - uddi-org:serviceSubset - UDDI find qualifier used to use categoryBags - of businessService elements to satisfy the - find_business inquiry. - - - - http://uddi.org/pubs/uddi_v3.htm#servSubset - - - - - - - - uddi-org:bindingSubset - UDDI find qualifier for specifying use of - categoryBags of bindingTempate elements to satisfy - the find_business or find_service inquiries. - - - - http://uddi.org/pubs/uddi_v3.htm#bindSubset - - - - - - - - uddi-org:suppressProjectedServices - - UDDI find qualifier used to exclude service - projections from an inquiry function at all - levels. - - - - http://uddi.org/pubs/uddi_v3.htm#suppressProjSvcs - - - - - - - - uddi-org:signaturePresent - UDDI findQualifier used to return only entities - that have or are contained in entities that have - XML Digital Signatures. - - - - http://uddi.org/pubs/uddi_v3.htm#sign - - - - - - - - uddi-org:hostingRedirector - UDDI Hosting Redirector service specification - - - - http://uddi.org/pubs/uddi_v3.htm#hostDir - - - - - - - - uddi-org:v3_policy - UDDI Policy Description service specification - - - - http://uddi.org/pubs/uddi_v3.htm#policyDesc - - - - - - - - uddi-org:ownership_transfer_v3 - UDDI Custody and Ownership Transfer API V3.0 - - - http://uddi.org/wsdl/uddi_custody_v3_binding.wsdl - - - - - http://uddi.org/pubs/uddi_v3.htm#OwnershipTransfer - - - - - - - - - - - uddi-org:subscription_v3 - UDDI Subscription API V3.0 - - - http://uddi.org/wsdl/uddi_sub_v3_binding.wsdl - - - - - http://uddi.org/pubs/uddi_v3.htm#Sub - - - - - - - - - - - uddi-org:subscriptionListener_v3 - UDDI Subscription Listener API V3.0 - - - http://uddi.org/wsdl/uddi_subr_v3_binding.wsdl - - - - - http://uddi.org/pubs/uddi_v3.htm#Subscribe - - - - - - - - - - - - - uddi-org:wsdl:types - WSDL Type Category System - - - http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#wsdlTypes - - - - - - - - - - uddi-org:wadl:types - WADL Type Category System - - - http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm - - - - - - - - - - - - uddi-org:xml:namespace - A category system used to indicate namespaces - - - http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#xmlNamespace - - - - - - - - - - uddi-org:xml:localName - A category system used to indicate XML local names - - - http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#xmlLocalName - - - - - - - - - - uddi-org:wsdl:portTypeReference - A category system used to reference a wsdl:portType tModel - - - http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#portTypeReference - - - - - - - - - - uddi-org:protocol:soap - A tModel that represents the SOAP 1.1 protocol - - - http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#soap - - - - - - - - - - uddi-org:protocol:soap12 - A tModel that represents the SOAP 1.2 protocol - - - http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#soap - - - - - - - - - - - uddi-org:protocol:http - A tModel that represents the HTTP protocol - - - http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#http - - - - - - - - - uddi-org:wsdl:categorization:protocol - Category system used to describe the protocol supported by a wsdl:binding - - - http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#protocol - - - - - - - - - - uddi-org:wsdl:categorization:transport - Category system used to describe the transport supported by a wsdl:binding - - - http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#transport - - - - - - - - - - uddi-org:wsdl:address - A tModel used to indicate the WSDL address option - - - http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#Address - - - - - - uddi-org:bpel:types - Category system used indicate BPEL processes - - - http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-bpel-20040725.htm - - - - - - - - - - - - - uddi:tmodelkey:keygenerator - - Key Generator for generic UDDI tModel Keys - - - - - - - - - - uddi:tmodelkey:address - Identifies an address. This can be a physical, mailing, or electric address. - - - - - - - - - uddi:tmodelkey:group - Identifies a tModel group. - - - - - - - - uddi:tmodelkey:blank - Identifies a blank tModel - - - - - - - - - - - - - urn:wsdm.org:keygenerator - Key Generator for WSDM.org tModels - - - http://uddi.org/pubs/uddi_v3.htm#protocolKeyGen - - - - - - - - urn:wsdm.org:metric:keygenerator - Key Generator for WSDM.org Metric tModels - - - http://uddi.org/pubs/uddi_v3.htm#protocolKeyGen - - - - - - - - urn:wsdm.org:identity:keygenerator - Key Generator for WSDM.org Identity tModels - - - http://uddi.org/pubs/uddi_v3.htm#protocolKeyGen - - - - - - - - urn:wsdm.org:qos:keygenerator - Key Generator for WSDM.org Quality of Service tModels - - - http://uddi.org/pubs/uddi_v3.htm#protocolKeyGen - - - - - - - - RequestCount - The number of requests to a given service. (number of requests) - - - https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc - - - - - - - - ReplyCount - The number of replies from a given service. (number of replies) - - - https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc - - - - - - - - FaultCount - The number of faults from a given service. (number of faults) - - - https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc - - - - - - - - ResourceId - This is the unique identity by which the resource (service) is known to the management system. It is useful for further queries. (resource identification in URI format) - - - https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc - - - - - - - - - LastUpdateTime - Represents the last time this metric was updated. (time value) - - - https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc - - - - - - - - - ResponseTime_Average - Average response time of the service. (numeric value or symbolic rating) - - - https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc - - - - - - - - Throughput_count - Throughput count. (numeric value or symbolic rating) - - - https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc - - - - - - - - Throughput_bytes - Throughput bytes. (numeric value or symbolic rating) - - - https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc - - - - - - - - Reliability - Reliability or the measure of. (numeric value or symbolic rating) - - - https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc - - - - - - - - ReportingPeriodStart - The beginning on the reporting time period used for the information above. (dateTime) - - - https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc - - - - - - - - ReportingPeriodEnd - The end of the reporting time period used for the information above. (dateTime) - - - https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc - - - - - - - - UpdateInterval - How often is this information updated in UDDI (it is not assumed to be realtime). (duration) - - - https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc - - - - - - - - - Service Interface Version - When using this tModel as a tModelInstance, it can be used to describe a version associated with either a service interface, a bindingTemplate service instance. Note: This is a jUDDI specific addon and may not be present in other registries. - - - http://www.ibm.com/developerworks/webservices/library/ws-version/ - - - - - - - - - ubr-uddi-org:iso-ch:3166-2003 - ISO 3166 Country Codes - When used in a Category Bag for a Business or Service, it can indicate the physical or logically location of the Business or Service. - ISO 3166 Codes for names of countries or regions. Updated with newsletters ISO 3166-1 V-1, V-2, V-3, V-4, V-5, V-6, V-7, ISO 3166-2 I-1, I-2, I-3, I-4. - - - http://www.iso.org/iso/country_codes - - - - - http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#ISO3166 - - - - - - - - - - - - - - United Nations Standard Products and Services Code with ISO 3166 Grouping - Grouping of the category systems for UNSPSC and ISO 3166. As a consequence, keyedReferenceGroups that reference this tModel describe countries or regions where a product category is offered. - - - http://uddi.org/pubs/uddi-v3.0.2-20041019.htm#_Toc535251470 - - - - - http://www.unspsc.org/ - - - - - - - - - - - - - World Geodetic System Key Generator - Key Generator for Standard for use in cartography, geodesy, and navigation. - - - http://www.ngs.noaa.gov/PUBS_LIB/Geodesy4Layman/TR80003E.HTM#ZZ11 - - - - - http://uddi.org/pubs/uddi_v3.htm#protocolKeyGen - - - - - - - - - World Geodetic System - Standard for use in cartography, geodesy, and navigation. - - - http://www.ngs.noaa.gov/PUBS_LIB/Geodesy4Layman/TR80003E.HTM#ZZ11 - - - - - - - - - - WGS Latitude - Standard for use in cartography, geodesy, and navigation. - - - http://www.ngs.noaa.gov/PUBS_LIB/Geodesy4Layman/TR80003E.HTM#ZZ11 - - - - - - - - - WGS Longitude - Standard for use in cartography, geodesy, and navigation. - - - http://www.ngs.noaa.gov/PUBS_LIB/Geodesy4Layman/TR80003E.HTM#ZZ11 - - - - - - - - - WGS Geographic Precision - Standard for use in cartography, geodesy, and navigation. - - - http://www.ngs.noaa.gov/PUBS_LIB/Geodesy4Layman/TR80003E.HTM#ZZ11 - - - - - - - - - - - - Universal Business Registry Key Generator - UBR domain key generator - - - http://uddi.org/pubs/uddi_v3.htm#keyGen - - - - - - - - Universal Business Registry Categorization Group Key Generator - UBR Categorization Group domain key generator - - - http://uddi.org/pubs/uddi_v3.htm#keyGen - - - - - - - - - Universal Business Registry Categorization Key Generator - UBR Categorization domain key generator - - - http://uddi.org/pubs/uddi_v3.htm#keyGen - - - - - - - - - ubr-uddi-org:postalAddress - Postal address structure - - - http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#postal - - - - - - - - - - - ubr-uddi-org:relationships - relationships in a UBR - - - http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm - - - - - - - - - ubr-uddi-org:identifier key generator - UBR Identifier Group domain key generator - - - http://uddi.org/pubs/uddi_v3.htm#keyGen - - - - - - - - - UBR Identifier Owning Business - Identifier for an Owning Business in a UBR - - - http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm - - - - - - - - - UBR Categorization United Nations Standard Products and Services Code - UNSPSC Categorization in a UBR - - - http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm - - - - - http://www.unspsc.org/ - - - - - - - - - - - - - - - North American Industry Classification System Key Generator - North American Industry Classification System Key Generator. - The North American Industry Classification System (NAICS) is the standard used by Federal statistical agencies in classifying business establishments for the purpose of collecting, analyzing, and publishing statistical data in the U.S. business economy - - - http://uddi.org/pubs/uddi_v3.htm#keyGen - - - https://www.census.gov/eos/www/naics/index.html - - - - - - - - - - - North American Industry Classification System 1997 - North American Industry Classification System 1997 - - - https://www.census.gov/eos/www/naics/reference_files_tools/1997/1997.html - - - - - - http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#NAICS - - - - - - - - - - - - - North American Industry Classification System 2012 - North American Industry Classification System 2012 - - - https://www.census.gov/cgi-bin/sssd/naics/naicsrch?chart=2012 - - - - - - - - - ntis-gov:naics:2002 - North American Industry Classification System 2002 - North American Industry Classification System 2002 - Business Taxonomy: NAICS (2002 Release) - - - https://www.census.gov/cgi-bin/sssd/naics/naicsrch?chart=2002 - - - - - http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#NAICS2002 - - - - - - - - - - - - - North American Industry Classification System 2007 - North American Industry Classification System 2007 - - - https://www.census.gov/cgi-bin/sssd/naics/naicsrch?chart=2007 - - - - - - - - - - - - UBR Taxonomies - Universal Business Registry Taxonomy Key Generator. - - - http://uddi.org/pubs/uddi_v3.htm#keyGen - - - - - - - - - North American Industry Classification System Taxonomy - North American Industry Classification System Taxonomy - - - https://www.census.gov/eos/www/naics/index.html - - - - - - - - - - - uddi-org:JIS-X4061 - UDDI JIS X 4061 Japanese - collation sequence find qualifier - - - - http://uddi.org/pubs/uddi-v3.0.2-20041019.htm#_Toc42047570 - - - - - - - - - - - ubr-uddi-org:identifier for dnb.com - UBR Identifier dnb.com Group domain key generator - - - http://uddi.org/pubs/uddi_v3.htm#keyGen - - - - - - - - - Dun and Bradstreet D-U-N-S Number - A unique nine digit identification number, for each physical location of your business. - - - http://fedgov.dnb.com/webform/pages/dunsnumber.jsp - - - - - http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#D-U-N-S - - - - - - - - - - - - ubr-uddi-org:iso-ch:1998:icd - ISO 6523 International Code Designator (ICD) System - - - - http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#ISO6523Code - - http://metadata-stds.org/Document-library/Draft-standards/6523-Identification-of-Organizations/ICD_list.htm - - - - http://metadata-stds.org/Document-library/Draft-standards/6523-Identification-of-Organizations/ICD_list.htm - - - - - - - - - - - dnb-com:D-U-N-S - Dun&Bradstreet D-U-N-S® Number - - This tModel is used for the Dun&Bradstreet D-U-N-S® Number identifier. - http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#D-U-N-S - - - - - - - ntis-gov:naics:1997 - Business Taxonomy: NAICS(1997 Release) - - This tModel defines the NAICS industry taxonomy. - http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#NAICS - - - - - - - - org.jboss.soa.esb.:category - - - - thomasregister-com:supplierID - Thomas Registry Suppliers - - This tModel is used for the Thomas Register supplier identifier codes. - http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#Thomas - - - - - - - uddi-org:general_keywords - Special taxonomy consisting of namespace identifiers and the keywords associated with the namespaces - - This tModel defines an unidentified taxonomy. - http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#GenKW - - - - - - - - - uddi-org:inquiry_v2 - UDDI Inquiry API Version 2 - Core Specification - - This tModel defines the inquiry API calls for interacting with a V2 UDDI node. - http://www.uddi.org/wsdl/inquire_v2.wsdl - - - - - - - - - - uddi-org:isReplacedBy - An identifier system used to point (using UDDI keys) to the tModel (or businessEntity) that is the logical replacement for the one in which isReplacedBy is used - - This is a checked value set. - http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#IsReplacedBy - - - - - - - - uddi-org:iso-ch:3166-1999 - ISO 3166-1:1997 and 3166-2:1998. Codes for names of countries and their subdivisions. Part 1: Country codes. Part 2:Country subdivision codes. Update newsletters include ISO 3166-1 V-1 (1998-02-05), V-2 (1999-10-01), ISO 3166-2 I-1 (1998) - - Taxonomy used to categorize entries by geographic location. - http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#ISO3166 - - - - http://www.iso.org/iso/country_codes - - - - - - - - - uddi-org:operators - Taxonomy for categorizing the businessEntity of an operator of a registry. - - This checked value set is used to identify UDDI operators. - http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#Operators - - - - - - - - uddi-org:owningBusiness - A pointer to a businessEntity that owns the tagged data. - - This tModel indicates the businessEntity that published or owns the tagged tModel. Used with tModels to establish an "owned" relationship with a registered businessEntity. - http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#owningBusiness - - - - - - - - - uddi-org:protocol:http - A tModel that represents the HTTP protocol - - The HTTP Protocol tModel can be used to indicate that a Web service supports the HTTP protocol. - http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#http - - - - - - - uddi-org:protocol:soap - A tModel that represents the SOAP 1.1 protocol - - The SOAP Protocol tModel can be used to indicate that a Web service supports the SOAP 1.1 protocol. - http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#soap - - - - - - - uddi-org:relationships - Starter set classifications of businessEntity relationships - - This tModel is used to describe business relationships. Used in the publisher assertion messages. - http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#Relationships - - - - - - - - uddi-org:taxonomy_v2 - UDDI Taxonomy API Version 2 - Core Specification - - This tModel defines the taxonomy validation API calls for interacting with a V2 UDDI node. - http://www.uddi.org/taxonomies/UDDI_Registry_tModels.htm#TaxV2 - - - - - - - - - uddi-org:types - UDDI Type Taxonomy - - Taxonomy used to categorize Service Descriptions. - http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#UDDItypes - - - - - - - - - uddi-org:wsdl:address - A tModel used to indicate the WSDL address option. - - The WSDL Address tModel provides A mechanism to indicate that the endpoint address should be obtained from a WSDL document. - http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#Address - - - - uddi-org:wsdl:categorization:protocol - Category system used to describe the protocol supported by a wsdl:binding. - - The Protocol Categorization tModel provides a mechanism to capture this protocol information in the UDDI binding tModel. - http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#protocol - - - - - - - - uddi-org:wsdl:categorization:transport - Category system used to describe the transport supported by a wsdl:binding. - - The Transport Categorization tModel provides a mechanism to capture transport information in the UDDI binding tModel which allows a user to search for bindings that implement a specific transport protocol. - http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#transport - - - - - - - - uddi-org:wsdl:portTypeReference - A category system used to reference a wsdl:portType tModel - - The WSDL portType Reference category system provides a mechanism to indicate that a UDDI entity has a relationship with a certain wsdl:portType tModel. - http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#portTypeReference - - - - - - - - uddi-org:wsdl:types - WSDL Type Category System - - The WSDL Entity Type tModel uses a number of UDDI entities to represent the various entities within a WSDL document. - http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#wsdlTypes - - - - - - - - uddi-org:xml:localName - A category system used to indicate XML local names - - The XML Local Name tModel provides a mechanism to indicate the name attribute for the uddi:businessService. - http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#xmlLocalName - - - - - - - - uddi-org:xml:namespace - A category system used to indicate namespaces - - A namespace provides necessary qualifying information about a technical concept or model. The XML Namespace tModel provides a mechanism to associate a namespace with a UDDI entity. - http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#xmlNamespace - - - - - - - - unspsc-org:unspsc - Product Taxonomy: UNSPSC (Version 7.3) - - This tModel defines Version 7.3 of the UNSPSC product taxonomy. - http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#UNSPSC - - - - - - - - - - unspsc-org:unspsc:3-1 - Product Taxonomy: UNSPSC (Version 3.1) - - This tModel defines the UNSPSC product taxonomy. - http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#UNSPSC31 - - - - - - - - ubr-uddi-org:iso-ch:1998:icd - ISO 6523 International Code Designator (ICD) System - - - - http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#ISO6523Code - - - - - - - - - - - ntis-gov:naics:2002 - North American Industry Classification System 2002 - North American Industry Classification System 2002 - Business Taxonomy: NAICS (2002 Release) - - - http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#NAICS2002 - - - - - - - - - - - unspsc-org:unspsc:v6.0501 - Product and Service Category System: United Nations Standard Products and Services Code (UNSPSC) - - - http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#UNSPSCv60501 - - - - - - - - - - - ubr-uddi-org:postalAddress - Postal address structure - - - http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#postal - - - - - - - - - - - - - - - thomasregister-com:key generator - Thomas Registry Suppliers key generator - - - http://uddi.org/pubs/uddi_v3.htm#keyGen - - - - - - - - - Thomas Registry - thomasregister-com:supplierID - This tModel is used for the Thomas Register supplier identifier codes. - - - http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#Thomas - - - - - - - - - - - uddi-org:valueSetValidation_v3 - UDDI Value Set Validation API V3.0 - - - http://uddi.org/wsdl/uddi_vs_v3_binding.wsdl - - - - - http://uddi.org/pubs/uddi_v3.htm#VSValid - - - - - - - - - - - - - uddi-org:valueSetCaching_v3 - UDDI Value Set Caching API V3.0 - - - http://uddi.org/wsdl/uddi_vscache_v3_binding.wsdl - - - - - http://uddi.org/pubs/uddi_v3.htm#VSCaching - - - - - - - - - - - - - uddi-org:validatedBy - Category system used to point a value set or category - group system tModel to associated value set Web service - implementations. - - - - http://uddi.org/pubs/uddi_v3.htm#validatedBy - - - - - - - - - - + + + + + + + + + uddi-org:keyGenerator + UDDI domain key generator + + + http://uddi.org/pubs/uddi_v3.htm#keyGen + + + + + + + + uddi-org:categorization:keyGenerator + + Key Generator for UDDI Categorization tModels + + + + http://uddi.org/pubs/uddi_v3.htm#categorizationKeyGen + + + + + + + + uddi-org:types + UDDI Type Category System + + + http://uddi.org/pubs/uddi_v3.htm#UDDITypes + + + + + + + + + + + uddi-org:general_keywords + Category system consisting of namespace + identifiers and the keywords associated with + the namespaces. + + + + http://uddi.org/pubs/uddi_v3.htm#GenKW + + + + + + + + + uddi-org:sortorder:keyGenerator + + Key Generator for UDDI Sort Order tModels + + + + http://uddi.org/pubs/uddi_v3.htm#sortorderKeyGen + + + + + + + + uddi-org:transport:keyGenerator + + Key Generator for UDDI Transport tModels + + + http://uddi.org/pubs/uddi_v3.htm#transportKeyGen + + + + + + + + uddi-org:protocol:keyGenerator + Key Generator for UDDI Protocol tModels + + + http://uddi.org/pubs/uddi_v3.htm#protocolKeyGen + + + + + + + + uddi-org:inquiry_v3 + UDDI Inquiry API V3.0 + + + http://uddi.org/wsdl/uddi_api_v3_binding.wsdl#UDDI_Inquiry_SoapBinding + + + + + http://uddi.org/pubs/uddi_v3.htm#InqV3 + + + + + + + + + + + uddi-org:nodes + Category system for identifying the nodes + of a registry. + + + + http://uddi.org/pubs/uddi_v3.htm#Nodes + + + + + + + + + + + + uddi-org:publication_v3 + UDDI Publication API V3.0 + + + http://uddi.org/wsdl/uddi_api_v3_binding.wsdl#UDDI_Publication_SoapBinding + + + + + http://uddi.org/pubs/uddi_v3.htm#PubV3 + + + + + + + + + + + uddi-org:security_v3 + UDDI Security API V3.0 + + + http://uddi.org/wsdl/uddi_api_v3_binding.wsdl#UDDI_Security_SoapBinding + + + + + http://uddi.org/pubs/uddi_v3.htm#SecV3 + + + + + + + + + + + + uddi-org:relationships + Basic types of business relationships + + + + http://uddi.org/pubs/uddi_v3.htm#Relationships + + + + + + + + + + uddi-org:owningBusiness_v3 + Category system used to point to the + businessEntity + associated with the publisher of the tModel. + + + + http://uddi.org/pubs/uddi_v3.htm#owningBusiness + + + + + + + + + + + + uddi-org:isReplacedBy + Identifier system used to point to the UDDI + entity, + using UDDI keys, that is the logical replacement + for the one in which isReplacedBy is used. + + + + http://uddi.org/pubs/uddi_v3.htm#IsReplacedBy + + + + + + + + + + + + + + Tax ID + The Tax Identifier for this business + + + + http://uddi.org/pubs/uddi-v3.0.2-20041019.htm#_Toc515847032 + + + + + + + + + + + + + + + + uddi-org:validatedBy + Category system used to point a value set or + category + group system tModel to associated value set Web service + implementations. + + This is typically used on tModels to validate tModel Instances via the Value Set Validation service. The keyValue + should be an existing binding key pointing to that service. + + + + http://uddi.org/pubs/uddi_v3.htm#validatedBy + + + + + + + + + + + + + + + + uddi-org:derivedFrom + Category system for referring tModels to other + tModels for the purpose of reuse. + + + + http://uddi.org/pubs/uddi_v3.htm#DerivedFrom + + + + + + + + + + + + + + uddi-org:derivedFrom + Category system for referring tModels to other + tModels for the purpose of reuse. + + + + http://uddi.org/pubs/uddi_v3.htm#DerivedFrom + + + + + + + + + + + + + + + + uddi-org:entityKeyValues + Category system used to declare that a value set + uses entity keys as valid values. + + + + http://uddi.org/pubs/uddi_v3.htm#entityKeyValues + + + + + + + + + + + + uddi-org:entityKeyValues + Category system used to declare that a value set + uses entity keys as valid values. + + + + http://uddi.org/pubs/uddi_v3.htm#entityKeyValues + + + + + + + + + + + + + + uddi-org:serverAuthenticatedSSL3 + Secure Sockets Layer Version 3.0 with Server + Authentication + + + + http://uddi.org/pubs/uddi_v3.htm#serverSSL3 + + + + + + + + + uddi-org:mutualAuthenticatedSSL3 + + Secure Sockets Layer Version 3.0 with Mutual + Authentication + + + + http://uddi.org/pubs/uddi_v3.htm#mutualSSL3 + + + + + + + + + uddi-org:mutualAuthenticatedSSL3 + + Secure Sockets Layer Version 3.0 with Mutual + Authentication + + + + http://uddi.org/pubs/uddi_v3.htm#mutualSSL3 + + + + + + + + + + uddi-org:http + A Web service that uses HTTP transport + + + http://uddi.org/pubs/uddi_v3.htm#overHTTP + + + + + + + + + uddi-org:http + A Web service that uses HTTP transport + + + http://uddi.org/pubs/uddi_v3.htm#overHTTP + + + + + + + + + + uddi-org:smtp + E-mail based Web service + + + http://uddi.org/pubs/uddi_v3.htm#overSMTP + + + + + + + + + uddi-org:smtp + E-mail based Web service + + + http://uddi.org/pubs/uddi_v3.htm#overSMTP + + + + + + + + + + Human Readable SMTP Email Deliveries + This is a jUDDI extension for providing SMTP based subscription alerts in a human readable fashion. + + + + + + + + + uddi-org:ftp + File Transfer Protocol (FTP) based Web service + + + + http://uddi.org/pubs/uddi_v3.htm#overFTP + + + + + + + + + uddi-org:ftp + File Transfer Protocol (FTP) based Web service + + + + http://uddi.org/pubs/uddi_v3.htm#overFTP + + + + + + + + + uddi-org:fax + Fax-based Web service + + + http://uddi.org/pubs/uddi_v3.htm#overFax + + + + + + + + uddi-org:telephone + Telephone based service + + + http://uddi.org/pubs/uddi_v3.htm#overPhone + + + + + + + + + + + uddi-org:amqp + A Web service that uses the AMQP transport + + + http://www.amqp.org/ + + + + + + + + + + uddi-org:omgdds + A Web service that uses the OMG DDS transport + + + http://portals.omg.org/dds/ + + + + + + + + + + uddi-org:udp + A Web service that uses the UDP transport + + + http://docs.oasis-open.org/ws-dd/soapoverudp/1.1/os/wsdd-soapoverudp-1.1-spec-os.html + + + + + + + + + uddi-org:jms + A Web service that uses the JMS API + + + http://docs.oasis-open.org/ws-dd/soapoverudp/1.1/os/wsdd-soapoverudp-1.1-spec-os.html + + + + + + + + + uddi-org:protocol:rest + A tModel that represents the Representational State Transfer architectural style + + + http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm + + + + + + + + + + + + uddi-org:approximateMatch:SQL99 + + UDDI approximate matching find qualifier + + + + http://uddi.org/pubs/uddi_v3.htm#wildcard + + + + + + + + uddi-org:exactMatch + UDDI exact name matching findQualifier + + + + http://uddi.org/pubs/uddi_v3.htm#exactmatch + + + + + + + + uddi-org:caseInsensitiveMatch + + UDDI case insensitive matching find qualifier + + + + http://uddi.org/pubs/uddi_v3.htm#caseinsens + + + + + + + + uddi-org:caseSensitiveMatch + UDDI Case Sensitive Matching find qualifier + + + + http://uddi.org/pubs/uddi_v3.htm#casesens + + + + + + + + uddi-org:diacriticsInsensitiveMatch + + UDDI Diacritics Insensitive Matching find qualifier + + + + http://uddi.org/pubs/uddi_v3.htm#diacritInsens + + + + + + + + uddi-org:diacriticsSensitiveMatch + + UDDI Diacritics Sensitive Matching find qualifier + + + + http://uddi.org/pubs/uddi_v3.htm#diacritSens + + + + + + + + uddi-org:binarySort + UDDI binary sort sortOrder qualifier + + + + http://uddi.org/pubs/uddi_v3.htm#sortOrd + + + + + + + + + uddi-org:UTS-10 + UDDI Unicode Technical Standard #10 sort + collation sequence find qualifier + + + + http://uddi.org/pubs/uddi_v3.htm#UCASort + + + + + + + + + uddi-org:caseInsensitiveSort + UDDI sort qualifier used to sort results without + regard to case + + + + http://uddi.org/pubs/uddi_v3.htm#caseInsensSort + + + + + + + + uddi-org:caseSensitiveSort + UDDI sort qualifier used to sort results using + case sensitivity + + + + http://uddi.org/pubs/uddi_v3.htm#caseSensSort + + + + + + + + + + uddi-org:sortByNameAsc + UDDI sort qualifier used to sort results by name + in ascending order + + + + http://uddi.org/pubs/uddi_v3.htm#nameAsc + + + + + + + + uddi-org:sortByNameDesc + UDDI sort qualifier used to sort results by + name in descending order + + + + http://uddi.org/pubs/uddi_v3.htm#nameDesc + + + + + + + + uddi-org:sortByDateAsc + UDDI sort qualifier used to sort results by date in + ascending order + + + + http://uddi.org/pubs/uddi_v3.htm#dateAsc + + + + + + + + uddi-org:sortByDateDesc + UDDI sort qualifier used to sort results + by date in descending order + + + + http://uddi.org/pubs/uddi_v3.htm#dateDesc + + + + + + + + uddi-org:andAllKeys + UDDI find qualifier used to request that a + logical AND be performed on bag contents + prior to a search + + + + http://uddi.org/pubs/uddi_v3.htm#andAll + + + + + + + + uddi-org:orAllKeys + UDDI find qualifier used to request that a + logical OR be performed on bag contents + prior to a search + + + + http://uddi.org/pubs/uddi_v3.htm#orAll + + + + + + + + uddi-org:orLikeKeys + UDDI find qualifier used to find entities + that reference one of the values from each + referenced value set + + + + http://uddi.org/pubs/uddi_v3.htm#orLike + + + + + + + + uddi-org:combineCategoryBags + UDDI find qualifier used to treat all of the + categoryBags within a businessEntity as if + they were one during inquiry + + + + http://uddi.org/pubs/uddi_v3.htm#combineCatBags + + + + + + + + uddi-org:serviceSubset + UDDI find qualifier used to use categoryBags + of businessService elements to satisfy the + find_business inquiry. + + + + http://uddi.org/pubs/uddi_v3.htm#servSubset + + + + + + + + uddi-org:bindingSubset + UDDI find qualifier for specifying use of + categoryBags of bindingTempate elements to satisfy + the find_business or find_service inquiries. + + + + http://uddi.org/pubs/uddi_v3.htm#bindSubset + + + + + + + + uddi-org:suppressProjectedServices + + UDDI find qualifier used to exclude service + projections from an inquiry function at all + levels. + + + + http://uddi.org/pubs/uddi_v3.htm#suppressProjSvcs + + + + + + + + uddi-org:signaturePresent + UDDI findQualifier used to return only entities + that have or are contained in entities that have + XML Digital Signatures. + + + + http://uddi.org/pubs/uddi_v3.htm#sign + + + + + + + + uddi-org:hostingRedirector + UDDI Hosting Redirector service specification + + + + http://uddi.org/pubs/uddi_v3.htm#hostDir + + + + + + + + uddi-org:v3_policy + UDDI Policy Description service specification + + + + http://uddi.org/pubs/uddi_v3.htm#policyDesc + + + + + + + + uddi-org:ownership_transfer_v3 + UDDI Custody and Ownership Transfer API V3.0 + + + http://uddi.org/wsdl/uddi_custody_v3_binding.wsdl + + + + + http://uddi.org/pubs/uddi_v3.htm#OwnershipTransfer + + + + + + + + + + + uddi-org:subscription_v3 + UDDI Subscription API V3.0 + + + http://uddi.org/wsdl/uddi_sub_v3_binding.wsdl + + + + + http://uddi.org/pubs/uddi_v3.htm#Sub + + + + + + + + + + + uddi-org:subscriptionListener_v3 + UDDI Subscription Listener API V3.0 + + + http://uddi.org/wsdl/uddi_subr_v3_binding.wsdl + + + + + http://uddi.org/pubs/uddi_v3.htm#Subscribe + + + + + + + + + + + + + uddi-org:wsdl:types + WSDL Type Category System + + + http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#wsdlTypes + + + + + + + + + + uddi-org:wadl:types + WADL Type Category System + + + http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm + + + + + + + + + + + + uddi-org:xml:namespace + A category system used to indicate namespaces + + + http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#xmlNamespace + + + + + + + + + + uddi-org:xml:localName + A category system used to indicate XML local names + + + http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#xmlLocalName + + + + + + + + + + uddi-org:wsdl:portTypeReference + A category system used to reference a wsdl:portType tModel + + + http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#portTypeReference + + + + + + + + + + uddi-org:protocol:soap + A tModel that represents the SOAP 1.1 protocol + + + http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#soap + + + + + + + + + + uddi-org:protocol:soap12 + A tModel that represents the SOAP 1.2 protocol + + + http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#soap + + + + + + + + + + + uddi-org:protocol:http + A tModel that represents the HTTP protocol + + + http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#http + + + + + + + + + uddi-org:wsdl:categorization:protocol + Category system used to describe the protocol supported by a wsdl:binding + + + http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#protocol + + + + + + + + + + uddi-org:wsdl:categorization:transport + Category system used to describe the transport supported by a wsdl:binding + + + http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#transport + + + + + + + + + + uddi-org:wsdl:address + A tModel used to indicate the WSDL address option + + + http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#Address + + + + + + uddi-org:bpel:types + Category system used indicate BPEL processes + + + http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-bpel-20040725.htm + + + + + + + + + + + + + uddi:tmodelkey:keygenerator + + Key Generator for generic UDDI tModel Keys + + + + + + + + + + uddi:tmodelkey:address + Identifies an address. This can be a physical, mailing, or electric address. + + + + + + + + + uddi:tmodelkey:group + Identifies a tModel group. + + + + + + + + uddi:tmodelkey:blank + Identifies a blank tModel + + + + + + + + + + + + + urn:wsdm.org:keygenerator + Key Generator for WSDM.org tModels + + + http://uddi.org/pubs/uddi_v3.htm#protocolKeyGen + + + + + + + + urn:wsdm.org:metric:keygenerator + Key Generator for WSDM.org Metric tModels + + + http://uddi.org/pubs/uddi_v3.htm#protocolKeyGen + + + + + + + + urn:wsdm.org:identity:keygenerator + Key Generator for WSDM.org Identity tModels + + + http://uddi.org/pubs/uddi_v3.htm#protocolKeyGen + + + + + + + + urn:wsdm.org:qos:keygenerator + Key Generator for WSDM.org Quality of Service tModels + + + http://uddi.org/pubs/uddi_v3.htm#protocolKeyGen + + + + + + + + RequestCount + The number of requests to a given service. (number of requests) + + + https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc + + + + + + + + ReplyCount + The number of replies from a given service. (number of replies) + + + https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc + + + + + + + + FaultCount + The number of faults from a given service. (number of faults) + + + https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc + + + + + + + + ResourceId + This is the unique identity by which the resource (service) is known to the management system. It is useful for further queries. (resource identification in URI format) + + + https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc + + + + + + + + + LastUpdateTime + Represents the last time this metric was updated. (time value) + + + https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc + + + + + + + + + ResponseTime_Average + Average response time of the service. (numeric value or symbolic rating) + + + https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc + + + + + + + + Throughput_count + Throughput count. (numeric value or symbolic rating) + + + https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc + + + + + + + + Throughput_bytes + Throughput bytes. (numeric value or symbolic rating) + + + https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc + + + + + + + + Reliability + Reliability or the measure of. (numeric value or symbolic rating) + + + https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc + + + + + + + + ReportingPeriodStart + The beginning on the reporting time period used for the information above. (dateTime) + + + https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc + + + + + + + + ReportingPeriodEnd + The end of the reporting time period used for the information above. (dateTime) + + + https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc + + + + + + + + UpdateInterval + How often is this information updated in UDDI (it is not assumed to be realtime). (duration) + + + https://www.oasis-open.org/committees/download.php/6227/uddi-spec-tc-tn-QoS-metrics-20040224.doc + + + + + + + + + Service Interface Version + When using this tModel as a tModelInstance, it can be used to describe a version associated with either a service interface, a bindingTemplate service instance. Note: This is a jUDDI specific addon and may not be present in other registries. + + + http://www.ibm.com/developerworks/webservices/library/ws-version/ + + + + + + + + + ubr-uddi-org:iso-ch:3166-2003 + ISO 3166 Country Codes + When used in a Category Bag for a Business or Service, it can indicate the physical or logically location of the Business or Service. + ISO 3166 Codes for names of countries or regions. Updated with newsletters ISO 3166-1 V-1, V-2, V-3, V-4, V-5, V-6, V-7, ISO 3166-2 I-1, I-2, I-3, I-4. + + + http://www.iso.org/iso/country_codes + + + + + http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#ISO3166 + + + + + + + + + + + + + + United Nations Standard Products and Services Code with ISO 3166 Grouping + Grouping of the category systems for UNSPSC and ISO 3166. As a consequence, keyedReferenceGroups that reference this tModel describe countries or regions where a product category is offered. + + + http://uddi.org/pubs/uddi-v3.0.2-20041019.htm#_Toc535251470 + + + + + http://www.unspsc.org/ + + + + + + + + + + + + + World Geodetic System Key Generator + Key Generator for Standard for use in cartography, geodesy, and navigation. + + + http://www.ngs.noaa.gov/PUBS_LIB/Geodesy4Layman/TR80003E.HTM#ZZ11 + + + + + http://uddi.org/pubs/uddi_v3.htm#protocolKeyGen + + + + + + + + + World Geodetic System + Standard for use in cartography, geodesy, and navigation. + + + http://www.ngs.noaa.gov/PUBS_LIB/Geodesy4Layman/TR80003E.HTM#ZZ11 + + + + + + + + + + WGS Latitude + Standard for use in cartography, geodesy, and navigation. + + + http://www.ngs.noaa.gov/PUBS_LIB/Geodesy4Layman/TR80003E.HTM#ZZ11 + + + + + + + + + WGS Longitude + Standard for use in cartography, geodesy, and navigation. + + + http://www.ngs.noaa.gov/PUBS_LIB/Geodesy4Layman/TR80003E.HTM#ZZ11 + + + + + + + + + WGS Geographic Precision + Standard for use in cartography, geodesy, and navigation. + + + http://www.ngs.noaa.gov/PUBS_LIB/Geodesy4Layman/TR80003E.HTM#ZZ11 + + + + + + + + + + + + Universal Business Registry Key Generator + UBR domain key generator + + + http://uddi.org/pubs/uddi_v3.htm#keyGen + + + + + + + + Universal Business Registry Categorization Group Key Generator + UBR Categorization Group domain key generator + + + http://uddi.org/pubs/uddi_v3.htm#keyGen + + + + + + + + + Universal Business Registry Categorization Key Generator + UBR Categorization domain key generator + + + http://uddi.org/pubs/uddi_v3.htm#keyGen + + + + + + + + + ubr-uddi-org:postalAddress + Postal address structure + + + http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#postal + + + + + + + + + + + ubr-uddi-org:relationships + relationships in a UBR + + + http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm + + + + + + + + + ubr-uddi-org:identifier key generator + UBR Identifier Group domain key generator + + + http://uddi.org/pubs/uddi_v3.htm#keyGen + + + + + + + + + UBR Identifier Owning Business + Identifier for an Owning Business in a UBR + + + http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm + + + + + + + + + UBR Categorization United Nations Standard Products and Services Code + UNSPSC Categorization in a UBR + + + http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm + + + + + http://www.unspsc.org/ + + + + + + + + + + + + + + + North American Industry Classification System Key Generator + North American Industry Classification System Key Generator. + The North American Industry Classification System (NAICS) is the standard used by Federal statistical agencies in classifying business establishments for the purpose of collecting, analyzing, and publishing statistical data in the U.S. business economy + + + http://uddi.org/pubs/uddi_v3.htm#keyGen + + + https://www.census.gov/eos/www/naics/index.html + + + + + + + + + + + North American Industry Classification System 1997 + North American Industry Classification System 1997 + + + https://www.census.gov/eos/www/naics/reference_files_tools/1997/1997.html + + + + + + http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#NAICS + + + + + + + + + + + + + North American Industry Classification System 2012 + North American Industry Classification System 2012 + + + https://www.census.gov/cgi-bin/sssd/naics/naicsrch?chart=2012 + + + + + + + + + ntis-gov:naics:2002 + North American Industry Classification System 2002 + North American Industry Classification System 2002 + Business Taxonomy: NAICS (2002 Release) + + + https://www.census.gov/cgi-bin/sssd/naics/naicsrch?chart=2002 + + + + + http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#NAICS2002 + + + + + + + + + + + + + North American Industry Classification System 2007 + North American Industry Classification System 2007 + + + https://www.census.gov/cgi-bin/sssd/naics/naicsrch?chart=2007 + + + + + + + + + + + + UBR Taxonomies + Universal Business Registry Taxonomy Key Generator. + + + http://uddi.org/pubs/uddi_v3.htm#keyGen + + + + + + + + + North American Industry Classification System Taxonomy + North American Industry Classification System Taxonomy + + + https://www.census.gov/eos/www/naics/index.html + + + + + + + + + + + uddi-org:JIS-X4061 + UDDI JIS X 4061 Japanese + collation sequence find qualifier + + + + http://uddi.org/pubs/uddi-v3.0.2-20041019.htm#_Toc42047570 + + + + + + + + + + + ubr-uddi-org:identifier for dnb.com + UBR Identifier dnb.com Group domain key generator + + + http://uddi.org/pubs/uddi_v3.htm#keyGen + + + + + + + + + Dun and Bradstreet D-U-N-S Number + A unique nine digit identification number, for each physical location of your business. + + + http://fedgov.dnb.com/webform/pages/dunsnumber.jsp + + + + + http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#D-U-N-S + + + + + + + + + + + + ubr-uddi-org:iso-ch:1998:icd + ISO 6523 International Code Designator (ICD) System + + + + http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#ISO6523Code + + http://metadata-stds.org/Document-library/Draft-standards/6523-Identification-of-Organizations/ICD_list.htm + + + + http://metadata-stds.org/Document-library/Draft-standards/6523-Identification-of-Organizations/ICD_list.htm + + + + + + + + + + + dnb-com:D-U-N-S + Dun&Bradstreet D-U-N-S® Number + + This tModel is used for the Dun&Bradstreet D-U-N-S® Number identifier. + http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#D-U-N-S + + + + + + + ntis-gov:naics:1997 + Business Taxonomy: NAICS(1997 Release) + + This tModel defines the NAICS industry taxonomy. + http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#NAICS + + + + + + + + org.jboss.soa.esb.:category + + + + thomasregister-com:supplierID + Thomas Registry Suppliers + + This tModel is used for the Thomas Register supplier identifier codes. + http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#Thomas + + + + + + + uddi-org:general_keywords + Special taxonomy consisting of namespace identifiers and the keywords associated with the namespaces + + This tModel defines an unidentified taxonomy. + http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#GenKW + + + + + + + + + uddi-org:inquiry_v2 + UDDI Inquiry API Version 2 - Core Specification + + This tModel defines the inquiry API calls for interacting with a V2 UDDI node. + http://www.uddi.org/wsdl/inquire_v2.wsdl + + + + + + + + + + uddi-org:isReplacedBy + An identifier system used to point (using UDDI keys) to the tModel (or businessEntity) that is the logical replacement for the one in which isReplacedBy is used + + This is a checked value set. + http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#IsReplacedBy + + + + + + + + uddi-org:iso-ch:3166-1999 + ISO 3166-1:1997 and 3166-2:1998. Codes for names of countries and their subdivisions. Part 1: Country codes. Part 2:Country subdivision codes. Update newsletters include ISO 3166-1 V-1 (1998-02-05), V-2 (1999-10-01), ISO 3166-2 I-1 (1998) + + Taxonomy used to categorize entries by geographic location. + http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#ISO3166 + + + + http://www.iso.org/iso/country_codes + + + + + + + + + uddi-org:operators + Taxonomy for categorizing the businessEntity of an operator of a registry. + + This checked value set is used to identify UDDI operators. + http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#Operators + + + + + + + + uddi-org:owningBusiness + A pointer to a businessEntity that owns the tagged data. + + This tModel indicates the businessEntity that published or owns the tagged tModel. Used with tModels to establish an "owned" relationship with a registered businessEntity. + http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#owningBusiness + + + + + + + + + uddi-org:protocol:http + A tModel that represents the HTTP protocol + + The HTTP Protocol tModel can be used to indicate that a Web service supports the HTTP protocol. + http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#http + + + + + + + uddi-org:protocol:soap + A tModel that represents the SOAP 1.1 protocol + + The SOAP Protocol tModel can be used to indicate that a Web service supports the SOAP 1.1 protocol. + http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#soap + + + + + + + uddi-org:relationships + Starter set classifications of businessEntity relationships + + This tModel is used to describe business relationships. Used in the publisher assertion messages. + http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#Relationships + + + + + + + + uddi-org:taxonomy_v2 + UDDI Taxonomy API Version 2 - Core Specification + + This tModel defines the taxonomy validation API calls for interacting with a V2 UDDI node. + http://www.uddi.org/taxonomies/UDDI_Registry_tModels.htm#TaxV2 + + + + + + + + + uddi-org:types + UDDI Type Taxonomy + + Taxonomy used to categorize Service Descriptions. + http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#UDDItypes + + + + + + + + + uddi-org:wsdl:address + A tModel used to indicate the WSDL address option. + + The WSDL Address tModel provides A mechanism to indicate that the endpoint address should be obtained from a WSDL document. + http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#Address + + + + uddi-org:wsdl:categorization:protocol + Category system used to describe the protocol supported by a wsdl:binding. + + The Protocol Categorization tModel provides a mechanism to capture this protocol information in the UDDI binding tModel. + http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#protocol + + + + + + + + uddi-org:wsdl:categorization:transport + Category system used to describe the transport supported by a wsdl:binding. + + The Transport Categorization tModel provides a mechanism to capture transport information in the UDDI binding tModel which allows a user to search for bindings that implement a specific transport protocol. + http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#transport + + + + + + + + uddi-org:wsdl:portTypeReference + A category system used to reference a wsdl:portType tModel + + The WSDL portType Reference category system provides a mechanism to indicate that a UDDI entity has a relationship with a certain wsdl:portType tModel. + http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#portTypeReference + + + + + + + + uddi-org:wsdl:types + WSDL Type Category System + + The WSDL Entity Type tModel uses a number of UDDI entities to represent the various entities within a WSDL document. + http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#wsdlTypes + + + + + + + + uddi-org:xml:localName + A category system used to indicate XML local names + + The XML Local Name tModel provides a mechanism to indicate the name attribute for the uddi:businessService. + http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#xmlLocalName + + + + + + + + uddi-org:xml:namespace + A category system used to indicate namespaces + + A namespace provides necessary qualifying information about a technical concept or model. The XML Namespace tModel provides a mechanism to associate a namespace with a UDDI entity. + http://www.oasis-open.org/committees/uddi-spec/doc/tn/uddi-spec-tc-tn-wsdl-v2.htm#xmlNamespace + + + + + + + + unspsc-org:unspsc + Product Taxonomy: UNSPSC (Version 7.3) + + This tModel defines Version 7.3 of the UNSPSC product taxonomy. + http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#UNSPSC + + + + + + + + + + unspsc-org:unspsc:3-1 + Product Taxonomy: UNSPSC (Version 3.1) + + This tModel defines the UNSPSC product taxonomy. + http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#UNSPSC31 + + + + + + + + ubr-uddi-org:iso-ch:1998:icd + ISO 6523 International Code Designator (ICD) System + + + + http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#ISO6523Code + + + + + + + + + + + ntis-gov:naics:2002 + North American Industry Classification System 2002 + North American Industry Classification System 2002 + Business Taxonomy: NAICS (2002 Release) + + + http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#NAICS2002 + + + + + + + + + + + unspsc-org:unspsc:v6.0501 + Product and Service Category System: United Nations Standard Products and Services Code (UNSPSC) + + + http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#UNSPSCv60501 + + + + + + + + + + + ubr-uddi-org:postalAddress + Postal address structure + + + http://uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#postal + + + + + + + + + + + + + + + thomasregister-com:key generator + Thomas Registry Suppliers key generator + + + http://uddi.org/pubs/uddi_v3.htm#keyGen + + + + + + + + + Thomas Registry + thomasregister-com:supplierID + This tModel is used for the Thomas Register supplier identifier codes. + + + http://www.uddi.org/taxonomies/UDDI_Taxonomy_tModels.htm#Thomas + + + + + + + + + + + uddi-org:valueSetValidation_v3 + UDDI Value Set Validation API V3.0 + + + http://uddi.org/wsdl/uddi_vs_v3_binding.wsdl + + + + + http://uddi.org/pubs/uddi_v3.htm#VSValid + + + + + + + + + + + + + uddi-org:valueSetCaching_v3 + UDDI Value Set Caching API V3.0 + + + http://uddi.org/wsdl/uddi_vscache_v3_binding.wsdl + + + + + http://uddi.org/pubs/uddi_v3.htm#VSCaching + + + + + + + + + + + + + uddi-org:validatedBy + Category system used to point a value set or category + group system tModel to associated value set Web service + implementations. + + + + http://uddi.org/pubs/uddi_v3.htm#validatedBy + + + + + + + + + + \ No newline at end of file diff --git a/juddi-core/src/main/resources/juddi_install_data/root_BusinessEntity.xml b/juddi-core-openjpa/src/main/resources/juddi_install_data/root_BusinessEntity.xml similarity index 98% rename from juddi-core/src/main/resources/juddi_install_data/root_BusinessEntity.xml rename to juddi-core-openjpa/src/main/resources/juddi_install_data/root_BusinessEntity.xml index 826bbedde..e0cf09da8 100644 --- a/juddi-core/src/main/resources/juddi_install_data/root_BusinessEntity.xml +++ b/juddi-core-openjpa/src/main/resources/juddi_install_data/root_BusinessEntity.xml @@ -1,668 +1,668 @@ - - - - - - An Apache jUDDI Node - - This is a UDDI registry node as implemented by Apache jUDDI. - - - ${juddi.server.baseurl} - - - - - - - - - UDDI Inquiry Service - Web Service supporting UDDI Inquiry API - - - UDDI Inquiry API V3 - - ${juddi.server.baseurl}/services/inquiry?wsdl - - - - - - - - uddi:uddi.org:sortorder:binarysort - - - ]]> - - - - - - - - - - - - - - UDDI Inquiry API V3 SSL - - ${juddi.server.baseurlsecure}/services/inquiry?wsdl - - - - - - - - uddi:uddi.org:sortorder:binarysort - - - ]]> - - - - - - - - - - - - - - - - - - - - - - UDDIv2 Inquiry Service - Web Service supporting UDDIv2 Inquiry API - - - UDDI Inquiry API V2 - - ${juddi.server.baseurl}/services/inquiryv2?wsdl - - - - - - - - - - - - UDDI Inquiry API V3 SSL - - ${juddi.server.baseurlsecure}/services/inquiryv2?wsdl - - - - - - - - - - - - - - - - - - - UDDI Inquiry REST Service - Web Service supporting UDDI Inquiry API via HTTP GET - - - UDDI Inquiry API V3 REST - - - - - ${juddi.server.baseurl}/services/inquiryRest?_wadl - - - - - - UDDI Inquiry API V3 REST SSL - ${juddi.server.baseurlsecure}/services/inquiryRest?_wadl - - - - - - - - - - - - - - - - - - - UDDI Publish Service - Web Service supporting UDDI Publish API - - - UDDI Publication API V3 - ${juddi.server.baseurl}/services/publish?wsdl - - - - - - - required - - ]]> - - - - - - - - - - - - - - UDDI Publication API V3 SSL - ${juddi.server.baseurlsecure}/services/publish?wsdl - - - - - - - required - - ]]> - - - - - - - - - - - - - - - - - - - - - - - - - UDDIv2 Publish Service - Web Service supporting UDDIv2 Publish API - - - UDDIv2 Publication API V2 - ${juddi.server.baseurl}/services/publishv2?wsdl - - - - - - - - - - UDDI Publication API V2 SSL - ${juddi.server.baseurlsecure}/services/publishv2?wsdl - - - - - - - - - - - - - - - - - - - - - UDDI Security Service - Web Service supporting UDDI Security API - - - UDDI Security API V3 - ${juddi.server.baseurl}/services/security?wsdl - - - - - - - - - - - - - UDDI Security API V3 SSL - ${juddi.server.baseurlsecure}/services/security?wsdl - - - - - - - - - - - - - - - - - - - - - UDDI Custody and Ownership Transfer Service - Web Service supporting UDDI Custody and Ownership Transfer API - - - UDDI Custody and Ownership Transfer API V3 - ${juddi.server.baseurl}/services/custody-transfer?wsdl - - - - - - - required - - ]]> - - - - - - - - - - - - - - - - UDDI Custody and Ownership Transfer API V3 SSL - ${juddi.server.baseurlsecure}/services/custody-transfer?wsdl - - - - - - - required - - ]]> - - - - - - - - - - - - - - - - - - - - - - - - - UDDI Subscription Service - Web Service supporting UDDI Subscription API - - - UDDI Subscription API V3 - ${juddi.server.baseurl}/services/subscription?wsdl - - - - - - - required - supported - - ]]> - - - - - - - - - - - - - - UDDI Subscription API V3 SSL - ${juddi.server.baseurlsecure}/services/subscription?wsdl - - - - - - - required - supported - - ]]> - - - - - - - - - - - - - - - - - - - - - - UDDI Subscription Listener Service - Web Service supporting UDDI Subscription Listener API - - - UDDI Subscription Listener API V3 - ${juddi.server.baseurl}/services/subscription-listener?wsdl - - - - - - - - - - - - - UDDI Subscription Listener API V3 SSL - ${juddi.server.baseurlsecure}/services/subscription-listener?wsdl - - - - - - - - - - - - - - - - - - - - - - - - UDDI Value Set API Service - Web Service supporting UDDI Value Set Validation service. This service provides tModel value validation and is - configured using the jUDDI Publisher Service - - - UDDI Value Set Validation API Version 3 - ${juddi.server.baseurl}/services/valueset-validation?wsdl - - - - - - - - - - UDDI Value Set Validation API Version 3 SSL - ${juddi.server.baseurlsecure}/services/valueset-validation?wsdl - - - - - - - - - - - - UDDI Value Set Validation API Version 3 using InVM Classpath Transport. Use this endpoint for Value Set Validation when - located on the same instance of jUDDI. - classpath:/org.apache.juddi.api.impl.UDDIValueSetValidationImpl - - - - - - - - - - - UDDI Value Set Caching API Service - Web Service supporting UDDI Value Set Caching service. This service provides tModel value validation and is - configured using the jUDDI Publisher Service - - - UDDI Value Set Caching API Version 3 - ${juddi.server.baseurl}/services/valueset-caching?wsdl - - - - - - - - - - UDDI Value Set caching API Version 3 SSL - ${juddi.server.baseurlsecure}/services/valueset-caching?wsdl - - - - - - - - - - - - - - - - - - - - - - UDDI Replication API Version 3 - UDDI Replication API Version 3 - - - UDDI Value Set Validation API Version 3 - ${juddi.server.baseurl}/services/replication?wsdl - - - - - - - - - - - - - - - - - jUDDI Publisher Service - Web Service supporting jUDDI specific API - - - jUDDI Publisher Service API V3 - ${juddi.server.baseurl}/services/publisher?wsdl - - - - - - - - - - jUDDI Publisher Service API V3 SSL - ${juddi.server.baseurlsecure}/services/publisher?wsdl - - - - - - - - - - - - - - - - - - - - - - - + + + + + + An Apache jUDDI Node + + This is a UDDI registry node as implemented by Apache jUDDI. + + + ${juddi.server.baseurl} + + + + + + + + + UDDI Inquiry Service + Web Service supporting UDDI Inquiry API + + + UDDI Inquiry API V3 + + ${juddi.server.baseurl}/services/inquiry?wsdl + + + + + + + + uddi:uddi.org:sortorder:binarysort + + + ]]> + + + + + + + + + + + + + + UDDI Inquiry API V3 SSL + + ${juddi.server.baseurlsecure}/services/inquiry?wsdl + + + + + + + + uddi:uddi.org:sortorder:binarysort + + + ]]> + + + + + + + + + + + + + + + + + + + + + + UDDIv2 Inquiry Service + Web Service supporting UDDIv2 Inquiry API + + + UDDI Inquiry API V2 + + ${juddi.server.baseurl}/services/inquiryv2?wsdl + + + + + + + + + + + + UDDI Inquiry API V3 SSL + + ${juddi.server.baseurlsecure}/services/inquiryv2?wsdl + + + + + + + + + + + + + + + + + + + UDDI Inquiry REST Service + Web Service supporting UDDI Inquiry API via HTTP GET + + + UDDI Inquiry API V3 REST + + + + + ${juddi.server.baseurl}/services/inquiryRest?_wadl + + + + + + UDDI Inquiry API V3 REST SSL + ${juddi.server.baseurlsecure}/services/inquiryRest?_wadl + + + + + + + + + + + + + + + + + + + UDDI Publish Service + Web Service supporting UDDI Publish API + + + UDDI Publication API V3 + ${juddi.server.baseurl}/services/publish?wsdl + + + + + + + required + + ]]> + + + + + + + + + + + + + + UDDI Publication API V3 SSL + ${juddi.server.baseurlsecure}/services/publish?wsdl + + + + + + + required + + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + UDDIv2 Publish Service + Web Service supporting UDDIv2 Publish API + + + UDDIv2 Publication API V2 + ${juddi.server.baseurl}/services/publishv2?wsdl + + + + + + + + + + UDDI Publication API V2 SSL + ${juddi.server.baseurlsecure}/services/publishv2?wsdl + + + + + + + + + + + + + + + + + + + + + UDDI Security Service + Web Service supporting UDDI Security API + + + UDDI Security API V3 + ${juddi.server.baseurl}/services/security?wsdl + + + + + + + + + + + + + UDDI Security API V3 SSL + ${juddi.server.baseurlsecure}/services/security?wsdl + + + + + + + + + + + + + + + + + + + + + UDDI Custody and Ownership Transfer Service + Web Service supporting UDDI Custody and Ownership Transfer API + + + UDDI Custody and Ownership Transfer API V3 + ${juddi.server.baseurl}/services/custody-transfer?wsdl + + + + + + + required + + ]]> + + + + + + + + + + + + + + + + UDDI Custody and Ownership Transfer API V3 SSL + ${juddi.server.baseurlsecure}/services/custody-transfer?wsdl + + + + + + + required + + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + UDDI Subscription Service + Web Service supporting UDDI Subscription API + + + UDDI Subscription API V3 + ${juddi.server.baseurl}/services/subscription?wsdl + + + + + + + required + supported + + ]]> + + + + + + + + + + + + + + UDDI Subscription API V3 SSL + ${juddi.server.baseurlsecure}/services/subscription?wsdl + + + + + + + required + supported + + ]]> + + + + + + + + + + + + + + + + + + + + + + UDDI Subscription Listener Service + Web Service supporting UDDI Subscription Listener API + + + UDDI Subscription Listener API V3 + ${juddi.server.baseurl}/services/subscription-listener?wsdl + + + + + + + + + + + + + UDDI Subscription Listener API V3 SSL + ${juddi.server.baseurlsecure}/services/subscription-listener?wsdl + + + + + + + + + + + + + + + + + + + + + + + + UDDI Value Set API Service + Web Service supporting UDDI Value Set Validation service. This service provides tModel value validation and is + configured using the jUDDI Publisher Service + + + UDDI Value Set Validation API Version 3 + ${juddi.server.baseurl}/services/valueset-validation?wsdl + + + + + + + + + + UDDI Value Set Validation API Version 3 SSL + ${juddi.server.baseurlsecure}/services/valueset-validation?wsdl + + + + + + + + + + + + UDDI Value Set Validation API Version 3 using InVM Classpath Transport. Use this endpoint for Value Set Validation when + located on the same instance of jUDDI. + classpath:/org.apache.juddi.api.impl.UDDIValueSetValidationImpl + + + + + + + + + + + UDDI Value Set Caching API Service + Web Service supporting UDDI Value Set Caching service. This service provides tModel value validation and is + configured using the jUDDI Publisher Service + + + UDDI Value Set Caching API Version 3 + ${juddi.server.baseurl}/services/valueset-caching?wsdl + + + + + + + + + + UDDI Value Set caching API Version 3 SSL + ${juddi.server.baseurlsecure}/services/valueset-caching?wsdl + + + + + + + + + + + + + + + + + + + + + + UDDI Replication API Version 3 + UDDI Replication API Version 3 + + + UDDI Value Set Validation API Version 3 + ${juddi.server.baseurl}/services/replication?wsdl + + + + + + + + + + + + + + + + + jUDDI Publisher Service + Web Service supporting jUDDI specific API + + + jUDDI Publisher Service API V3 + ${juddi.server.baseurl}/services/publisher?wsdl + + + + + + + + + + jUDDI Publisher Service API V3 SSL + ${juddi.server.baseurlsecure}/services/publisher?wsdl + + + + + + + + + + + + + + + + + + + + + + + diff --git a/juddi-core/src/main/resources/juddi_install_data/root_Publisher.xml b/juddi-core-openjpa/src/main/resources/juddi_install_data/root_Publisher.xml similarity index 97% rename from juddi-core/src/main/resources/juddi_install_data/root_Publisher.xml rename to juddi-core-openjpa/src/main/resources/juddi_install_data/root_Publisher.xml index ad3e3867c..a5949f187 100644 --- a/juddi-core/src/main/resources/juddi_install_data/root_Publisher.xml +++ b/juddi-core-openjpa/src/main/resources/juddi_install_data/root_Publisher.xml @@ -1,21 +1,21 @@ - - - - root publisher - true - + + + + root publisher + true + diff --git a/juddi-core/src/main/resources/juddi_install_data/root_replicationConfiguration.xml b/juddi-core-openjpa/src/main/resources/juddi_install_data/root_replicationConfiguration.xml similarity index 100% rename from juddi-core/src/main/resources/juddi_install_data/root_replicationConfiguration.xml rename to juddi-core-openjpa/src/main/resources/juddi_install_data/root_replicationConfiguration.xml diff --git a/juddi-core/src/main/resources/juddi_install_data/root_tModelKeyGen.xml b/juddi-core-openjpa/src/main/resources/juddi_install_data/root_tModelKeyGen.xml similarity index 97% rename from juddi-core/src/main/resources/juddi_install_data/root_tModelKeyGen.xml rename to juddi-core-openjpa/src/main/resources/juddi_install_data/root_tModelKeyGen.xml index 9cbb5806e..73c0c8ad6 100644 --- a/juddi-core/src/main/resources/juddi_install_data/root_tModelKeyGen.xml +++ b/juddi-core-openjpa/src/main/resources/juddi_install_data/root_tModelKeyGen.xml @@ -1,40 +1,40 @@ - - - - - uddi-org:keyGenerator - Root domain key generator - - - http://uddi.org/pubs/uddi_v3.htm#keyGen - - - - - + + + + + uddi-org:keyGenerator + Root domain key generator + + + http://uddi.org/pubs/uddi_v3.htm#keyGen + + + + + diff --git a/juddi-core/src/main/resources/messages.properties b/juddi-core-openjpa/src/main/resources/messages.properties similarity index 98% rename from juddi-core/src/main/resources/messages.properties rename to juddi-core-openjpa/src/main/resources/messages.properties index 817f5c3f5..f91d8701e 100644 --- a/juddi-core/src/main/resources/messages.properties +++ b/juddi-core-openjpa/src/main/resources/messages.properties @@ -1,312 +1,312 @@ -#/* -# * Copyright 2001-2008 The Apache Software Foundation. -# * -# * 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. -# * -# */ - -# Global base messages file. - -#-- UDDI-specific messages -E_accountLimitExceeded=Save request exceeds the quantity limits for a given data type. -E_assertionNotFound=Publisher assertion cannot be identified in a save or delete operation. -E_authTokenExpired=Authentication token information has timed out. -E_authTokenRequired=Authentication token is missing or is invalid. -E_busy=The request cannot be processed at the current time. -E_categorizationNotAllowed= -E_fatalError=A serious technical error has occurred while processing the request. -E_historyDataNotAvailable=Requested history data is not available for the time period requested. -E_invalidCategory= -E_invalidCompletionStatus=Assertion status value passed is unrecognized. -E_invalidCombination=Invalid find qualifier combination -E_invalidKeyPassed=An invalid key has been passed -E_invalidProjection=An attempt was made to save a businessEntity containing a service projection where the serviceKey does not belong to the business designated by the businessKey. -E_invalidTime=The time period, the date/time, or the pair of date/time is invalid. -E_invalidURLPassed= -E_invalidValue=A value that was passed in a keyValue attribute did not pass validation. -E_invalidValueAddressLine=Each addressLine element MAY be adorned with two optional descriptive attributes, keyName and keyValue. Both attributes MUST be present in each address line if a tModelKey is specified in the address structure. Elements with errors: -E_keyRetired=The specified key was retired - -E_keyUnavailable=The proposed key is in a partition that has already been assigned to some other publisher. -E_languageError=Language error -E_messageTooLarge=The message is too large. -E_nameTooLong=The name is too large -E_operatorMismatch=Operator Mismatch -E_publisherCancelled= -E_requestDenied=Subscription cannot be renewed. -E_requestTimeout=The request could not be carried out because a needed Web service did not respond in a reasonable amount of time. -E_resultSetTooLarge=The UDDI node deems that a result set from an inquiry is too large, and requests to obtain the results are not honored, even using subsets. -E_secretUnknown= -E_success= -E_tokenAlreadyExists=Key already exists in transfer request -E_tooManyOptions=Too many options -E_transferAborted=Transfer Aborted -E_transferNotAllowed=The transfer request is not allowed -E_transferNotAllowedUnknownNode=The transfer request is not allowed because the destination node is not in the replication config. -E_transferBlocked=The transfer was blocked from it's originator (node to node transfer). -E_unknownUser=The user ID and password pair passed in a get_authToken API is not known to the UDDI node or is not valid. -E_unrecognizedVersion=The value of the namespace attribute is unsupported by the node being queried. -E_unsupported=Unsupported feature or API. -E_unvalidatable=An attempt was made to reference a value set in a keyedReference whose tModel is categorized with the unvalidatable categorization. -E_userMismatch=An attempt was made to use the publishing API to change data that is controlled by another party. -E_valueNotAllowed=A value did not pass validation because of contextual issues. - - -#-- General error messages -errors.stringEncoding=non-UTF8 token -errors.DatatypeFactor=Can't create a DatatypeFactory instance. -errors.Unspecified=An unspecified error occurred -errors.Unsupported=This version does not support this feature or API -errros.UnsupportedAuthenticator=This selected authenticator does not support AuthTokens. -errors.Unsupported.findQualifier=An invalid or unsupported findQualifier value was passed -errors.configuration.Retrieval=An error occurred attempting to retrieve configuration information -errors.install.AlreadyInstalled=It appears that the application is already installed. Please un-install before proceeding. -errors.NullInput=No input was provided for this API call -errors.keyunavailable.BadPartition=The proposed key is not within the partition defined by owning publisher. If you're trying to create a new tModel in a new partition, try creating a tModel that ends in :keygenerator. Failing key -errors.keyunavailable.KeyExists=The key used for the save operation already exists. Another key must be chosen -errors.invalidkey.NullKey=The key cannot be null -errors.invalidkey.MalformedKey=The passed key does not conform to UDDI v3 rules -errors.invalidkey.KeyGenSuffix=The passed key generator key does not end with the appropriate suffix -errors.invalidkey.NoKeys=No keys passed. At least one key must be passed -errors.invalidkey.ClerkNotFound=The clerk was not found for the given name -errors.invalidkey.DuplicateKey=A duplicate key was passed. No duplicates are allowed -errors.invalidkey.PublisherNotFound=The publisher was not found for the given id -errors.invalidkey.EntityNotFound=The entity was not found for the given id -errors.invalidkey.BusinessNotFound=The business entity was not found for the given key -errors.invalidkey.ServiceNotFound=The business service was not found for the given key -errors.invalidkey.BindingTemplateNotFound=The binding template was not found for the given key -errors.invalidkey.TModelNotFound=The technical model was not found for the given key -errors.invalidkey.TModelNodeOwner=You've attempted to delete a tModel that is not owned by this node. Access the owning node to delete. -errors.invalidkey.ParentServiceNotFound=The business service parent was not found for the given key -errors.invalidkey.ParentBusinessNotFound=The business entity parent was not found for the given key -errors.invalidkey.ServiceKeyNotProvidedWithProjection=Attempting to project a service when the service key was not provided. The non-owning businessEntity cannot generate a key for a projected service -errors.invalidkey.ProjectedServiceNotFound=Attempting to project a service when the service does not exist -errors.invalidkey.businessservice.ParentMismatch=The service being saved has a different parent business key then the one provided -errors.invalidkey.bindingtemplate.ParentMismatch=The binding template being saved has a different parent service key then the one provided -errors.invalidkey.SubscriptionNotFound=The subscription was not found for the given key -errors.invalidKey.KeysOwned=Either the to key for the from key must be specified on a keysOwned structure -errors.invalidkey.SubscripKeyNotFound=The subscriptionKey was not found for the given id -errors.invalidkey.NodeNotFound=The node was not found for the key given name -errors.invalidprojection.ParentMismatch=The supplied business key doesn't match the actual business key of the service being projected -errors.usermismatch.InvalidOwner=The user is not authorized to access the given entity -errors.usermismatch.InvalidOwnerParent=The user is not authorized to access the given parent entity -errors.config.InvalidTokenExpirationSetting=The authentication token expiration setting is missing or invalid, will default to 15 minutes. See juddiv3.properties file -errors.accessPoint.bindingtemplateRedirect.keynotexist=The access point contains a useType specifying a referenced binding template which does not exist. -errors.accessPoint.hostingRedirector.notaurl=The access point value is not a valid URL. This URL should be a URL to another UDDI registry -#-- Error messages related to entities and other data structures -errors.savebusiness.NoInput=At least one BusinessEntity must be provided -errors.saveservice.NoInput=At least one BusinessService must be provided -errors.savebinding.NoInput=At least one BindingTemplate must be provided -errors.saveclientsubscriptionKey.NoInput=The SubscriptionKey must be provided -errors.saveClerk.NoInput=At least one Clerk must be provided -errors.saveNodes.NoInput=At least one Node must be provided -errors.deleteNode.NoInput=A node id must be specified -errors.deleteNode.NotFound=The specified node could not be found. -errors.deleteClerk.NoInput=A clerk id must be specified -errors.deleteClerk.NotFound=The specified clerk if could not be found. -errors.savetmodel.NoInput=At least one tModel must be provided -errors.addpublisherassertions.NoInput=At least one publisherAssertion must be provided -errors.businessentity.NullInput=The businessEntity structure cannot be blank -errors.entity.SignedButNoKey=The entity has no key defined, which means I'll generate one for you, but the entity is signed and thus will become invalid after I add a generated key. Either specify your own key or omit the signature. -errors.businessservice.NullInput=The businessService structure cannot be blank -errors.bindingtemplate.NullInput=The bindingTemplate structure cannot be blank -errors.bindingtemplate.NoAccessPoint=A binding template must contain either an access point or a hosting redirector element, but not both -errors.tmodel.NullInput=The tModel structure cannot be blank -errors.tmodel.NoName=A tModel must contain a name -errors.tmodel.keygenerator.BadCategory=A Key Generator tModel must have exactly one 'types' category (categoryBag/keyedReference/value) whose value is 'keyGenerator' -errors.tmodel.keygenerator.RootKeyGen=A Key Generator cannot be added for the root publisher. Try signing in as a different user -errors.pubassertion.NullInput=The publisherAssertion structure cannot be blank -errors.pubassertion.BlankKeyedRef=The keyedReference of the publisherAssertion cannot be blank. All fields must contain content. -errors.pubassertion.BlankFromKey=The fromKey of the publisherAssertion cannot be blank. -errors.pubassertion.BlankToKey=The toKey of the publisherAssertion cannot be blank. -errors.pubassertion.SameBusinessKey=The fromKey and toKey refer to the same business -errors.pubassertion.UserMismatch=The publisher does not own either referenced businessEntity of the publisherAssertion -errors.pubassertion.NoPubAssertions=No publisher assertions were passed. At least one assertion must be passed -errors.pubassertion.AssertionNotFound=The publisher assertion was not found for the given key -errors.businessservices.NoInput=A businessServices collection must contain at least one businessService -errors.bindingtemplates.NoInput=A bindingTemplates collection must contain at least one bindingTemplate -errors.names.NoInput=At least one name is required -errors.names.TooLong=At least one name is required -errors.names.NoValue=A name was provided with no value -errors.names.LangTooLong=A name language was provided that is too long, only 26 characters are permitted. -errors.names.UseTypeTooLong=The field 'useType' must be less than 256 characters -errors.DescriptionTooLong=The field 'description' must be less than 256 characters -errors.keys.TooLong=Key lengths are limited to 255 characters or less -errors.url.overviewTooLong=Overview URLs are limited to 4096 characters -errors.accessPoint.TooLong=Access points are limited to 4096 characters -errors.sortCode.TooLong=Sort codes are limited to 10 characters -errors.keyname.TooLong=Key Names are limited to 255 characters -errors.phone.noinput=No input provided for phone value -errors.phone.TooLong=Phone numbers are limited to 50 characters -errors.email.TooLong=Email addresses are limited to 4096 characters -errors.email.noinput=No input provided for email -errors.hostingredirector.noinput=No input provided for hosting redirector -errors.hostingredirector.TooLong=The input provided for hosting redirector is too long, only 255 characters are allowed -errors.addressline.noinput=No input provided for address lines -errors.addressline.TooLong=Address lines are limited to 80 characters -errors.hostingredirector.keynotexist=When specifying a hosting redirector field, the referenced binding template must exist already -errors.keyvalue.TooLong=Key values are limited to 255 characters -errors.tmodel.ReferencedKeyDoesNotExist=The referenced tModel key does not exist. This can be caused when specifying a tModel key that is not defined and when jUDDI's referential integrity validation is enabled. -errors.tmodel.ReferentialIntegrityNullConfig=Configuration object is null, I won't be able to process referential integrity checks on tmodel keys -errors.tmodel.ReferentialIntegrityNullEM=The entity manager is null, I won't be able to process referential integrity checks on tmodel keys - - -errors.contacts.NoInput=At least one contact is required -errors.contact.NullInput=The contact structure cannot be blank -errors.contact.NoPersonName=The contact structure must contain at least one personName -errors.contact.NoAddressLine=Each contact address must contain at least one addressLine -errors.discurls.NoInput=A discoveryURLs collection must have at least one discoveryURL -errors.categorybag.NoInput=A category bag must have at least one keyedReference or keyedReferenceGroup -errors.identifierbag.NoInput=An identifier bag must have at least one keyedReference -errors.keyedreference.NullInput=The keyed reference (or group) cannot be blank -errors.keyedreference.NoTModelKey=The keyed reference (or group) must contain a tModel key -errors.keyedreference.NoKeyValue=The keyed reference (or group) must contain a key value -errors.keyedreference.NodeCategoryTModel=The node categorization tModel is not allowed -errors.tmodelinstdetails.NoInput=A tModelInstanceDetails structure must have at least one tModelInstanceInfo -errors.tmodelinstinfo.NullInput=The tModelInstanceInfo structure cannot be blank -errors.tmodelinstinfo.NoTModelKey=The tModelInstanceInfo structure must contain a tModel key -errors.instdetails.NoOverviewOrParms=The instanceDetails structure must contain either an overviewDoc or instanceParms -errors.instdetails.MaxLength=tModelInstanceInfo value must be no larger than 8192 -errors.overviewdoc.NullInput=The overviewDoc structure cannot be blank -errors.overviewdoc.NoDescOrUrl=The overviewDoc structure must contain either a description or overviewURL -errors.findqualifiers.NoInput=The findQualifier collection must contain at least one findQualifier. Try 'approximateMatch' -errors.findqualifiers.DuplicateValue=A duplicate findQualifier was passed. No duplicates are allowed -errors.findqualifiers.InvalidCombo=An invalid findQualifier combination occurred -errors.findbusiness.NoInput=At least one search criterion must be supplied. Try using '%' as a wild card with the a 'approximateMatch' find qualifer for everything -errors.findservice.NoInput=At least one name, categoryBag, find_tModel or tModelBag or name must be supplied -errors.findbinding.NoInput=At least one categoryBag, find_tModel or tModelBag must be supplied -errors.findtmodel.NoInput=At least one categoryBag, identifierBag or name must be supplied -errors.findrelatedbusiness.NoInput=At least one businessKey, fromKey or toKey must be supplied -errors.findrelatedbusiness.MultipleInput=Only one businessKey, fromKey or toKey can be supplied -errors.findrelatedbusiness.BlankKeyedRef=All fields of the keyedReference provided in find_relatedBusiness must contain values -errors.tmodelbag.NoInput=A tModel key must be supplied in the tModelBag -errors.keybag.NoInput=A key bag must have at least one key -errors.keybag.NullInput=Key bag cannot be null. -errors.discardtransfertoken.NoInput=A discard_transferToken request must contain either a transferToken or keyBag -errors.gettransfertoken.KeyExists=The key already exists in a transfer request -errors.gettransfertoken.InvalidEntity=The key refers to an invalid entity. Only a BusinessEntity or TModel can be transferred -errors.transfertoken.NullInput=A transfer token must be supplied -errors.transferentities.TokenNotFound=The supplied transfer token was not found -errors.transferentities.TokenExpired=The supplied transfer token has expired -errors.transferentities.KeyMismatch=A supplied key does not match a key associated with the transfer request -errors.transferentities.KeySizeMismatch=The quantity of transfered keys must equal the number of keys in the request -errors.savesubscription.NoInput=At least one Subscription must be provided -errors.subscription.NullInput=The subscription structure cannot be blank -errors.subscription.BindingDoesntExist=The requested subscription has a binding key defined, however that binding template does not exist -errors.subscription.NoFilterOnNewSubscription=No subscription filter was provided on this new subscription request -errors.subscription.BlankFilter=A filter structure was provided but no filter criteria was specified -errors.subscription.TooManyFilters=Only one filter is allowed per subscription request -errors.subscription.expired=The expiration timestamp has already passed. -errors.subscription.maxrecordstoosmall=When specifying the maxium record, it must be greater than zero -errors.subscription.notificationintervalnotdefined=A notification interval must be specified and must be greater than 0ms -errors.getsubscriptionresult.SubscriptionExpired=The passed subscription has expired -errors.getsubscriptionresult.NullCoveragePeriod=The coverage period cannot be blank -errors.getsubscriptionresult.InvalidDateInCoveragePeriod=The coverage period must contain valid dates for start and end points -errors.getsubscriptionresult.StartPointAfterEndPoint=The start point in the coverage period cannot be later than the end point -errors.getsubscriptionresult.InvalidChunkToken=You have provided an invalid chunk token -errors.getsubscriptionresult.NonMatchingChunkToken=The provided chunk token does not match the subscription parameters -errors.getsubscriptionresult.ExpiredChunkToken=The provided chunk token has expired -errors.subscriptionnotifier.client=Client did not receive notification data -errors.getregisteredinfo.NoInfoSelection=The infoSelection argument is required -errors.valuesetvalidation.invalidcontent=The content for tModel value is invalid according to the valid value set defined. -errors.valuesetvalidation.invalidurl=The URL for validating a checked tModel value is invalid or empty -errors.valuesetvalidation.noinput=No input was provided -errors.valuesetvalidation.fatal=Unable to process the validation rule for the specified key. This can happen with a misconfiguration or a classpath issue. - -#-- jUDDI-specific API messages -errors.AdminReqd=An account must have administrative privileges to perform this function -errors.savepublisher.NoInput=At least one Publisher must be provided -errors.savepublisher.AdminReqd=An account must have administrative privileges to save publishers -errors.save.maxBusinessesExceeded=The maximum allowed number of businesses are exceed for this publisher -errors.save.maxServicesExceeded=The maximum allowed number of services are exceed for this business -errors.save.maxBindingsExceeded=The maximum allowed number of bindings are exceed for this service -errors.save.maxTModelsExceeded=The maximum allowed number of tmodels are exceed for this publisher -errors.deletepublisher.AdminReqd=An account must have administrative privileges to perform this action -errors.publisher.NullInput=The Publisher structure cannot be blank -errors.publisher.NoAuthorizedName=A valid publisher authorized name was not specified -errors.publisher.NoPublisherName=A valid publisher name was not specified -errors.clerk.NullInput=The Clerk structure cannot be blank -errors.clerk.NullNodeInput=The Node structure on Clerk cannot be blank -errors.clerk.NoName=A valid clerk name was not specified -errors.clerk.NoPublisherName=A valid publisher name was not specified -errors.node.NullInput=The Node structure cannot be blank -errors.node.NoName=A valid node name was not specified -errors.node.NoClientName=A valid client name was not specified -errors.node.NoDescription=A description was not specified -errors.node.NoCT=A custody transfer url was not specified -errors.node.NoPUB=A publish url was not specified -errors.node.NoIN=A inquiry url was not specified -errors.node.NoSUBL=A subscription listener url was not specified -errors.node.NoSUB=A subscription url was not specified -errors.node.NoSec=A security url was not specified -errors.node.NoProxy=A transport proxy class must be specified. If you're not sure, use 'org.apache.juddi.v3.client.transport.JAXWSTransport' -errors.node.illegalProxyTransport=The transport proxy class is invalid. If you're not sure, use 'org.apache.juddi.v3.client.transport.JAXWSTransport' -errors.node.NoRMIData=When using org.apache.juddi.v3.client.transport.RMITransport is no longer supported. - -#-- Authentication error messages -errors.auth.AuthRequired=Authentication is required for this API call -errors.auth.AuthInvalid=Invalid authentication information -errors.auth.AuthTokenExpired=The authentication token is expired -errors.auth.InvalidUserId=An invalid user identification was passed -errors.auth.InvalidCredentials=Invalid credentials were passed -errors.auth.NoPublisher=The user provided does not have a publishing account -errors.auth.cryptor.InvalidKey=Invalid Key Exception in crypting the password -errors.auth.cryptor.Padding=Padding Exception in crypting the password -errors.auth.cryptor.Algorithm=Algorithm Exception in crypting the password -errors.auth.cryptor.AlgorithmParam=Algorithm parameter Exception in crypting the password -errors.auth.cryptor.BlockSize=Block size Exception in crypting the password -errors.auth.cryptor.BadPadding=Bad Padding Exception in crypting the password - -#-- Local transport error messages -errors.local.soapnotfound=A UDDI request was not found in the SOAP message -errors.local.serviceoperation=The UDDI service operation could not be identified -errors.local.generic=A UDDI generic attribute value was not found for the request. UDDI generic attribute must be present -errors.local.serviceoperation.unsupported=The UDDI service operation specified in unknown or unsupported -errors.local.responseobject.unknown=The response object type is unknown -errors.local.registryunavailable=The registry is currently unavailable -errors.local.operation.notidentified=The UDDI service operation could not be identified -errors.local.inquiry.notsupported=The operation is not supported by the UDDI version 3 Inquiry API -errors.local.publish.notsupported=The operation is not supported by the UDDI version 3 Publish API -errors.local.security.notsupported=The operation is not supported by the UDDI version 3 Security API - - -notifications.smtp.default.subject=UDDI Subscription Notification for subscription - -notifications.smtp.userfriendly.subject=UDDI Subscription Notification for subscription -notifications.smtp.userfriendly.body=Hello %s,

You are currently registered to receive subscription updates in the UDDI Node %s for %s. A change was registered that triggered an update notification to be sent. The attachment contains the XML containing the details of the change.

Summary of changes:

%s -notifications.smtp.subscriptionDeleted=Hello %s, %s,

Your UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s.

Non-secure web site
Secure web site -notifications.smtp.accountDeleted=Hello %s, %s,

Your account has been deleted by %s, %s at %s. This node is %s.

Non-secure web site
Secure web site -notifications.smtp.accountDeleted.subject=UDDI Account Management -#username -#node -#search results or a specific item - - - -#replication error messages -errors.replication.nodeNotSpecified=The requestor's node name must be specified -errors.replication.unknownNode=The requestor's node is NOT in the replication configuration graph. Access Denied -errors.replication.bothLimitsSpecified=responseLimitCount or responseLimitVector: A caller MAY place an upper bound on the number of change records he wishes to receive in response to this message by either providing a integer responseLimitCount, or, using responseLimitVector, indicating for each node in the graph the first change originating there that he does not wish to be returned. -errors.replication.negativeLimit=The specified response limit is either 0 or a negative number. -errors.replication.limitVectorNull=The high water mark vector limit specified OriginatingUSN is null or invalid -errors.replication.limitVectorNoNode=No node name was specified -errors.replication.configNodeNotFound=No specified node name is not currently listed as a Operator. Add it to the list and try again. Id: -errors.replication.configNull=No replication config was present in the message -errors.replication.contactNull=No replication contact was present in the message -errors.replication.configNodeLoop=In at least one edge, there is a loop where the sender is also the receiver. This is not allowed and just does not make sense -errors.deleteNode.InReplicationConfig=The node to be deleted is currently referenced in the replication configuration. You must revise the configuration before deleting the node, -errors.usermismatch.InvalidNode=The user is not authorized to alter the given entity. It is not owned by this jUDDI node. Try your request again on the authoritative node. - -errors.usermismatch.assertion=You have to be either the owner of the 'from' or 'to' business in order to delete a publisher assertion. -errors.assertionNotFound=The referenced publisher assertion isn't in the database! +#/* +# * Copyright 2001-2008 The Apache Software Foundation. +# * +# * 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. +# * +# */ + +# Global base messages file. + +#-- UDDI-specific messages +E_accountLimitExceeded=Save request exceeds the quantity limits for a given data type. +E_assertionNotFound=Publisher assertion cannot be identified in a save or delete operation. +E_authTokenExpired=Authentication token information has timed out. +E_authTokenRequired=Authentication token is missing or is invalid. +E_busy=The request cannot be processed at the current time. +E_categorizationNotAllowed= +E_fatalError=A serious technical error has occurred while processing the request. +E_historyDataNotAvailable=Requested history data is not available for the time period requested. +E_invalidCategory= +E_invalidCompletionStatus=Assertion status value passed is unrecognized. +E_invalidCombination=Invalid find qualifier combination +E_invalidKeyPassed=An invalid key has been passed +E_invalidProjection=An attempt was made to save a businessEntity containing a service projection where the serviceKey does not belong to the business designated by the businessKey. +E_invalidTime=The time period, the date/time, or the pair of date/time is invalid. +E_invalidURLPassed= +E_invalidValue=A value that was passed in a keyValue attribute did not pass validation. +E_invalidValueAddressLine=Each addressLine element MAY be adorned with two optional descriptive attributes, keyName and keyValue. Both attributes MUST be present in each address line if a tModelKey is specified in the address structure. Elements with errors: +E_keyRetired=The specified key was retired + +E_keyUnavailable=The proposed key is in a partition that has already been assigned to some other publisher. +E_languageError=Language error +E_messageTooLarge=The message is too large. +E_nameTooLong=The name is too large +E_operatorMismatch=Operator Mismatch +E_publisherCancelled= +E_requestDenied=Subscription cannot be renewed. +E_requestTimeout=The request could not be carried out because a needed Web service did not respond in a reasonable amount of time. +E_resultSetTooLarge=The UDDI node deems that a result set from an inquiry is too large, and requests to obtain the results are not honored, even using subsets. +E_secretUnknown= +E_success= +E_tokenAlreadyExists=Key already exists in transfer request +E_tooManyOptions=Too many options +E_transferAborted=Transfer Aborted +E_transferNotAllowed=The transfer request is not allowed +E_transferNotAllowedUnknownNode=The transfer request is not allowed because the destination node is not in the replication config. +E_transferBlocked=The transfer was blocked from it's originator (node to node transfer). +E_unknownUser=The user ID and password pair passed in a get_authToken API is not known to the UDDI node or is not valid. +E_unrecognizedVersion=The value of the namespace attribute is unsupported by the node being queried. +E_unsupported=Unsupported feature or API. +E_unvalidatable=An attempt was made to reference a value set in a keyedReference whose tModel is categorized with the unvalidatable categorization. +E_userMismatch=An attempt was made to use the publishing API to change data that is controlled by another party. +E_valueNotAllowed=A value did not pass validation because of contextual issues. + + +#-- General error messages +errors.stringEncoding=non-UTF8 token +errors.DatatypeFactor=Can't create a DatatypeFactory instance. +errors.Unspecified=An unspecified error occurred +errors.Unsupported=This version does not support this feature or API +errros.UnsupportedAuthenticator=This selected authenticator does not support AuthTokens. +errors.Unsupported.findQualifier=An invalid or unsupported findQualifier value was passed +errors.configuration.Retrieval=An error occurred attempting to retrieve configuration information +errors.install.AlreadyInstalled=It appears that the application is already installed. Please un-install before proceeding. +errors.NullInput=No input was provided for this API call +errors.keyunavailable.BadPartition=The proposed key is not within the partition defined by owning publisher. If you're trying to create a new tModel in a new partition, try creating a tModel that ends in :keygenerator. Failing key +errors.keyunavailable.KeyExists=The key used for the save operation already exists. Another key must be chosen +errors.invalidkey.NullKey=The key cannot be null +errors.invalidkey.MalformedKey=The passed key does not conform to UDDI v3 rules +errors.invalidkey.KeyGenSuffix=The passed key generator key does not end with the appropriate suffix +errors.invalidkey.NoKeys=No keys passed. At least one key must be passed +errors.invalidkey.ClerkNotFound=The clerk was not found for the given name +errors.invalidkey.DuplicateKey=A duplicate key was passed. No duplicates are allowed +errors.invalidkey.PublisherNotFound=The publisher was not found for the given id +errors.invalidkey.EntityNotFound=The entity was not found for the given id +errors.invalidkey.BusinessNotFound=The business entity was not found for the given key +errors.invalidkey.ServiceNotFound=The business service was not found for the given key +errors.invalidkey.BindingTemplateNotFound=The binding template was not found for the given key +errors.invalidkey.TModelNotFound=The technical model was not found for the given key +errors.invalidkey.TModelNodeOwner=You've attempted to delete a tModel that is not owned by this node. Access the owning node to delete. +errors.invalidkey.ParentServiceNotFound=The business service parent was not found for the given key +errors.invalidkey.ParentBusinessNotFound=The business entity parent was not found for the given key +errors.invalidkey.ServiceKeyNotProvidedWithProjection=Attempting to project a service when the service key was not provided. The non-owning businessEntity cannot generate a key for a projected service +errors.invalidkey.ProjectedServiceNotFound=Attempting to project a service when the service does not exist +errors.invalidkey.businessservice.ParentMismatch=The service being saved has a different parent business key then the one provided +errors.invalidkey.bindingtemplate.ParentMismatch=The binding template being saved has a different parent service key then the one provided +errors.invalidkey.SubscriptionNotFound=The subscription was not found for the given key +errors.invalidKey.KeysOwned=Either the to key for the from key must be specified on a keysOwned structure +errors.invalidkey.SubscripKeyNotFound=The subscriptionKey was not found for the given id +errors.invalidkey.NodeNotFound=The node was not found for the key given name +errors.invalidprojection.ParentMismatch=The supplied business key doesn't match the actual business key of the service being projected +errors.usermismatch.InvalidOwner=The user is not authorized to access the given entity +errors.usermismatch.InvalidOwnerParent=The user is not authorized to access the given parent entity +errors.config.InvalidTokenExpirationSetting=The authentication token expiration setting is missing or invalid, will default to 15 minutes. See juddiv3.properties file +errors.accessPoint.bindingtemplateRedirect.keynotexist=The access point contains a useType specifying a referenced binding template which does not exist. +errors.accessPoint.hostingRedirector.notaurl=The access point value is not a valid URL. This URL should be a URL to another UDDI registry +#-- Error messages related to entities and other data structures +errors.savebusiness.NoInput=At least one BusinessEntity must be provided +errors.saveservice.NoInput=At least one BusinessService must be provided +errors.savebinding.NoInput=At least one BindingTemplate must be provided +errors.saveclientsubscriptionKey.NoInput=The SubscriptionKey must be provided +errors.saveClerk.NoInput=At least one Clerk must be provided +errors.saveNodes.NoInput=At least one Node must be provided +errors.deleteNode.NoInput=A node id must be specified +errors.deleteNode.NotFound=The specified node could not be found. +errors.deleteClerk.NoInput=A clerk id must be specified +errors.deleteClerk.NotFound=The specified clerk if could not be found. +errors.savetmodel.NoInput=At least one tModel must be provided +errors.addpublisherassertions.NoInput=At least one publisherAssertion must be provided +errors.businessentity.NullInput=The businessEntity structure cannot be blank +errors.entity.SignedButNoKey=The entity has no key defined, which means I'll generate one for you, but the entity is signed and thus will become invalid after I add a generated key. Either specify your own key or omit the signature. +errors.businessservice.NullInput=The businessService structure cannot be blank +errors.bindingtemplate.NullInput=The bindingTemplate structure cannot be blank +errors.bindingtemplate.NoAccessPoint=A binding template must contain either an access point or a hosting redirector element, but not both +errors.tmodel.NullInput=The tModel structure cannot be blank +errors.tmodel.NoName=A tModel must contain a name +errors.tmodel.keygenerator.BadCategory=A Key Generator tModel must have exactly one 'types' category (categoryBag/keyedReference/value) whose value is 'keyGenerator' +errors.tmodel.keygenerator.RootKeyGen=A Key Generator cannot be added for the root publisher. Try signing in as a different user +errors.pubassertion.NullInput=The publisherAssertion structure cannot be blank +errors.pubassertion.BlankKeyedRef=The keyedReference of the publisherAssertion cannot be blank. All fields must contain content. +errors.pubassertion.BlankFromKey=The fromKey of the publisherAssertion cannot be blank. +errors.pubassertion.BlankToKey=The toKey of the publisherAssertion cannot be blank. +errors.pubassertion.SameBusinessKey=The fromKey and toKey refer to the same business +errors.pubassertion.UserMismatch=The publisher does not own either referenced businessEntity of the publisherAssertion +errors.pubassertion.NoPubAssertions=No publisher assertions were passed. At least one assertion must be passed +errors.pubassertion.AssertionNotFound=The publisher assertion was not found for the given key +errors.businessservices.NoInput=A businessServices collection must contain at least one businessService +errors.bindingtemplates.NoInput=A bindingTemplates collection must contain at least one bindingTemplate +errors.names.NoInput=At least one name is required +errors.names.TooLong=At least one name is required +errors.names.NoValue=A name was provided with no value +errors.names.LangTooLong=A name language was provided that is too long, only 26 characters are permitted. +errors.names.UseTypeTooLong=The field 'useType' must be less than 256 characters +errors.DescriptionTooLong=The field 'description' must be less than 256 characters +errors.keys.TooLong=Key lengths are limited to 255 characters or less +errors.url.overviewTooLong=Overview URLs are limited to 4096 characters +errors.accessPoint.TooLong=Access points are limited to 4096 characters +errors.sortCode.TooLong=Sort codes are limited to 10 characters +errors.keyname.TooLong=Key Names are limited to 255 characters +errors.phone.noinput=No input provided for phone value +errors.phone.TooLong=Phone numbers are limited to 50 characters +errors.email.TooLong=Email addresses are limited to 4096 characters +errors.email.noinput=No input provided for email +errors.hostingredirector.noinput=No input provided for hosting redirector +errors.hostingredirector.TooLong=The input provided for hosting redirector is too long, only 255 characters are allowed +errors.addressline.noinput=No input provided for address lines +errors.addressline.TooLong=Address lines are limited to 80 characters +errors.hostingredirector.keynotexist=When specifying a hosting redirector field, the referenced binding template must exist already +errors.keyvalue.TooLong=Key values are limited to 255 characters +errors.tmodel.ReferencedKeyDoesNotExist=The referenced tModel key does not exist. This can be caused when specifying a tModel key that is not defined and when jUDDI's referential integrity validation is enabled. +errors.tmodel.ReferentialIntegrityNullConfig=Configuration object is null, I won't be able to process referential integrity checks on tmodel keys +errors.tmodel.ReferentialIntegrityNullEM=The entity manager is null, I won't be able to process referential integrity checks on tmodel keys + + +errors.contacts.NoInput=At least one contact is required +errors.contact.NullInput=The contact structure cannot be blank +errors.contact.NoPersonName=The contact structure must contain at least one personName +errors.contact.NoAddressLine=Each contact address must contain at least one addressLine +errors.discurls.NoInput=A discoveryURLs collection must have at least one discoveryURL +errors.categorybag.NoInput=A category bag must have at least one keyedReference or keyedReferenceGroup +errors.identifierbag.NoInput=An identifier bag must have at least one keyedReference +errors.keyedreference.NullInput=The keyed reference (or group) cannot be blank +errors.keyedreference.NoTModelKey=The keyed reference (or group) must contain a tModel key +errors.keyedreference.NoKeyValue=The keyed reference (or group) must contain a key value +errors.keyedreference.NodeCategoryTModel=The node categorization tModel is not allowed +errors.tmodelinstdetails.NoInput=A tModelInstanceDetails structure must have at least one tModelInstanceInfo +errors.tmodelinstinfo.NullInput=The tModelInstanceInfo structure cannot be blank +errors.tmodelinstinfo.NoTModelKey=The tModelInstanceInfo structure must contain a tModel key +errors.instdetails.NoOverviewOrParms=The instanceDetails structure must contain either an overviewDoc or instanceParms +errors.instdetails.MaxLength=tModelInstanceInfo value must be no larger than 8192 +errors.overviewdoc.NullInput=The overviewDoc structure cannot be blank +errors.overviewdoc.NoDescOrUrl=The overviewDoc structure must contain either a description or overviewURL +errors.findqualifiers.NoInput=The findQualifier collection must contain at least one findQualifier. Try 'approximateMatch' +errors.findqualifiers.DuplicateValue=A duplicate findQualifier was passed. No duplicates are allowed +errors.findqualifiers.InvalidCombo=An invalid findQualifier combination occurred +errors.findbusiness.NoInput=At least one search criterion must be supplied. Try using '%' as a wild card with the a 'approximateMatch' find qualifer for everything +errors.findservice.NoInput=At least one name, categoryBag, find_tModel or tModelBag or name must be supplied +errors.findbinding.NoInput=At least one categoryBag, find_tModel or tModelBag must be supplied +errors.findtmodel.NoInput=At least one categoryBag, identifierBag or name must be supplied +errors.findrelatedbusiness.NoInput=At least one businessKey, fromKey or toKey must be supplied +errors.findrelatedbusiness.MultipleInput=Only one businessKey, fromKey or toKey can be supplied +errors.findrelatedbusiness.BlankKeyedRef=All fields of the keyedReference provided in find_relatedBusiness must contain values +errors.tmodelbag.NoInput=A tModel key must be supplied in the tModelBag +errors.keybag.NoInput=A key bag must have at least one key +errors.keybag.NullInput=Key bag cannot be null. +errors.discardtransfertoken.NoInput=A discard_transferToken request must contain either a transferToken or keyBag +errors.gettransfertoken.KeyExists=The key already exists in a transfer request +errors.gettransfertoken.InvalidEntity=The key refers to an invalid entity. Only a BusinessEntity or TModel can be transferred +errors.transfertoken.NullInput=A transfer token must be supplied +errors.transferentities.TokenNotFound=The supplied transfer token was not found +errors.transferentities.TokenExpired=The supplied transfer token has expired +errors.transferentities.KeyMismatch=A supplied key does not match a key associated with the transfer request +errors.transferentities.KeySizeMismatch=The quantity of transfered keys must equal the number of keys in the request +errors.savesubscription.NoInput=At least one Subscription must be provided +errors.subscription.NullInput=The subscription structure cannot be blank +errors.subscription.BindingDoesntExist=The requested subscription has a binding key defined, however that binding template does not exist +errors.subscription.NoFilterOnNewSubscription=No subscription filter was provided on this new subscription request +errors.subscription.BlankFilter=A filter structure was provided but no filter criteria was specified +errors.subscription.TooManyFilters=Only one filter is allowed per subscription request +errors.subscription.expired=The expiration timestamp has already passed. +errors.subscription.maxrecordstoosmall=When specifying the maxium record, it must be greater than zero +errors.subscription.notificationintervalnotdefined=A notification interval must be specified and must be greater than 0ms +errors.getsubscriptionresult.SubscriptionExpired=The passed subscription has expired +errors.getsubscriptionresult.NullCoveragePeriod=The coverage period cannot be blank +errors.getsubscriptionresult.InvalidDateInCoveragePeriod=The coverage period must contain valid dates for start and end points +errors.getsubscriptionresult.StartPointAfterEndPoint=The start point in the coverage period cannot be later than the end point +errors.getsubscriptionresult.InvalidChunkToken=You have provided an invalid chunk token +errors.getsubscriptionresult.NonMatchingChunkToken=The provided chunk token does not match the subscription parameters +errors.getsubscriptionresult.ExpiredChunkToken=The provided chunk token has expired +errors.subscriptionnotifier.client=Client did not receive notification data +errors.getregisteredinfo.NoInfoSelection=The infoSelection argument is required +errors.valuesetvalidation.invalidcontent=The content for tModel value is invalid according to the valid value set defined. +errors.valuesetvalidation.invalidurl=The URL for validating a checked tModel value is invalid or empty +errors.valuesetvalidation.noinput=No input was provided +errors.valuesetvalidation.fatal=Unable to process the validation rule for the specified key. This can happen with a misconfiguration or a classpath issue. + +#-- jUDDI-specific API messages +errors.AdminReqd=An account must have administrative privileges to perform this function +errors.savepublisher.NoInput=At least one Publisher must be provided +errors.savepublisher.AdminReqd=An account must have administrative privileges to save publishers +errors.save.maxBusinessesExceeded=The maximum allowed number of businesses are exceed for this publisher +errors.save.maxServicesExceeded=The maximum allowed number of services are exceed for this business +errors.save.maxBindingsExceeded=The maximum allowed number of bindings are exceed for this service +errors.save.maxTModelsExceeded=The maximum allowed number of tmodels are exceed for this publisher +errors.deletepublisher.AdminReqd=An account must have administrative privileges to perform this action +errors.publisher.NullInput=The Publisher structure cannot be blank +errors.publisher.NoAuthorizedName=A valid publisher authorized name was not specified +errors.publisher.NoPublisherName=A valid publisher name was not specified +errors.clerk.NullInput=The Clerk structure cannot be blank +errors.clerk.NullNodeInput=The Node structure on Clerk cannot be blank +errors.clerk.NoName=A valid clerk name was not specified +errors.clerk.NoPublisherName=A valid publisher name was not specified +errors.node.NullInput=The Node structure cannot be blank +errors.node.NoName=A valid node name was not specified +errors.node.NoClientName=A valid client name was not specified +errors.node.NoDescription=A description was not specified +errors.node.NoCT=A custody transfer url was not specified +errors.node.NoPUB=A publish url was not specified +errors.node.NoIN=A inquiry url was not specified +errors.node.NoSUBL=A subscription listener url was not specified +errors.node.NoSUB=A subscription url was not specified +errors.node.NoSec=A security url was not specified +errors.node.NoProxy=A transport proxy class must be specified. If you're not sure, use 'org.apache.juddi.v3.client.transport.JAXWSTransport' +errors.node.illegalProxyTransport=The transport proxy class is invalid. If you're not sure, use 'org.apache.juddi.v3.client.transport.JAXWSTransport' +errors.node.NoRMIData=When using org.apache.juddi.v3.client.transport.RMITransport is no longer supported. + +#-- Authentication error messages +errors.auth.AuthRequired=Authentication is required for this API call +errors.auth.AuthInvalid=Invalid authentication information +errors.auth.AuthTokenExpired=The authentication token is expired +errors.auth.InvalidUserId=An invalid user identification was passed +errors.auth.InvalidCredentials=Invalid credentials were passed +errors.auth.NoPublisher=The user provided does not have a publishing account +errors.auth.cryptor.InvalidKey=Invalid Key Exception in crypting the password +errors.auth.cryptor.Padding=Padding Exception in crypting the password +errors.auth.cryptor.Algorithm=Algorithm Exception in crypting the password +errors.auth.cryptor.AlgorithmParam=Algorithm parameter Exception in crypting the password +errors.auth.cryptor.BlockSize=Block size Exception in crypting the password +errors.auth.cryptor.BadPadding=Bad Padding Exception in crypting the password + +#-- Local transport error messages +errors.local.soapnotfound=A UDDI request was not found in the SOAP message +errors.local.serviceoperation=The UDDI service operation could not be identified +errors.local.generic=A UDDI generic attribute value was not found for the request. UDDI generic attribute must be present +errors.local.serviceoperation.unsupported=The UDDI service operation specified in unknown or unsupported +errors.local.responseobject.unknown=The response object type is unknown +errors.local.registryunavailable=The registry is currently unavailable +errors.local.operation.notidentified=The UDDI service operation could not be identified +errors.local.inquiry.notsupported=The operation is not supported by the UDDI version 3 Inquiry API +errors.local.publish.notsupported=The operation is not supported by the UDDI version 3 Publish API +errors.local.security.notsupported=The operation is not supported by the UDDI version 3 Security API + + +notifications.smtp.default.subject=UDDI Subscription Notification for subscription + +notifications.smtp.userfriendly.subject=UDDI Subscription Notification for subscription +notifications.smtp.userfriendly.body=Hello %s,

You are currently registered to receive subscription updates in the UDDI Node %s for %s. A change was registered that triggered an update notification to be sent. The attachment contains the XML containing the details of the change.

Summary of changes:

%s +notifications.smtp.subscriptionDeleted=Hello %s, %s,

Your UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s.

Non-secure web site
Secure web site +notifications.smtp.accountDeleted=Hello %s, %s,

Your account has been deleted by %s, %s at %s. This node is %s.

Non-secure web site
Secure web site +notifications.smtp.accountDeleted.subject=UDDI Account Management +#username +#node +#search results or a specific item + + + +#replication error messages +errors.replication.nodeNotSpecified=The requestor's node name must be specified +errors.replication.unknownNode=The requestor's node is NOT in the replication configuration graph. Access Denied +errors.replication.bothLimitsSpecified=responseLimitCount or responseLimitVector: A caller MAY place an upper bound on the number of change records he wishes to receive in response to this message by either providing a integer responseLimitCount, or, using responseLimitVector, indicating for each node in the graph the first change originating there that he does not wish to be returned. +errors.replication.negativeLimit=The specified response limit is either 0 or a negative number. +errors.replication.limitVectorNull=The high water mark vector limit specified OriginatingUSN is null or invalid +errors.replication.limitVectorNoNode=No node name was specified +errors.replication.configNodeNotFound=No specified node name is not currently listed as a Operator. Add it to the list and try again. Id: +errors.replication.configNull=No replication config was present in the message +errors.replication.contactNull=No replication contact was present in the message +errors.replication.configNodeLoop=In at least one edge, there is a loop where the sender is also the receiver. This is not allowed and just does not make sense +errors.deleteNode.InReplicationConfig=The node to be deleted is currently referenced in the replication configuration. You must revise the configuration before deleting the node, +errors.usermismatch.InvalidNode=The user is not authorized to alter the given entity. It is not owned by this jUDDI node. Try your request again on the authoritative node. + +errors.usermismatch.assertion=You have to be either the owner of the 'from' or 'to' business in order to delete a publisher assertion. +errors.assertionNotFound=The referenced publisher assertion isn't in the database! errors.digitalsignature.validationfailure=The digital signature the following element failed to validate. Because of this, the request was rejected. Key and validation error as follows. \ No newline at end of file diff --git a/juddi-core-openjpa/src/test/.gitignore b/juddi-core-openjpa/src/test/.gitignore deleted file mode 100644 index 34dbc4597..000000000 --- a/juddi-core-openjpa/src/test/.gitignore +++ /dev/null @@ -1 +0,0 @@ -java/ diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_010_PublisherTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_010_PublisherTest.java similarity index 97% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/API_010_PublisherTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_010_PublisherTest.java index 74b4db198..f2d16e318 100644 --- a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_010_PublisherTest.java +++ b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_010_PublisherTest.java @@ -1,345 +1,345 @@ -/* - * Copyright 2001-2009 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import static junit.framework.Assert.assertEquals; - -import java.rmi.RemoteException; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.List; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.ws.Holder; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.Registry; -import org.apache.juddi.api_v3.DeletePublisher; -import org.apache.juddi.api_v3.GetPublisherDetail; -import org.apache.juddi.api_v3.Publisher; -import org.apache.juddi.api_v3.PublisherDetail; -import org.apache.juddi.api_v3.SavePublisher; -import org.apache.juddi.config.AppConfig; -import org.apache.juddi.config.Property; -import org.apache.juddi.jaxb.EntityCreator; -import org.apache.juddi.v3.client.UDDIConstants; -import org.apache.juddi.v3.error.InvalidKeyPassedException; -import org.apache.juddi.v3.error.UserMismatchException; -import org.apache.juddi.v3.tck.TckPublisher; -import org.apache.juddi.v3.tck.TckSecurity; -import org.apache.juddi.v3.tck.TckSubscription; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.uddi.api_v3.FindBusiness; -import org.uddi.api_v3.FindQualifiers; -import org.uddi.api_v3.Name; -import org.uddi.api_v3.TModel; -import org.uddi.sub_v3.Subscription; -import org.uddi.sub_v3.SubscriptionFilter; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.v3_service.UDDISecurityPortType; - -/** - * This test is jUDDI specific, as the publisher methods are an extension to the - * UDDI api. - * - * @author Jeff Faath - * @author Kurt T Stam - * @author Alex O'Ree - */ -public class API_010_PublisherTest { - - private static Log logger = LogFactory.getLog(API_010_PublisherTest.class); - private JUDDIApiImpl publisher = new JUDDIApiImpl(); - private UDDISecurityPortType security = new UDDISecurityImpl(); - private static TckSubscription tckSubscription = new TckSubscription(new UDDISubscriptionImpl(), new UDDISecurityImpl(), new UDDIInquiryImpl()); - - @BeforeClass - public static void startRegistry() throws ConfigurationException { - Registry.start(); - } - - @AfterClass - public static void stopRegistry() throws ConfigurationException { - Registry.stop(); - } - - @Test - public void testJoePublisher() { - //We can only test this if the publisher is not there already. - //If it already there is probably has foreign key relationships. - //This test should really only run on an empty database. Seed - //data will be added if the root publisher is missing. - if (!isExistPublisher(TckPublisher.getJoePublisherId())) { - saveJoePublisher(); - deleteJoePublisher(); - } - } - - @Test - public void testSamSyndicator() { - //We can only test this if the publisher is not there already. - if (!isExistPublisher(TckPublisher.getSamPublisherId())) { - saveSamSyndicator(); - deleteSamSyndicator(); - } - } - - /** - * Persists Joe Publisher to the database. - * - * @return - true if the published did not exist already, - false in all - * other cases. - */ - public boolean saveJoePublisher() { - if (!isExistPublisher(TckPublisher.getJoePublisherId())) { - savePublisher(TckPublisher.getJoePublisherId(), TckPublisher.JOE_PUBLISHER_XML); - return true; - } else { - return false; - } - } - - /** - * Persists Mary Publisher to the database. - * - * @return - true if the published did not exist already, - false in all - * other cases. - */ - public boolean saveMaryPublisher() { - if (!isExistPublisher(TckPublisher.getMaryPublisherId())) { - savePublisher(TckPublisher.getMaryPublisherId(), TckPublisher.MARY_PUBLISHER_XML); - return true; - } else { - return false; - } - } - - /** - * Removes Joe Publisher from the database, this will fail if there are - * child objects attached; think Services etc. - */ - public void deleteJoePublisher() { - deletePublisher(TckPublisher.getJoePublisherId()); - } - - /** - * Persists Sam Syndicator to the database. - * - * @return publisherId - */ - public String saveSamSyndicator() { - if (!isExistPublisher(TckPublisher.getSamPublisherId())) { - savePublisher(TckPublisher.getSamPublisherId(), TckPublisher.SAM_SYNDICATOR_XML); - } - return TckPublisher.getSamPublisherId(); - } - - /** - * Removes Sam Syndicator from the database, this will fail if there are - * child objects attached; think Services etc. - */ - public void deleteSamSyndicator() { - deletePublisher(TckPublisher.getSamPublisherId()); - } - - private void savePublisher(String publisherId, String publisherXML) { - try { - String rootPublisherStr = AppConfig.getConfiguration().getString(Property.JUDDI_ROOT_PUBLISHER); - logger.info("savePublisher as " + rootPublisherStr); - String authInfo = TckSecurity.getAuthToken(security, rootPublisherStr, ""); - logger.debug("Saving new publisher: " + publisherXML); - SavePublisher sp = new SavePublisher(); - sp.setAuthInfo(authInfo); - Publisher pubIn = (Publisher) EntityCreator.buildFromDoc(publisherXML, EntityCreator.JUDDIv3_Package); - sp.getPublisher().add(pubIn); - publisher.savePublisher(sp); - - // Now get the entity and check the values - GetPublisherDetail gp = new GetPublisherDetail(); - gp.getPublisherId().add(publisherId); - gp.setAuthInfo(authInfo); - PublisherDetail pd = publisher.getPublisherDetail(gp); - List pubOutList = pd.getPublisher(); - Publisher pubOut = pubOutList.get(0); - - assertEquals(pubIn.getAuthorizedName(), pubOut.getAuthorizedName()); - assertEquals(pubIn.getPublisherName(), pubOut.getPublisherName()); - assertEquals(pubIn.getEmailAddress(), pubOut.getEmailAddress()); - assertEquals(pubIn.isIsAdmin(), pubOut.isIsAdmin()); - assertEquals(pubIn.isIsEnabled(), pubOut.isIsEnabled()); - assertEquals(pubIn.getMaxBindingsPerService(), pubOut.getMaxBindingsPerService()); - assertEquals(pubIn.getMaxBusinesses(), pubOut.getMaxBusinesses()); - assertEquals(pubIn.getMaxServicePerBusiness(), pubOut.getMaxServicePerBusiness()); - assertEquals(pubIn.getMaxTModels(), pubOut.getMaxTModels()); - - logger.debug("Querying for publisher: " + publisherXML); - //Querying for this publisher to make sure it's really gone - //We're expecting a invalid Key exception at this point. - PublisherDetail pdBeforeDelete = null; - try { - pdBeforeDelete = publisher.getPublisherDetail(gp); - Assert.assertNotNull(pdBeforeDelete); - } catch (InvalidKeyPassedException e) { - Assert.fail("We expected to find publisher " + publisherXML); - } - - } catch (Exception e) { - logger.error(e.getMessage(), e); - Assert.fail("No exception should be thrown"); - } - } - - private void deletePublisher(String publisherId) { - try { - String rootPublisherStr = AppConfig.getConfiguration().getString(Property.JUDDI_ROOT_PUBLISHER); - String authInfo = TckSecurity.getAuthToken(security, rootPublisherStr, ""); - logger.debug("Delete publisher: " + publisherId); - //Now deleting this publisher - DeletePublisher dp = new DeletePublisher(); - dp.setAuthInfo(authInfo); - dp.getPublisherId().add(publisherId); - publisher.deletePublisher(dp); - - logger.info("Querying for publisher: " + publisherId + " after deletion."); - //Querying for this publisher to make sure it's really gone - //We're expecting a invalid Key exception at this point. - GetPublisherDetail gp = new GetPublisherDetail(); - gp.getPublisherId().add(publisherId); - gp.setAuthInfo(authInfo); - PublisherDetail pdAfterDelete = null; - try { - pdAfterDelete = publisher.getPublisherDetail(gp); - Assert.fail("We did not expect to find this publisher anymore."); - } catch (InvalidKeyPassedException e) { - Assert.assertNull(pdAfterDelete); - } - - } catch (Exception e) { - logger.error(e.getMessage(), e); - Assert.fail("No exception should be thrown"); - } - } - - private boolean isExistPublisher(String publisherId) { - GetPublisherDetail gp = new GetPublisherDetail(); - gp.getPublisherId().add(publisherId); - try { - publisher.getPublisherDetail(gp); - return true; - } catch (Exception e) { - return false; - } - } - - protected String authInfoJoe() throws RemoteException, DispositionReportFaultMessage { - return TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); - } - - protected String authInfoSam() throws RemoteException, DispositionReportFaultMessage { - return TckSecurity.getAuthToken(security, TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword()); - } - - /** - * Joe saves a subscription on Sam's behalf - * - * @throws Exception - */ - @Test - public void testAdminSaveSubscriptionAuthorized() throws Exception { - saveJoePublisher(); - saveSamSyndicator(); - DatatypeFactory fac = DatatypeFactory.newInstance(); - List subs = new ArrayList(); - Subscription s = new Subscription(); - - s.setMaxEntities(10); - s.setBrief(false); - GregorianCalendar gcal = new GregorianCalendar(); - gcal.setTimeInMillis(System.currentTimeMillis()); - gcal.add(Calendar.HOUR, 1); - s.setExpiresAfter(fac.newXMLGregorianCalendar(gcal)); - s.setSubscriptionFilter(new SubscriptionFilter()); - s.getSubscriptionFilter().setFindBusiness(new FindBusiness()); - s.getSubscriptionFilter().getFindBusiness().setFindQualifiers(new FindQualifiers()); - s.getSubscriptionFilter().getFindBusiness().getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); - s.getSubscriptionFilter().getFindBusiness().getName().add(new Name(UDDIConstants.WILDCARD, null)); - subs.add(s); - Holder> items = new Holder>(); - items.value = subs; - publisher.adminSaveSubscription(authInfoJoe(), TckPublisher.getSamPublisherId(), items); - for (int i = 0; i < items.value.size(); i++) { - tckSubscription.deleteSubscription(authInfoSam(), items.value.get(i).getSubscriptionKey()); - } - - deleteJoePublisher(); - deleteSamSyndicator(); - - } - - /** - * Sam saves a subscription on Sam's behalf (not authorized - * - * @throws Exception - */ - @Test(expected = UserMismatchException.class) - public void testAdminSaveSubscriptionNotAuthorized() throws Exception { - saveJoePublisher(); - saveSamSyndicator(); - DatatypeFactory fac = DatatypeFactory.newInstance(); - List subs = new ArrayList(); - Subscription s = new Subscription(); - - s.setMaxEntities(10); - s.setBrief(false); - GregorianCalendar gcal = new GregorianCalendar(); - gcal.setTimeInMillis(System.currentTimeMillis()); - gcal.add(Calendar.HOUR, 1); - s.setExpiresAfter(fac.newXMLGregorianCalendar(gcal)); - s.setSubscriptionFilter(new SubscriptionFilter()); - s.getSubscriptionFilter().setFindBusiness(new FindBusiness()); - s.getSubscriptionFilter().getFindBusiness().setFindQualifiers(new FindQualifiers()); - s.getSubscriptionFilter().getFindBusiness().getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); - s.getSubscriptionFilter().getFindBusiness().getName().add(new Name(UDDIConstants.WILDCARD, null)); - subs.add(s); - Holder> items = new Holder>(); - items.value = subs; - publisher.adminSaveSubscription(authInfoSam(), TckPublisher.getJoePublisherId(), items); - deleteJoePublisher(); - deleteSamSyndicator(); - - } - - @Test - public void testAdminSaveTModel() throws Exception { - saveJoePublisher(); - saveSamSyndicator(); - List values = new ArrayList(); - org.apache.juddi.api_v3.AdminSaveTModelWrapper x = new org.apache.juddi.api_v3.AdminSaveTModelWrapper(); - x.setPublisherID(TckPublisher.getSamPublisherId()); - TModel tm = new TModel(); - tm.setName(new Name("testAdminSaveTModel joe on sam's behalf", null)); - - x.getTModel().add(tm); - publisher.adminSaveTModel(authInfoJoe(), values); - deleteJoePublisher(); - deleteSamSyndicator(); - } - -} +/* + * Copyright 2001-2009 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import static junit.framework.Assert.assertEquals; + +import java.rmi.RemoteException; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.List; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.ws.Holder; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.Registry; +import org.apache.juddi.api_v3.DeletePublisher; +import org.apache.juddi.api_v3.GetPublisherDetail; +import org.apache.juddi.api_v3.Publisher; +import org.apache.juddi.api_v3.PublisherDetail; +import org.apache.juddi.api_v3.SavePublisher; +import org.apache.juddi.config.AppConfig; +import org.apache.juddi.config.Property; +import org.apache.juddi.jaxb.EntityCreator; +import org.apache.juddi.v3.client.UDDIConstants; +import org.apache.juddi.v3.error.InvalidKeyPassedException; +import org.apache.juddi.v3.error.UserMismatchException; +import org.apache.juddi.v3.tck.TckPublisher; +import org.apache.juddi.v3.tck.TckSecurity; +import org.apache.juddi.v3.tck.TckSubscription; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.uddi.api_v3.FindBusiness; +import org.uddi.api_v3.FindQualifiers; +import org.uddi.api_v3.Name; +import org.uddi.api_v3.TModel; +import org.uddi.sub_v3.Subscription; +import org.uddi.sub_v3.SubscriptionFilter; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.v3_service.UDDISecurityPortType; + +/** + * This test is jUDDI specific, as the publisher methods are an extension to the + * UDDI api. + * + * @author Jeff Faath + * @author Kurt T Stam + * @author Alex O'Ree + */ +public class API_010_PublisherTest { + + private static Log logger = LogFactory.getLog(API_010_PublisherTest.class); + private JUDDIApiImpl publisher = new JUDDIApiImpl(); + private UDDISecurityPortType security = new UDDISecurityImpl(); + private static TckSubscription tckSubscription = new TckSubscription(new UDDISubscriptionImpl(), new UDDISecurityImpl(), new UDDIInquiryImpl()); + + @BeforeClass + public static void startRegistry() throws ConfigurationException { + Registry.start(); + } + + @AfterClass + public static void stopRegistry() throws ConfigurationException { + Registry.stop(); + } + + @Test + public void testJoePublisher() { + //We can only test this if the publisher is not there already. + //If it already there is probably has foreign key relationships. + //This test should really only run on an empty database. Seed + //data will be added if the root publisher is missing. + if (!isExistPublisher(TckPublisher.getJoePublisherId())) { + saveJoePublisher(); + deleteJoePublisher(); + } + } + + @Test + public void testSamSyndicator() { + //We can only test this if the publisher is not there already. + if (!isExistPublisher(TckPublisher.getSamPublisherId())) { + saveSamSyndicator(); + deleteSamSyndicator(); + } + } + + /** + * Persists Joe Publisher to the database. + * + * @return - true if the published did not exist already, - false in all + * other cases. + */ + public boolean saveJoePublisher() { + if (!isExistPublisher(TckPublisher.getJoePublisherId())) { + savePublisher(TckPublisher.getJoePublisherId(), TckPublisher.JOE_PUBLISHER_XML); + return true; + } else { + return false; + } + } + + /** + * Persists Mary Publisher to the database. + * + * @return - true if the published did not exist already, - false in all + * other cases. + */ + public boolean saveMaryPublisher() { + if (!isExistPublisher(TckPublisher.getMaryPublisherId())) { + savePublisher(TckPublisher.getMaryPublisherId(), TckPublisher.MARY_PUBLISHER_XML); + return true; + } else { + return false; + } + } + + /** + * Removes Joe Publisher from the database, this will fail if there are + * child objects attached; think Services etc. + */ + public void deleteJoePublisher() { + deletePublisher(TckPublisher.getJoePublisherId()); + } + + /** + * Persists Sam Syndicator to the database. + * + * @return publisherId + */ + public String saveSamSyndicator() { + if (!isExistPublisher(TckPublisher.getSamPublisherId())) { + savePublisher(TckPublisher.getSamPublisherId(), TckPublisher.SAM_SYNDICATOR_XML); + } + return TckPublisher.getSamPublisherId(); + } + + /** + * Removes Sam Syndicator from the database, this will fail if there are + * child objects attached; think Services etc. + */ + public void deleteSamSyndicator() { + deletePublisher(TckPublisher.getSamPublisherId()); + } + + private void savePublisher(String publisherId, String publisherXML) { + try { + String rootPublisherStr = AppConfig.getConfiguration().getString(Property.JUDDI_ROOT_PUBLISHER); + logger.info("savePublisher as " + rootPublisherStr); + String authInfo = TckSecurity.getAuthToken(security, rootPublisherStr, ""); + logger.debug("Saving new publisher: " + publisherXML); + SavePublisher sp = new SavePublisher(); + sp.setAuthInfo(authInfo); + Publisher pubIn = (Publisher) EntityCreator.buildFromDoc(publisherXML, EntityCreator.JUDDIv3_Package); + sp.getPublisher().add(pubIn); + publisher.savePublisher(sp); + + // Now get the entity and check the values + GetPublisherDetail gp = new GetPublisherDetail(); + gp.getPublisherId().add(publisherId); + gp.setAuthInfo(authInfo); + PublisherDetail pd = publisher.getPublisherDetail(gp); + List pubOutList = pd.getPublisher(); + Publisher pubOut = pubOutList.get(0); + + assertEquals(pubIn.getAuthorizedName(), pubOut.getAuthorizedName()); + assertEquals(pubIn.getPublisherName(), pubOut.getPublisherName()); + assertEquals(pubIn.getEmailAddress(), pubOut.getEmailAddress()); + assertEquals(pubIn.isIsAdmin(), pubOut.isIsAdmin()); + assertEquals(pubIn.isIsEnabled(), pubOut.isIsEnabled()); + assertEquals(pubIn.getMaxBindingsPerService(), pubOut.getMaxBindingsPerService()); + assertEquals(pubIn.getMaxBusinesses(), pubOut.getMaxBusinesses()); + assertEquals(pubIn.getMaxServicePerBusiness(), pubOut.getMaxServicePerBusiness()); + assertEquals(pubIn.getMaxTModels(), pubOut.getMaxTModels()); + + logger.debug("Querying for publisher: " + publisherXML); + //Querying for this publisher to make sure it's really gone + //We're expecting a invalid Key exception at this point. + PublisherDetail pdBeforeDelete = null; + try { + pdBeforeDelete = publisher.getPublisherDetail(gp); + Assert.assertNotNull(pdBeforeDelete); + } catch (InvalidKeyPassedException e) { + Assert.fail("We expected to find publisher " + publisherXML); + } + + } catch (Exception e) { + logger.error(e.getMessage(), e); + Assert.fail("No exception should be thrown"); + } + } + + private void deletePublisher(String publisherId) { + try { + String rootPublisherStr = AppConfig.getConfiguration().getString(Property.JUDDI_ROOT_PUBLISHER); + String authInfo = TckSecurity.getAuthToken(security, rootPublisherStr, ""); + logger.debug("Delete publisher: " + publisherId); + //Now deleting this publisher + DeletePublisher dp = new DeletePublisher(); + dp.setAuthInfo(authInfo); + dp.getPublisherId().add(publisherId); + publisher.deletePublisher(dp); + + logger.info("Querying for publisher: " + publisherId + " after deletion."); + //Querying for this publisher to make sure it's really gone + //We're expecting a invalid Key exception at this point. + GetPublisherDetail gp = new GetPublisherDetail(); + gp.getPublisherId().add(publisherId); + gp.setAuthInfo(authInfo); + PublisherDetail pdAfterDelete = null; + try { + pdAfterDelete = publisher.getPublisherDetail(gp); + Assert.fail("We did not expect to find this publisher anymore."); + } catch (InvalidKeyPassedException e) { + Assert.assertNull(pdAfterDelete); + } + + } catch (Exception e) { + logger.error(e.getMessage(), e); + Assert.fail("No exception should be thrown"); + } + } + + private boolean isExistPublisher(String publisherId) { + GetPublisherDetail gp = new GetPublisherDetail(); + gp.getPublisherId().add(publisherId); + try { + publisher.getPublisherDetail(gp); + return true; + } catch (Exception e) { + return false; + } + } + + protected String authInfoJoe() throws RemoteException, DispositionReportFaultMessage { + return TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); + } + + protected String authInfoSam() throws RemoteException, DispositionReportFaultMessage { + return TckSecurity.getAuthToken(security, TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword()); + } + + /** + * Joe saves a subscription on Sam's behalf + * + * @throws Exception + */ + @Test + public void testAdminSaveSubscriptionAuthorized() throws Exception { + saveJoePublisher(); + saveSamSyndicator(); + DatatypeFactory fac = DatatypeFactory.newInstance(); + List subs = new ArrayList(); + Subscription s = new Subscription(); + + s.setMaxEntities(10); + s.setBrief(false); + GregorianCalendar gcal = new GregorianCalendar(); + gcal.setTimeInMillis(System.currentTimeMillis()); + gcal.add(Calendar.HOUR, 1); + s.setExpiresAfter(fac.newXMLGregorianCalendar(gcal)); + s.setSubscriptionFilter(new SubscriptionFilter()); + s.getSubscriptionFilter().setFindBusiness(new FindBusiness()); + s.getSubscriptionFilter().getFindBusiness().setFindQualifiers(new FindQualifiers()); + s.getSubscriptionFilter().getFindBusiness().getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); + s.getSubscriptionFilter().getFindBusiness().getName().add(new Name(UDDIConstants.WILDCARD, null)); + subs.add(s); + Holder> items = new Holder>(); + items.value = subs; + publisher.adminSaveSubscription(authInfoJoe(), TckPublisher.getSamPublisherId(), items); + for (int i = 0; i < items.value.size(); i++) { + tckSubscription.deleteSubscription(authInfoSam(), items.value.get(i).getSubscriptionKey()); + } + + deleteJoePublisher(); + deleteSamSyndicator(); + + } + + /** + * Sam saves a subscription on Sam's behalf (not authorized + * + * @throws Exception + */ + @Test(expected = UserMismatchException.class) + public void testAdminSaveSubscriptionNotAuthorized() throws Exception { + saveJoePublisher(); + saveSamSyndicator(); + DatatypeFactory fac = DatatypeFactory.newInstance(); + List subs = new ArrayList(); + Subscription s = new Subscription(); + + s.setMaxEntities(10); + s.setBrief(false); + GregorianCalendar gcal = new GregorianCalendar(); + gcal.setTimeInMillis(System.currentTimeMillis()); + gcal.add(Calendar.HOUR, 1); + s.setExpiresAfter(fac.newXMLGregorianCalendar(gcal)); + s.setSubscriptionFilter(new SubscriptionFilter()); + s.getSubscriptionFilter().setFindBusiness(new FindBusiness()); + s.getSubscriptionFilter().getFindBusiness().setFindQualifiers(new FindQualifiers()); + s.getSubscriptionFilter().getFindBusiness().getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); + s.getSubscriptionFilter().getFindBusiness().getName().add(new Name(UDDIConstants.WILDCARD, null)); + subs.add(s); + Holder> items = new Holder>(); + items.value = subs; + publisher.adminSaveSubscription(authInfoSam(), TckPublisher.getJoePublisherId(), items); + deleteJoePublisher(); + deleteSamSyndicator(); + + } + + @Test + public void testAdminSaveTModel() throws Exception { + saveJoePublisher(); + saveSamSyndicator(); + List values = new ArrayList(); + org.apache.juddi.api_v3.AdminSaveTModelWrapper x = new org.apache.juddi.api_v3.AdminSaveTModelWrapper(); + x.setPublisherID(TckPublisher.getSamPublisherId()); + TModel tm = new TModel(); + tm.setName(new Name("testAdminSaveTModel joe on sam's behalf", null)); + + x.getTModel().add(tm); + publisher.adminSaveTModel(authInfoJoe(), values); + deleteJoePublisher(); + deleteSamSyndicator(); + } + +} diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_020_TmodelTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_020_TmodelTest.java similarity index 97% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/API_020_TmodelTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_020_TmodelTest.java index da65e4b4d..94292f9ff 100644 --- a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_020_TmodelTest.java +++ b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_020_TmodelTest.java @@ -1,125 +1,125 @@ -/* - * Copyright 2001-2009 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.rmi.RemoteException; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.Registry; -import org.apache.juddi.v3.tck.TckPublisher; -import org.apache.juddi.v3.tck.TckSecurity; -import org.apache.juddi.v3.tck.TckTModel; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.uddi.api_v3.CategoryBag; -import org.uddi.api_v3.KeyedReference; -import org.uddi.api_v3.Name; -import org.uddi.api_v3.TModel; -import org.uddi.api_v3.TModelDetail; -import org.uddi.api_v3.TModelInfo; -import org.uddi.api_v3.TModelList; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.v3_service.UDDISecurityPortType; - -/** - * @author Jeff Faath - * @author Kurt T Stam - */ -public class API_020_TmodelTest { - - private static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - private static Log logger = LogFactory.getLog(API_020_TmodelTest.class); - private static API_010_PublisherTest api010 = new API_010_PublisherTest(); - private static String authInfoJoe = null; - private static String authInfoSam = null; - - @BeforeClass - public static void setup() throws ConfigurationException, RemoteException { - Registry.start(); - logger.debug("Getting auth tokens.."); - try { - api010.saveJoePublisher(); - api010.saveSamSyndicator(); - UDDISecurityPortType security = new UDDISecurityImpl(); - authInfoJoe = TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); - authInfoSam = TckSecurity.getAuthToken(security, TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword()); - } catch (DispositionReportFaultMessage e) { - logger.error(e.getMessage(), e); - Assert.fail("Could not obtain authInfo token."); - } - } - - @AfterClass - public static void stopRegistry() throws ConfigurationException { - Registry.stop(); - } - - @Test - public void testJoePublisherTmodel() { - tckTModel.saveJoePublisherTmodel(authInfoJoe, true); - - //Now if we use a finder it should be found. - TModelList tModelList = tckTModel.findJoeTModelDetail(); - Assert.assertNotNull(tModelList.getTModelInfos()); - - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - - //Even if it deleted you should still be able to access it through a getTModelDetail - TModelDetail detail = tckTModel.getJoePublisherTmodel(authInfoJoe); - Assert.assertNotNull(detail.getTModel()); - - //However if we use a finder it should not be found. - TModelList tModelList2 = tckTModel.findJoeTModelDetail(); - Assert.assertNull(tModelList2.getTModelInfos()); - - //Make sure none of the found key generators is Joe's key generator - TModelList tModelList3 = tckTModel.findJoeTModelDetailByCategoryBag(); - for (TModelInfo tModelInfo : tModelList3.getTModelInfos().getTModelInfo()) { - Assert.assertFalse("uddi:uddi.joepublisher.com:keygenerator".equals(tModelInfo.getTModelKey())); - } - } - - @Test - public void testSamSyndicatorTmodelTest() { - tckTModel.saveSamSyndicatorTmodel(authInfoSam); - tckTModel.deleteSamSyndicatorTmodel(authInfoSam); - } - - - @Test - public void testJUDDI956Test(){ - tckTModel.saveJoePublisherTmodel(authInfoJoe, true); - TModel one = new TModel(); - one.setTModelKey("uddi:uddi.joepublisher.com:juddi956"); - one.setName(new Name("JUDDI-956 Test case", "EN")); - - tckTModel.saveTModel(authInfoJoe, one, false); - TModel two = new TModel(); - two.setTModelKey("uddi:uddi.joepublisher.com:juddi956-2"); - two.setName(new Name("JUDDI-956 Test case", "EN")); - two.setCategoryBag(new CategoryBag()); - two.getCategoryBag().getKeyedReference().add(new KeyedReference("uddi:uddi.joepublisher.com:juddi956", "juddi956", "a value")); - tckTModel.saveTModel(authInfoJoe, one, false); - - tckTModel.deleteTModel(authInfoJoe, null, "uddi:uddi.joepublisher.com:juddi956-2"); - tckTModel.deleteTModel(authInfoJoe, null, "uddi:uddi.joepublisher.com:juddi956"); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - - } -} +/* + * Copyright 2001-2009 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.rmi.RemoteException; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.Registry; +import org.apache.juddi.v3.tck.TckPublisher; +import org.apache.juddi.v3.tck.TckSecurity; +import org.apache.juddi.v3.tck.TckTModel; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.uddi.api_v3.CategoryBag; +import org.uddi.api_v3.KeyedReference; +import org.uddi.api_v3.Name; +import org.uddi.api_v3.TModel; +import org.uddi.api_v3.TModelDetail; +import org.uddi.api_v3.TModelInfo; +import org.uddi.api_v3.TModelList; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.v3_service.UDDISecurityPortType; + +/** + * @author Jeff Faath + * @author Kurt T Stam + */ +public class API_020_TmodelTest { + + private static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + private static Log logger = LogFactory.getLog(API_020_TmodelTest.class); + private static API_010_PublisherTest api010 = new API_010_PublisherTest(); + private static String authInfoJoe = null; + private static String authInfoSam = null; + + @BeforeClass + public static void setup() throws ConfigurationException, RemoteException { + Registry.start(); + logger.debug("Getting auth tokens.."); + try { + api010.saveJoePublisher(); + api010.saveSamSyndicator(); + UDDISecurityPortType security = new UDDISecurityImpl(); + authInfoJoe = TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); + authInfoSam = TckSecurity.getAuthToken(security, TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword()); + } catch (DispositionReportFaultMessage e) { + logger.error(e.getMessage(), e); + Assert.fail("Could not obtain authInfo token."); + } + } + + @AfterClass + public static void stopRegistry() throws ConfigurationException { + Registry.stop(); + } + + @Test + public void testJoePublisherTmodel() { + tckTModel.saveJoePublisherTmodel(authInfoJoe, true); + + //Now if we use a finder it should be found. + TModelList tModelList = tckTModel.findJoeTModelDetail(); + Assert.assertNotNull(tModelList.getTModelInfos()); + + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + + //Even if it deleted you should still be able to access it through a getTModelDetail + TModelDetail detail = tckTModel.getJoePublisherTmodel(authInfoJoe); + Assert.assertNotNull(detail.getTModel()); + + //However if we use a finder it should not be found. + TModelList tModelList2 = tckTModel.findJoeTModelDetail(); + Assert.assertNull(tModelList2.getTModelInfos()); + + //Make sure none of the found key generators is Joe's key generator + TModelList tModelList3 = tckTModel.findJoeTModelDetailByCategoryBag(); + for (TModelInfo tModelInfo : tModelList3.getTModelInfos().getTModelInfo()) { + Assert.assertFalse("uddi:uddi.joepublisher.com:keygenerator".equals(tModelInfo.getTModelKey())); + } + } + + @Test + public void testSamSyndicatorTmodelTest() { + tckTModel.saveSamSyndicatorTmodel(authInfoSam); + tckTModel.deleteSamSyndicatorTmodel(authInfoSam); + } + + + @Test + public void testJUDDI956Test(){ + tckTModel.saveJoePublisherTmodel(authInfoJoe, true); + TModel one = new TModel(); + one.setTModelKey("uddi:uddi.joepublisher.com:juddi956"); + one.setName(new Name("JUDDI-956 Test case", "EN")); + + tckTModel.saveTModel(authInfoJoe, one, false); + TModel two = new TModel(); + two.setTModelKey("uddi:uddi.joepublisher.com:juddi956-2"); + two.setName(new Name("JUDDI-956 Test case", "EN")); + two.setCategoryBag(new CategoryBag()); + two.getCategoryBag().getKeyedReference().add(new KeyedReference("uddi:uddi.joepublisher.com:juddi956", "juddi956", "a value")); + tckTModel.saveTModel(authInfoJoe, one, false); + + tckTModel.deleteTModel(authInfoJoe, null, "uddi:uddi.joepublisher.com:juddi956-2"); + tckTModel.deleteTModel(authInfoJoe, null, "uddi:uddi.joepublisher.com:juddi956"); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + + } +} diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_030_BusinessEntityTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_030_BusinessEntityTest.java similarity index 97% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/API_030_BusinessEntityTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_030_BusinessEntityTest.java index 519428b2e..b0239d99b 100644 --- a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_030_BusinessEntityTest.java +++ b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_030_BusinessEntityTest.java @@ -1,160 +1,160 @@ -/* - * Copyright 2001-2009 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.rmi.RemoteException; -import java.util.UUID; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.Registry; -import org.apache.juddi.auth.MockWebServiceContext; -import org.apache.juddi.v3.tck.TckBusiness; -import org.apache.juddi.v3.tck.TckFindEntity; -import org.apache.juddi.v3.tck.TckPublisher; -import org.apache.juddi.v3.tck.TckSecurity; -import org.apache.juddi.v3.tck.TckTModel; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.uddi.api_v3.BusinessDetail; -import org.uddi.api_v3.BusinessEntity; -import org.uddi.api_v3.Name; -import org.uddi.api_v3.SaveBusiness; -import org.uddi.v3_service.UDDISecurityPortType; - -/** - * @author Jeff Faath - * @author Kurt T Stam - * @author Alex O'Ree - */ -public class API_030_BusinessEntityTest { - - private static Log logger = LogFactory.getLog(API_030_BusinessEntityTest.class); - private static API_010_PublisherTest api010 = new API_010_PublisherTest(); - private static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - private static TckBusiness tckBusiness = new TckBusiness(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - private static TckFindEntity tckFindEntity = new TckFindEntity(new UDDIInquiryImpl()); - private static String authInfoJoe = null; - private static String authInfoSam = null; - - @BeforeClass - public static void setup() throws ConfigurationException { - Registry.start(); - logger.info("API_030_BusinessEntityTest"); - logger.debug("Getting auth token.."); - try { - api010.saveJoePublisher(); - api010.saveSamSyndicator(); - UDDISecurityPortType security = new UDDISecurityImpl(); - authInfoJoe = TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); - authInfoSam = TckSecurity.getAuthToken(security, TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword()); - String authInfoUDDI = TckSecurity.getAuthToken(security, TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword()); - tckTModel.saveUDDIPublisherTmodel(authInfoUDDI); - tckTModel.saveTModels(authInfoUDDI, TckTModel.TMODELS_XML); - } catch (RemoteException e) { - logger.error(e.getMessage(), e); - Assert.fail("Could not obtain authInfo token."); - } - } - - @AfterClass - public static void stopRegistry() throws ConfigurationException { - tckTModel.deleteCreatedTModels(authInfoJoe); - Registry.stop(); - } - - @Test - public void testJoePublisherBusinessEntity() { - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe); - - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - } catch (Exception e) { - e.printStackTrace(); - - } finally { - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - } - } - - @Test - public void testSamSyndicatorBusiness() { - try { - tckTModel.saveSamSyndicatorTmodel(authInfoSam); - tckBusiness.saveSamSyndicatorBusiness(authInfoSam); - tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); - } finally { - tckTModel.deleteSamSyndicatorTmodel(authInfoSam); - } - } - - @Test - public void testJoePublisherBusinessEntitySignature() { - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckBusiness.saveJoePublisherBusinessX509Signature(authInfoJoe); - tckFindEntity.findAllBusiness(); - tckTModel.saveSamSyndicatorTmodel(authInfoSam); - tckBusiness.saveSamSyndicatorBusiness(authInfoSam); - - //find the signed business - tckFindEntity.findAllSignedBusiness(); - - tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - - } finally { - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - tckTModel.deleteSamSyndicatorTmodel(authInfoSam); - } - } - - /** - * simulates a multinode registry via replication and attempts to save - * content that is owned by another node. - * - * @throws Exception - */ - @Test - public void testJIRA727() throws Exception { - UDDIPublicationImplExt pubRemoteNode = new UDDIPublicationImplExt(new MockWebServiceContext(null)); - UDDIPublicationImpl pubLocalNode = new UDDIPublicationImpl(); - UDDISecurityPortType security = new UDDISecurityImpl(); - authInfoSam = TckSecurity.getAuthToken(security, TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword()); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoSam); - BusinessEntity be = new BusinessEntity(); - be.getName().add(new Name("testJIRA727", "en")); - String node = "testJIRA727Node" + UUID.randomUUID().toString(); - sb.getBusinessEntity().add(be); - BusinessDetail saveBusinessFudge = pubRemoteNode.saveBusinessFudge(sb, node); - - sb = new SaveBusiness(); - sb.setAuthInfo(authInfoSam); - sb.getBusinessEntity().add(saveBusinessFudge.getBusinessEntity().get(0)); - try { - saveBusinessFudge = pubLocalNode.saveBusiness(sb); - Assert.fail("unexpected success"); - } catch (Exception ex) { - logger.warn(ex.getMessage()); - logger.debug(ex); - } - - } -} +/* + * Copyright 2001-2009 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.rmi.RemoteException; +import java.util.UUID; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.Registry; +import org.apache.juddi.auth.MockWebServiceContext; +import org.apache.juddi.v3.tck.TckBusiness; +import org.apache.juddi.v3.tck.TckFindEntity; +import org.apache.juddi.v3.tck.TckPublisher; +import org.apache.juddi.v3.tck.TckSecurity; +import org.apache.juddi.v3.tck.TckTModel; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.uddi.api_v3.BusinessDetail; +import org.uddi.api_v3.BusinessEntity; +import org.uddi.api_v3.Name; +import org.uddi.api_v3.SaveBusiness; +import org.uddi.v3_service.UDDISecurityPortType; + +/** + * @author Jeff Faath + * @author Kurt T Stam + * @author Alex O'Ree + */ +public class API_030_BusinessEntityTest { + + private static Log logger = LogFactory.getLog(API_030_BusinessEntityTest.class); + private static API_010_PublisherTest api010 = new API_010_PublisherTest(); + private static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + private static TckBusiness tckBusiness = new TckBusiness(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + private static TckFindEntity tckFindEntity = new TckFindEntity(new UDDIInquiryImpl()); + private static String authInfoJoe = null; + private static String authInfoSam = null; + + @BeforeClass + public static void setup() throws ConfigurationException { + Registry.start(); + logger.info("API_030_BusinessEntityTest"); + logger.debug("Getting auth token.."); + try { + api010.saveJoePublisher(); + api010.saveSamSyndicator(); + UDDISecurityPortType security = new UDDISecurityImpl(); + authInfoJoe = TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); + authInfoSam = TckSecurity.getAuthToken(security, TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword()); + String authInfoUDDI = TckSecurity.getAuthToken(security, TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword()); + tckTModel.saveUDDIPublisherTmodel(authInfoUDDI); + tckTModel.saveTModels(authInfoUDDI, TckTModel.TMODELS_XML); + } catch (RemoteException e) { + logger.error(e.getMessage(), e); + Assert.fail("Could not obtain authInfo token."); + } + } + + @AfterClass + public static void stopRegistry() throws ConfigurationException { + tckTModel.deleteCreatedTModels(authInfoJoe); + Registry.stop(); + } + + @Test + public void testJoePublisherBusinessEntity() { + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe); + + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + } catch (Exception e) { + e.printStackTrace(); + + } finally { + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + } + } + + @Test + public void testSamSyndicatorBusiness() { + try { + tckTModel.saveSamSyndicatorTmodel(authInfoSam); + tckBusiness.saveSamSyndicatorBusiness(authInfoSam); + tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); + } finally { + tckTModel.deleteSamSyndicatorTmodel(authInfoSam); + } + } + + @Test + public void testJoePublisherBusinessEntitySignature() { + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckBusiness.saveJoePublisherBusinessX509Signature(authInfoJoe); + tckFindEntity.findAllBusiness(); + tckTModel.saveSamSyndicatorTmodel(authInfoSam); + tckBusiness.saveSamSyndicatorBusiness(authInfoSam); + + //find the signed business + tckFindEntity.findAllSignedBusiness(); + + tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + + } finally { + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + tckTModel.deleteSamSyndicatorTmodel(authInfoSam); + } + } + + /** + * simulates a multinode registry via replication and attempts to save + * content that is owned by another node. + * + * @throws Exception + */ + @Test + public void testJIRA727() throws Exception { + UDDIPublicationImplExt pubRemoteNode = new UDDIPublicationImplExt(new MockWebServiceContext(null)); + UDDIPublicationImpl pubLocalNode = new UDDIPublicationImpl(); + UDDISecurityPortType security = new UDDISecurityImpl(); + authInfoSam = TckSecurity.getAuthToken(security, TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword()); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoSam); + BusinessEntity be = new BusinessEntity(); + be.getName().add(new Name("testJIRA727", "en")); + String node = "testJIRA727Node" + UUID.randomUUID().toString(); + sb.getBusinessEntity().add(be); + BusinessDetail saveBusinessFudge = pubRemoteNode.saveBusinessFudge(sb, node); + + sb = new SaveBusiness(); + sb.setAuthInfo(authInfoSam); + sb.getBusinessEntity().add(saveBusinessFudge.getBusinessEntity().get(0)); + try { + saveBusinessFudge = pubLocalNode.saveBusiness(sb); + Assert.fail("unexpected success"); + } catch (Exception ex) { + logger.warn(ex.getMessage()); + logger.debug(ex); + } + + } +} diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_040_BusinessServiceLoadTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_040_BusinessServiceLoadTest.java similarity index 98% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/API_040_BusinessServiceLoadTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_040_BusinessServiceLoadTest.java index 7c95fcb0e..fd00bca8e 100644 --- a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_040_BusinessServiceLoadTest.java +++ b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_040_BusinessServiceLoadTest.java @@ -1,172 +1,172 @@ -/* - * Copyright 2001-2009 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.io.File; -import java.rmi.RemoteException; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.Registry; -import org.apache.juddi.config.AppConfig; -import static org.apache.juddi.config.AppConfig.JUDDI_CONFIGURATION_FILE_SYSTEM_PROPERTY; -import org.apache.juddi.config.Property; -import org.apache.juddi.query.util.FindQualifiers; -import org.apache.juddi.v3.tck.TckBusiness; -import org.apache.juddi.v3.tck.TckBusinessService; -import org.apache.juddi.v3.tck.TckPublisher; -import org.apache.juddi.v3.tck.TckSecurity; -import org.apache.juddi.v3.tck.TckTModel; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.uddi.api_v3.BusinessList; -import org.uddi.api_v3.FindBusiness; -import org.uddi.api_v3.FindService; -import org.uddi.api_v3.Name; -import org.uddi.api_v3.ServiceList; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.v3_service.UDDISecurityPortType; - -/** - * @author Kurt T Stam - * @author Alex O'Ree - */ -public class API_040_BusinessServiceLoadTest { - - private static Log logger = LogFactory.getLog(API_040_BusinessServiceTest.class); - - private static API_010_PublisherTest api010 = new API_010_PublisherTest(); - protected static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - protected static TckBusiness tckBusiness = new TckBusiness(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - protected static TckBusinessService tckBusinessService = new TckBusinessService(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - private static UDDIInquiryImpl inquiry = new UDDIInquiryImpl(); - - int numberOfBusinesses = 100; - int numberOfServices = 100; - - protected static String authInfoJoe = null; - protected static String authInfoSam = null; - - @BeforeClass - public static void setup() throws ConfigurationException { - File f = new File("."); - System.out.println("Current working dir is " + f.getAbsolutePath()); - System.setProperty(JUDDI_CONFIGURATION_FILE_SYSTEM_PROPERTY, f.getAbsolutePath()+"/src/test/resources/juddiv3DisabledTModelKeybag.xml"); - Registry.start(); - logger.info("API_040_BusinessServiceTestPerformance"); - logger.debug("Getting auth tokens.."); - try { - api010.saveJoePublisher(); - UDDISecurityPortType security = new UDDISecurityImpl(); - authInfoJoe = TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); - String authInfoUDDI = TckSecurity.getAuthToken(security, TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword()); - tckTModel.saveUDDIPublisherTmodel(authInfoUDDI); - tckTModel.saveTModels(authInfoUDDI, TckTModel.TMODELS_XML); - } catch (RemoteException e) { - logger.error(e.getMessage(), e); - Assert.fail("Could not obtain authInfo token."); - } - } - - @AfterClass - public static void shutdown() throws ConfigurationException { - tckTModel.deleteCreatedTModels(authInfoJoe); - Registry.stop(); - System.clearProperty(JUDDI_CONFIGURATION_FILE_SYSTEM_PROPERTY); - } - - /** - * loads the database with 100x100 services, runs a basic query, then - * deletes the records - * - * @throws DispositionReportFaultMessage - * @throws ConfigurationException - */ - @Test - //@Ignore - public void find20Businesses() throws DispositionReportFaultMessage, ConfigurationException { - //disable TModelBag filtering - Assume.assumeTrue(TckPublisher.isLoadTest()); - try { - //logger.info("Disabling findBusiness tModelBag filtering...."); - //AppConfig.getConfiguration().setProperty(Property.JUDDI_ENABLE_FIND_BUSINESS_TMODEL_BAG_FILTERING, false); - //logger.info("findBusiness tModelBag filtering is enabled: " - // + AppConfig.getConfiguration().getProperty(Property.JUDDI_ENABLE_FIND_BUSINESS_TMODEL_BAG_FILTERING)); - System.setProperty(JUDDI_CONFIGURATION_FILE_SYSTEM_PROPERTY, "/src/test/resources/juddiv3DisabledTModelKeybag.xml"); - tckTModel.saveJoePublisherTmodel(authInfoJoe); - long startSave = System.currentTimeMillis(); - //loading up 100 businesses, with a 100 services each - tckBusiness.saveJoePublisherBusinesses(authInfoJoe, numberOfBusinesses); - for (int i = 0; i < numberOfBusinesses; i++) { - tckBusinessService.saveJoePublisherServices(authInfoJoe, i, numberOfServices); - } - long saveDuration = System.currentTimeMillis() - startSave; - System.out.println("Saved " + numberOfBusinesses + " businesses with each " + numberOfServices + " services in " + saveDuration + "ms"); - System.out.println("Tiggering findBusiness query..."); - //find 20 businesses by name - FindBusiness fb = new FindBusiness(); - org.uddi.api_v3.FindQualifiers apiFq = new org.uddi.api_v3.FindQualifiers(); - apiFq.getFindQualifier().add(FindQualifiers.APPROXIMATE_MATCH); - apiFq.getFindQualifier().add(FindQualifiers.CASE_INSENSITIVE_MATCH); - fb.setFindQualifiers(apiFq); - Name name = new Name(); - name.setValue("John%"); - fb.getName().add(name); - fb.setMaxRows(20); - long startFind = System.currentTimeMillis(); - BusinessList result = inquiry.findBusiness(fb); - long findDuration = System.currentTimeMillis() - startFind; - System.out.println("Find 20 businesses took " + findDuration + "ms. Size=" + result.getBusinessInfos().getBusinessInfo().size()); - // it takes less then 1 second, make sure it stays faster then 5 seconds - if (findDuration > 20000) { - Assert.fail("This operation took too long to process"); - } - //Assert.assertTrue(findDuration < 5000); - System.out.println("Tiggering findService query..."); - FindService fs = new FindService(); - fs.setFindQualifiers(apiFq); - name.setValue("Service One%"); - fs.getName().add(name); - startFind = System.currentTimeMillis(); - //this will match ALL services (100 * 100 =) 10,000 services - int all = numberOfBusinesses * numberOfServices; - System.out.println("Matching " + all + " services"); - ServiceList serviceList = inquiry.findService(fs); - findDuration = System.currentTimeMillis() - startFind; - System.out.println("Find " + all + " services took " + findDuration + "ms. Size=" + serviceList.getServiceInfos().getServiceInfo().size()); - if (findDuration > 20000) { - Assert.fail("This operation took too long to process"); - } - - } finally { - System.out.println("Tiggering deletion..."); - long startDelete = System.currentTimeMillis(); - for (int i = 0; i < numberOfBusinesses; i++) { - tckBusinessService.deleteJoePublisherServices(authInfoJoe, i, numberOfServices); - } - long deleteDuration = System.currentTimeMillis() - startDelete; - System.out.println("Delete all business and services in " + deleteDuration + "ms"); - tckBusiness.deleteJoePublisherBusinesses(authInfoJoe, numberOfBusinesses); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - } - - } - -} +/* + * Copyright 2001-2009 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.io.File; +import java.rmi.RemoteException; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.Registry; +import org.apache.juddi.config.AppConfig; +import static org.apache.juddi.config.AppConfig.JUDDI_CONFIGURATION_FILE_SYSTEM_PROPERTY; +import org.apache.juddi.config.Property; +import org.apache.juddi.query.util.FindQualifiers; +import org.apache.juddi.v3.tck.TckBusiness; +import org.apache.juddi.v3.tck.TckBusinessService; +import org.apache.juddi.v3.tck.TckPublisher; +import org.apache.juddi.v3.tck.TckSecurity; +import org.apache.juddi.v3.tck.TckTModel; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Assume; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.uddi.api_v3.BusinessList; +import org.uddi.api_v3.FindBusiness; +import org.uddi.api_v3.FindService; +import org.uddi.api_v3.Name; +import org.uddi.api_v3.ServiceList; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.v3_service.UDDISecurityPortType; + +/** + * @author Kurt T Stam + * @author Alex O'Ree + */ +public class API_040_BusinessServiceLoadTest { + + private static Log logger = LogFactory.getLog(API_040_BusinessServiceTest.class); + + private static API_010_PublisherTest api010 = new API_010_PublisherTest(); + protected static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + protected static TckBusiness tckBusiness = new TckBusiness(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + protected static TckBusinessService tckBusinessService = new TckBusinessService(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + private static UDDIInquiryImpl inquiry = new UDDIInquiryImpl(); + + int numberOfBusinesses = 100; + int numberOfServices = 100; + + protected static String authInfoJoe = null; + protected static String authInfoSam = null; + + @BeforeClass + public static void setup() throws ConfigurationException { + File f = new File("."); + System.out.println("Current working dir is " + f.getAbsolutePath()); + System.setProperty(JUDDI_CONFIGURATION_FILE_SYSTEM_PROPERTY, f.getAbsolutePath()+"/src/test/resources/juddiv3DisabledTModelKeybag.xml"); + Registry.start(); + logger.info("API_040_BusinessServiceTestPerformance"); + logger.debug("Getting auth tokens.."); + try { + api010.saveJoePublisher(); + UDDISecurityPortType security = new UDDISecurityImpl(); + authInfoJoe = TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); + String authInfoUDDI = TckSecurity.getAuthToken(security, TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword()); + tckTModel.saveUDDIPublisherTmodel(authInfoUDDI); + tckTModel.saveTModels(authInfoUDDI, TckTModel.TMODELS_XML); + } catch (RemoteException e) { + logger.error(e.getMessage(), e); + Assert.fail("Could not obtain authInfo token."); + } + } + + @AfterClass + public static void shutdown() throws ConfigurationException { + tckTModel.deleteCreatedTModels(authInfoJoe); + Registry.stop(); + System.clearProperty(JUDDI_CONFIGURATION_FILE_SYSTEM_PROPERTY); + } + + /** + * loads the database with 100x100 services, runs a basic query, then + * deletes the records + * + * @throws DispositionReportFaultMessage + * @throws ConfigurationException + */ + @Test + //@Ignore + public void find20Businesses() throws DispositionReportFaultMessage, ConfigurationException { + //disable TModelBag filtering + Assume.assumeTrue(TckPublisher.isLoadTest()); + try { + //logger.info("Disabling findBusiness tModelBag filtering...."); + //AppConfig.getConfiguration().setProperty(Property.JUDDI_ENABLE_FIND_BUSINESS_TMODEL_BAG_FILTERING, false); + //logger.info("findBusiness tModelBag filtering is enabled: " + // + AppConfig.getConfiguration().getProperty(Property.JUDDI_ENABLE_FIND_BUSINESS_TMODEL_BAG_FILTERING)); + System.setProperty(JUDDI_CONFIGURATION_FILE_SYSTEM_PROPERTY, "/src/test/resources/juddiv3DisabledTModelKeybag.xml"); + tckTModel.saveJoePublisherTmodel(authInfoJoe); + long startSave = System.currentTimeMillis(); + //loading up 100 businesses, with a 100 services each + tckBusiness.saveJoePublisherBusinesses(authInfoJoe, numberOfBusinesses); + for (int i = 0; i < numberOfBusinesses; i++) { + tckBusinessService.saveJoePublisherServices(authInfoJoe, i, numberOfServices); + } + long saveDuration = System.currentTimeMillis() - startSave; + System.out.println("Saved " + numberOfBusinesses + " businesses with each " + numberOfServices + " services in " + saveDuration + "ms"); + System.out.println("Tiggering findBusiness query..."); + //find 20 businesses by name + FindBusiness fb = new FindBusiness(); + org.uddi.api_v3.FindQualifiers apiFq = new org.uddi.api_v3.FindQualifiers(); + apiFq.getFindQualifier().add(FindQualifiers.APPROXIMATE_MATCH); + apiFq.getFindQualifier().add(FindQualifiers.CASE_INSENSITIVE_MATCH); + fb.setFindQualifiers(apiFq); + Name name = new Name(); + name.setValue("John%"); + fb.getName().add(name); + fb.setMaxRows(20); + long startFind = System.currentTimeMillis(); + BusinessList result = inquiry.findBusiness(fb); + long findDuration = System.currentTimeMillis() - startFind; + System.out.println("Find 20 businesses took " + findDuration + "ms. Size=" + result.getBusinessInfos().getBusinessInfo().size()); + // it takes less then 1 second, make sure it stays faster then 5 seconds + if (findDuration > 20000) { + Assert.fail("This operation took too long to process"); + } + //Assert.assertTrue(findDuration < 5000); + System.out.println("Tiggering findService query..."); + FindService fs = new FindService(); + fs.setFindQualifiers(apiFq); + name.setValue("Service One%"); + fs.getName().add(name); + startFind = System.currentTimeMillis(); + //this will match ALL services (100 * 100 =) 10,000 services + int all = numberOfBusinesses * numberOfServices; + System.out.println("Matching " + all + " services"); + ServiceList serviceList = inquiry.findService(fs); + findDuration = System.currentTimeMillis() - startFind; + System.out.println("Find " + all + " services took " + findDuration + "ms. Size=" + serviceList.getServiceInfos().getServiceInfo().size()); + if (findDuration > 20000) { + Assert.fail("This operation took too long to process"); + } + + } finally { + System.out.println("Tiggering deletion..."); + long startDelete = System.currentTimeMillis(); + for (int i = 0; i < numberOfBusinesses; i++) { + tckBusinessService.deleteJoePublisherServices(authInfoJoe, i, numberOfServices); + } + long deleteDuration = System.currentTimeMillis() - startDelete; + System.out.println("Delete all business and services in " + deleteDuration + "ms"); + tckBusiness.deleteJoePublisherBusinesses(authInfoJoe, numberOfBusinesses); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + } + + } + +} diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_040_BusinessServiceTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_040_BusinessServiceTest.java similarity index 97% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/API_040_BusinessServiceTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_040_BusinessServiceTest.java index 5aa0575ce..ee8f59f99 100644 --- a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_040_BusinessServiceTest.java +++ b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_040_BusinessServiceTest.java @@ -1,181 +1,181 @@ -/* - * Copyright 2001-2009 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.rmi.RemoteException; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.Registry; -import org.apache.juddi.v3.tck.TckBusiness; -import org.apache.juddi.v3.tck.TckBusinessService; -import org.apache.juddi.v3.tck.TckPublisher; -import org.apache.juddi.v3.tck.TckSecurity; -import org.apache.juddi.v3.tck.TckTModel; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.uddi.v3_service.UDDISecurityPortType; - -/** - * @author Jeff Faath - * @author Kurt T Stam - */ -public class API_040_BusinessServiceTest -{ - private static Log logger = LogFactory.getLog(API_040_BusinessServiceTest.class); - - private static API_010_PublisherTest api010 = new API_010_PublisherTest(); - private static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - private static TckBusiness tckBusiness = new TckBusiness(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - private static TckBusinessService tckBusinessService = new TckBusinessService(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - - private static String authInfoJoe = null; - private static String authInfoSam = null; - - @BeforeClass - public static void setup() throws ConfigurationException { - Registry.start(); - logger.info("API_040_BusinessServiceTest"); - logger.debug("Getting auth tokens.."); - - try { - api010.saveJoePublisher(); - api010.saveSamSyndicator(); - UDDISecurityPortType security = new UDDISecurityImpl(); - authInfoJoe = TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); - authInfoSam = TckSecurity.getAuthToken(security, TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword()); - String authInfoUDDI = TckSecurity.getAuthToken(security, TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword()); - tckTModel.saveUDDIPublisherTmodel(authInfoUDDI); - tckTModel.saveTModels(authInfoUDDI, TckTModel.TMODELS_XML); - } catch (RemoteException e) { - logger.error(e.getMessage(), e); - Assert.fail("Could not obtain authInfo token."); - } - } - - @AfterClass - public static void stopRegistry() throws ConfigurationException { - tckTModel.deleteCreatedTModels(authInfoJoe); - Registry.stop(); - } - - @Test - public void joepublisher() { - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusinessService.saveJoePublisherService(authInfoJoe); - tckBusinessService.deleteJoePublisherService(authInfoJoe); - } finally { - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - } - } - - @Test - public void joepublisher2Services() { - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusinessService.saveJoePublisherService(authInfoJoe); - tckBusinessService.saveJoePublisherService2(authInfoJoe); - tckBusinessService.deleteJoePublisherService(authInfoJoe); - tckBusinessService.deleteJoePublisherService2(authInfoJoe); - } finally { - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - } - } - - @Test - public void joepublisher2UpdateBusiness() { - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusinessService.saveJoePublisherService(authInfoJoe); - tckBusinessService.saveJoePublisherService2(authInfoJoe); - tckBusiness.updateJoePublisherBusiness(authInfoJoe); - tckBusinessService.deleteJoePublisherService(authInfoJoe); - tckBusinessService.deleteJoePublisherService2(authInfoJoe); - } finally { - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - } - } - /** - * 5.2.16.3 paragraph 4 - * Data contained within businessEntity structures can be rearranged with - * this API call. This can be done by redefining parent container relationships - * for other registered information. For instance, if a new businessEntity - * is saved with information about a businessService that is registered - * already as part of a different businessEntity, this results in the - * businessService being moved from its current container to the new businessEntity. - * This condition occurs when the businessKey of the businessService being - * saved matches the businessKey of the businessEntity being saved. - * An attempt to delete or move a businessService in this manner by - * a party who is not the publisher of the businessService MUST be - * rejected with an error E_userMismatch. - */ - @Test - public void joepublisherMoveBusinessService() { - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusinessService.saveJoePublisherService(authInfoJoe); - tckBusiness.checkServicesBusinessOne(1); - tckBusiness.saveJoePublisherBusiness3(authInfoJoe); - //check that this business has no services - tckBusiness.checkServicesBusinessThree(0); - //Now move the service from one to three - tckBusiness.saveJoePublisherBusiness1to3(authInfoJoe); - tckBusiness.checkServicesBusinessOne(0); - tckBusiness.checkServicesBusinessThree(1); - } catch (Exception e) { - e.printStackTrace(); - Assert.fail(e.getMessage()); - } finally { - tckBusinessService.deleteJoePublisherService(authInfoJoe); - tckBusiness.deleteJoePublisherBusiness3(authInfoJoe); - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - } - } - - @Test - public void samsyndicator() { - try { - // For sam's service projection, joe's information must be loaded - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusinessService.saveJoePublisherService(authInfoJoe); - - tckTModel.saveSamSyndicatorTmodel(authInfoSam); - tckBusiness.saveSamSyndicatorBusinessWithProjection(authInfoSam); - tckBusinessService.saveSamSyndicatorService(authInfoSam); - tckBusinessService.deleteSamSyndicatorService(authInfoSam); - } finally { - tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); - tckTModel.deleteSamSyndicatorTmodel(authInfoSam); - - tckBusinessService.deleteJoePublisherService(authInfoJoe); - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - } - } - -} +/* + * Copyright 2001-2009 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.rmi.RemoteException; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.Registry; +import org.apache.juddi.v3.tck.TckBusiness; +import org.apache.juddi.v3.tck.TckBusinessService; +import org.apache.juddi.v3.tck.TckPublisher; +import org.apache.juddi.v3.tck.TckSecurity; +import org.apache.juddi.v3.tck.TckTModel; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.uddi.v3_service.UDDISecurityPortType; + +/** + * @author Jeff Faath + * @author Kurt T Stam + */ +public class API_040_BusinessServiceTest +{ + private static Log logger = LogFactory.getLog(API_040_BusinessServiceTest.class); + + private static API_010_PublisherTest api010 = new API_010_PublisherTest(); + private static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + private static TckBusiness tckBusiness = new TckBusiness(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + private static TckBusinessService tckBusinessService = new TckBusinessService(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + + private static String authInfoJoe = null; + private static String authInfoSam = null; + + @BeforeClass + public static void setup() throws ConfigurationException { + Registry.start(); + logger.info("API_040_BusinessServiceTest"); + logger.debug("Getting auth tokens.."); + + try { + api010.saveJoePublisher(); + api010.saveSamSyndicator(); + UDDISecurityPortType security = new UDDISecurityImpl(); + authInfoJoe = TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); + authInfoSam = TckSecurity.getAuthToken(security, TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword()); + String authInfoUDDI = TckSecurity.getAuthToken(security, TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword()); + tckTModel.saveUDDIPublisherTmodel(authInfoUDDI); + tckTModel.saveTModels(authInfoUDDI, TckTModel.TMODELS_XML); + } catch (RemoteException e) { + logger.error(e.getMessage(), e); + Assert.fail("Could not obtain authInfo token."); + } + } + + @AfterClass + public static void stopRegistry() throws ConfigurationException { + tckTModel.deleteCreatedTModels(authInfoJoe); + Registry.stop(); + } + + @Test + public void joepublisher() { + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusinessService.saveJoePublisherService(authInfoJoe); + tckBusinessService.deleteJoePublisherService(authInfoJoe); + } finally { + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + } + } + + @Test + public void joepublisher2Services() { + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusinessService.saveJoePublisherService(authInfoJoe); + tckBusinessService.saveJoePublisherService2(authInfoJoe); + tckBusinessService.deleteJoePublisherService(authInfoJoe); + tckBusinessService.deleteJoePublisherService2(authInfoJoe); + } finally { + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + } + } + + @Test + public void joepublisher2UpdateBusiness() { + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusinessService.saveJoePublisherService(authInfoJoe); + tckBusinessService.saveJoePublisherService2(authInfoJoe); + tckBusiness.updateJoePublisherBusiness(authInfoJoe); + tckBusinessService.deleteJoePublisherService(authInfoJoe); + tckBusinessService.deleteJoePublisherService2(authInfoJoe); + } finally { + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + } + } + /** + * 5.2.16.3 paragraph 4 + * Data contained within businessEntity structures can be rearranged with + * this API call. This can be done by redefining parent container relationships + * for other registered information. For instance, if a new businessEntity + * is saved with information about a businessService that is registered + * already as part of a different businessEntity, this results in the + * businessService being moved from its current container to the new businessEntity. + * This condition occurs when the businessKey of the businessService being + * saved matches the businessKey of the businessEntity being saved. + * An attempt to delete or move a businessService in this manner by + * a party who is not the publisher of the businessService MUST be + * rejected with an error E_userMismatch. + */ + @Test + public void joepublisherMoveBusinessService() { + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusinessService.saveJoePublisherService(authInfoJoe); + tckBusiness.checkServicesBusinessOne(1); + tckBusiness.saveJoePublisherBusiness3(authInfoJoe); + //check that this business has no services + tckBusiness.checkServicesBusinessThree(0); + //Now move the service from one to three + tckBusiness.saveJoePublisherBusiness1to3(authInfoJoe); + tckBusiness.checkServicesBusinessOne(0); + tckBusiness.checkServicesBusinessThree(1); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail(e.getMessage()); + } finally { + tckBusinessService.deleteJoePublisherService(authInfoJoe); + tckBusiness.deleteJoePublisherBusiness3(authInfoJoe); + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + } + } + + @Test + public void samsyndicator() { + try { + // For sam's service projection, joe's information must be loaded + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusinessService.saveJoePublisherService(authInfoJoe); + + tckTModel.saveSamSyndicatorTmodel(authInfoSam); + tckBusiness.saveSamSyndicatorBusinessWithProjection(authInfoSam); + tckBusinessService.saveSamSyndicatorService(authInfoSam); + tckBusinessService.deleteSamSyndicatorService(authInfoSam); + } finally { + tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); + tckTModel.deleteSamSyndicatorTmodel(authInfoSam); + + tckBusinessService.deleteJoePublisherService(authInfoJoe); + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + } + } + +} diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_050_BindingTemplateTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_050_BindingTemplateTest.java similarity index 98% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/API_050_BindingTemplateTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_050_BindingTemplateTest.java index af6f3af97..007918bf7 100644 --- a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_050_BindingTemplateTest.java +++ b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_050_BindingTemplateTest.java @@ -1,309 +1,309 @@ -/* - * Copyright 2001-2009 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.rmi.RemoteException; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.Registry; -import org.apache.juddi.v3.client.UDDIConstants; -import org.apache.juddi.v3.client.config.UDDIClient; -import org.apache.juddi.v3.client.config.UDDIClientContainer; -import org.apache.juddi.v3.client.ext.wsdm.WSDMQosConstants; -import org.apache.juddi.v3.client.mapping.ServiceLocator; -import org.apache.juddi.v3.client.transport.Transport; -import org.apache.juddi.v3.error.ValueNotAllowedException; -import org.apache.juddi.v3.tck.TckBindingTemplate; -import static org.apache.juddi.v3.tck.TckBindingTemplate.JOE_BINDING_KEY; -import static org.apache.juddi.v3.tck.TckBindingTemplate.JOE_BINDING_XML; -import org.apache.juddi.v3.tck.TckBusiness; -import org.apache.juddi.v3.tck.TckBusinessService; -import org.apache.juddi.v3.tck.TckCommon; -import org.apache.juddi.v3.tck.TckFindEntity; -import org.apache.juddi.v3.tck.TckPublisher; -import org.apache.juddi.v3.tck.TckSecurity; -import org.apache.juddi.v3.tck.TckTModel; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.uddi.api_v3.BindingDetail; -import org.uddi.api_v3.FindBinding; -import org.uddi.api_v3.FindTModel; -import org.uddi.api_v3.IdentifierBag; -import org.uddi.api_v3.KeyedReference; -import org.uddi.api_v3.TModelBag; -import org.uddi.v3_service.UDDIPublicationPortType; -import org.uddi.v3_service.UDDISecurityPortType; - -/** - * @author Jeff Faath - * @author Kurt T Stam - */ -public class API_050_BindingTemplateTest { - - private static Log logger = LogFactory.getLog(API_050_BindingTemplateTest.class); - - private static API_010_PublisherTest api010 = new API_010_PublisherTest(); - private static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - private static TckBusiness tckBusiness = new TckBusiness(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - private static TckBusinessService tckBusinessService = new TckBusinessService(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - private static TckBindingTemplate tckBindingTemplate = new TckBindingTemplate(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - private static TckFindEntity tckFindEntity = new TckFindEntity(new UDDIInquiryImpl()); - - private static String authInfoJoe = null; - - @BeforeClass - public static void setup() throws ConfigurationException { - Registry.start(); - logger.debug("Getting auth token.."); - try { - api010.saveJoePublisher(); - authInfoJoe = TckSecurity.getAuthToken(new UDDISecurityImpl(), TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); - UDDISecurityPortType security = new UDDISecurityImpl(); - String authInfoUDDI = TckSecurity.getAuthToken(security, TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword()); - tckTModel.saveUDDIPublisherTmodel(authInfoUDDI); - tckTModel.saveTModels(authInfoUDDI, TckTModel.TMODELS_XML); - } catch (RemoteException e) { - logger.error(e.getMessage(), e); - Assert.fail("Could not obtain authInfo token."); - } - } - - @AfterClass - public static void stopRegistry() throws ConfigurationException { - Registry.stop(); - } - - @Test - public void joepublisher() throws Exception { - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusinessService.saveJoePublisherService(authInfoJoe); - tckBindingTemplate.saveJoePublisherBinding(authInfoJoe); - tckBindingTemplate.deleteJoePublisherBinding(authInfoJoe); - } finally { - tckBusinessService.deleteJoePublisherService(authInfoJoe); - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - } - } - - @Test - public void testSearchBinding() throws Exception { - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusinessService.saveJoePublisherService(authInfoJoe); - - tckFindEntity.findServiceDetail("uddi:uddi.joepublisher.com:serviceone"); - tckBindingTemplate.deleteBinding(authInfoJoe, "uddi:uddi.joepublisher.com:bindingone"); - String serviceKey = tckFindEntity.findService(null); - tckFindEntity.findServiceDetail(serviceKey); - - tckBindingTemplate.saveJoePublisherBinding(authInfoJoe); - - serviceKey = tckFindEntity.findService(null); - tckFindEntity.findServiceDetail(serviceKey); - - tckBindingTemplate.deleteJoePublisherBinding(authInfoJoe); - - tckFindEntity.findService(null); - tckFindEntity.findServiceDetail(serviceKey); - } finally { - tckBusinessService.deleteJoePublisherService(authInfoJoe); - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - } - } - - /** - * https://issues.apache.org/jira/browse/JUDDI-728 Inquiry NPE on - * find_binding - * - * @throws Exception - */ - @Test - public void testJUDDI_728() throws Exception { - UDDIInquiryImpl inquiry = new UDDIInquiryImpl(); - FindBinding fb = new FindBinding(); - fb.setAuthInfo(authInfoJoe); - org.uddi.api_v3.FindQualifiers fq = new org.uddi.api_v3.FindQualifiers(); - fq.getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); - fb.setFindQualifiers(fq); - fb.setFindTModel(new FindTModel()); - fb.getFindTModel().setIdentifierBag(new IdentifierBag()); - fb.getFindTModel().getIdentifierBag().getKeyedReference().add(new KeyedReference(WSDMQosConstants.METRIC_FAULT_COUNT_KEY, "%", "%")); - inquiry.findBinding(fb); - } - - /** - * https://issues.apache.org/jira/browse/JUDDI-899 findBinding by - * category bag doesn't work - * - * @throws Exception - */ - @Test - public void testJUDDI_899() throws Exception { - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusinessService.saveJoePublisherService(authInfoJoe); - tckBindingTemplate.saveJoePublisherBinding(authInfoJoe); - - UDDIInquiryImpl inquiry = new UDDIInquiryImpl(); - - FindBinding fb = new FindBinding(); - fb.setAuthInfo(authInfoJoe); - - fb.setTModelBag(new TModelBag()); - //this is stored in joe's binding template - fb.getTModelBag().getTModelKey().add("uddi:uddi.org:protocol:serverauthenticatedssl3"); - logger.info("testJUDDI_899 searching..."); - BindingDetail findBinding = inquiry.findBinding(fb); - logger.info("testJUDDI_899 searching complete."); - Assert.assertNotNull(findBinding); - Assert.assertNotNull(findBinding.getBindingTemplate()); - Assert.assertFalse(findBinding.getBindingTemplate().isEmpty()); - - for (int i = 0; i < findBinding.getBindingTemplate().size(); i++) { - if (findBinding.getBindingTemplate().get(i).getBindingKey().equals(TckBindingTemplate.JOE_BINDING_KEY)) { - return; - } - } - - Assert.fail("Binding wasn't returned"); - } finally { - tckBusinessService.deleteJoePublisherService(authInfoJoe); - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - } - /* if (findBinding.isTruncated()==null) { - findBinding.setTruncated(false); - } - //support for paging - while (!findBinding.isTruncated() && !findBinding.getBindingTemplate().isEmpty()) { - - findBinding = inquiry.findBinding(fb); - Assert.assertNotNull(findBinding); - - if (findBinding.isTruncated()) { - findBinding.setTruncated(false); - } - } - - Assert.fail("The expected service wasn't returned");*/ - } - - /** - * https://issues.apache.org/jira/browse/JUDDI-999 - * max length test for tmodel instance info - */ - @Test - public void testJUDDI_999() throws Exception { - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusinessService.saveJoePublisherService(authInfoJoe); - tckBindingTemplate. saveBinding(authInfoJoe, "uddi_data/joepublisher/bindingTemplateMaxLength.xml", JOE_BINDING_KEY); - - } finally { - tckBusinessService.deleteJoePublisherService(authInfoJoe); - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - } - } - - - /** - * https://issues.apache.org/jira/browse/JUDDI-999 - * too long length test for tmodel instance info - */ - - @Test(expected=org.apache.juddi.v3.error.ValueNotAllowedException.class) - public void testJUDDI_999_2() throws Exception { - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusinessService.saveJoePublisherService(authInfoJoe); - tckBindingTemplate.saveBinding(authInfoJoe, "uddi_data/joepublisher/bindingTemplateInvalid.xml", JOE_BINDING_KEY,false); - - } finally { - tckBusinessService.deleteJoePublisherService(authInfoJoe); - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - } - } - - @Test - public void testJuddi937ServiceLocatorWithCache() throws Exception { - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusinessService.saveJoePublisherService(authInfoJoe); - tckBindingTemplate.saveBinding(authInfoJoe, "uddi_data/joepublisher/bindingTemplate.xml", JOE_BINDING_KEY, false); - - //create a client using invm transport - UDDIClientContainer.removeAll(); - UDDIClient.clearServiceLocatorCaches(); - UDDIClient c = new UDDIClient("META-INF/uddi.xml"); - ServiceLocator serviceLocator = c.getServiceLocator("joe"); - serviceLocator.withSimpleCache(); - serviceLocator.clearCaches(); - String lookupEndpoint = serviceLocator.lookupEndpoint(TckBusinessService.JOE_SERVICE_KEY); - String lookupEndpoint2 = serviceLocator.lookupEndpoint(TckBusinessService.JOE_SERVICE_KEY); - System.out.println(TckCommon.DumpAllServices(authInfoJoe, c.getTransport("default").getUDDIInquiryService())); - Assert.assertNotEquals(lookupEndpoint, lookupEndpoint2); - } finally { - tckBusinessService.deleteJoePublisherService(authInfoJoe); - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - } - } - - - - @Test - public void testJuddi937ServiceLocatorWithoutCache() throws Exception { - try { - - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusinessService.saveJoePublisherService(authInfoJoe); - tckBindingTemplate.saveBinding(authInfoJoe, "uddi_data/joepublisher/bindingTemplate.xml", JOE_BINDING_KEY, false); - - //create a client using invm transport - UDDIClientContainer.removeAll(); - UDDIClient.clearServiceLocatorCaches(); - UDDIClient c = new UDDIClient("META-INF/uddi.xml"); - ServiceLocator serviceLocator = c.getServiceLocator("joe"); - serviceLocator.clearCaches(); - //serviceLocator.withSimpleCache(); - String lookupEndpoint = serviceLocator.lookupEndpoint(TckBusinessService.JOE_SERVICE_KEY); - String lookupEndpoint2 = serviceLocator.lookupEndpoint(TckBusinessService.JOE_SERVICE_KEY); - - System.out.println(TckCommon.DumpAllServices(authInfoJoe, c.getTransport("default").getUDDIInquiryService())); - Assert.assertEquals(lookupEndpoint, lookupEndpoint2); - } finally { - tckBusinessService.deleteJoePublisherService(authInfoJoe); - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - } - } -} +/* + * Copyright 2001-2009 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.rmi.RemoteException; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.Registry; +import org.apache.juddi.v3.client.UDDIConstants; +import org.apache.juddi.v3.client.config.UDDIClient; +import org.apache.juddi.v3.client.config.UDDIClientContainer; +import org.apache.juddi.v3.client.ext.wsdm.WSDMQosConstants; +import org.apache.juddi.v3.client.mapping.ServiceLocator; +import org.apache.juddi.v3.client.transport.Transport; +import org.apache.juddi.v3.error.ValueNotAllowedException; +import org.apache.juddi.v3.tck.TckBindingTemplate; +import static org.apache.juddi.v3.tck.TckBindingTemplate.JOE_BINDING_KEY; +import static org.apache.juddi.v3.tck.TckBindingTemplate.JOE_BINDING_XML; +import org.apache.juddi.v3.tck.TckBusiness; +import org.apache.juddi.v3.tck.TckBusinessService; +import org.apache.juddi.v3.tck.TckCommon; +import org.apache.juddi.v3.tck.TckFindEntity; +import org.apache.juddi.v3.tck.TckPublisher; +import org.apache.juddi.v3.tck.TckSecurity; +import org.apache.juddi.v3.tck.TckTModel; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.uddi.api_v3.BindingDetail; +import org.uddi.api_v3.FindBinding; +import org.uddi.api_v3.FindTModel; +import org.uddi.api_v3.IdentifierBag; +import org.uddi.api_v3.KeyedReference; +import org.uddi.api_v3.TModelBag; +import org.uddi.v3_service.UDDIPublicationPortType; +import org.uddi.v3_service.UDDISecurityPortType; + +/** + * @author Jeff Faath + * @author Kurt T Stam + */ +public class API_050_BindingTemplateTest { + + private static Log logger = LogFactory.getLog(API_050_BindingTemplateTest.class); + + private static API_010_PublisherTest api010 = new API_010_PublisherTest(); + private static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + private static TckBusiness tckBusiness = new TckBusiness(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + private static TckBusinessService tckBusinessService = new TckBusinessService(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + private static TckBindingTemplate tckBindingTemplate = new TckBindingTemplate(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + private static TckFindEntity tckFindEntity = new TckFindEntity(new UDDIInquiryImpl()); + + private static String authInfoJoe = null; + + @BeforeClass + public static void setup() throws ConfigurationException { + Registry.start(); + logger.debug("Getting auth token.."); + try { + api010.saveJoePublisher(); + authInfoJoe = TckSecurity.getAuthToken(new UDDISecurityImpl(), TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); + UDDISecurityPortType security = new UDDISecurityImpl(); + String authInfoUDDI = TckSecurity.getAuthToken(security, TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword()); + tckTModel.saveUDDIPublisherTmodel(authInfoUDDI); + tckTModel.saveTModels(authInfoUDDI, TckTModel.TMODELS_XML); + } catch (RemoteException e) { + logger.error(e.getMessage(), e); + Assert.fail("Could not obtain authInfo token."); + } + } + + @AfterClass + public static void stopRegistry() throws ConfigurationException { + Registry.stop(); + } + + @Test + public void joepublisher() throws Exception { + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusinessService.saveJoePublisherService(authInfoJoe); + tckBindingTemplate.saveJoePublisherBinding(authInfoJoe); + tckBindingTemplate.deleteJoePublisherBinding(authInfoJoe); + } finally { + tckBusinessService.deleteJoePublisherService(authInfoJoe); + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + } + } + + @Test + public void testSearchBinding() throws Exception { + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusinessService.saveJoePublisherService(authInfoJoe); + + tckFindEntity.findServiceDetail("uddi:uddi.joepublisher.com:serviceone"); + tckBindingTemplate.deleteBinding(authInfoJoe, "uddi:uddi.joepublisher.com:bindingone"); + String serviceKey = tckFindEntity.findService(null); + tckFindEntity.findServiceDetail(serviceKey); + + tckBindingTemplate.saveJoePublisherBinding(authInfoJoe); + + serviceKey = tckFindEntity.findService(null); + tckFindEntity.findServiceDetail(serviceKey); + + tckBindingTemplate.deleteJoePublisherBinding(authInfoJoe); + + tckFindEntity.findService(null); + tckFindEntity.findServiceDetail(serviceKey); + } finally { + tckBusinessService.deleteJoePublisherService(authInfoJoe); + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + } + } + + /** + * https://issues.apache.org/jira/browse/JUDDI-728 Inquiry NPE on + * find_binding + * + * @throws Exception + */ + @Test + public void testJUDDI_728() throws Exception { + UDDIInquiryImpl inquiry = new UDDIInquiryImpl(); + FindBinding fb = new FindBinding(); + fb.setAuthInfo(authInfoJoe); + org.uddi.api_v3.FindQualifiers fq = new org.uddi.api_v3.FindQualifiers(); + fq.getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); + fb.setFindQualifiers(fq); + fb.setFindTModel(new FindTModel()); + fb.getFindTModel().setIdentifierBag(new IdentifierBag()); + fb.getFindTModel().getIdentifierBag().getKeyedReference().add(new KeyedReference(WSDMQosConstants.METRIC_FAULT_COUNT_KEY, "%", "%")); + inquiry.findBinding(fb); + } + + /** + * https://issues.apache.org/jira/browse/JUDDI-899 findBinding by + * category bag doesn't work + * + * @throws Exception + */ + @Test + public void testJUDDI_899() throws Exception { + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusinessService.saveJoePublisherService(authInfoJoe); + tckBindingTemplate.saveJoePublisherBinding(authInfoJoe); + + UDDIInquiryImpl inquiry = new UDDIInquiryImpl(); + + FindBinding fb = new FindBinding(); + fb.setAuthInfo(authInfoJoe); + + fb.setTModelBag(new TModelBag()); + //this is stored in joe's binding template + fb.getTModelBag().getTModelKey().add("uddi:uddi.org:protocol:serverauthenticatedssl3"); + logger.info("testJUDDI_899 searching..."); + BindingDetail findBinding = inquiry.findBinding(fb); + logger.info("testJUDDI_899 searching complete."); + Assert.assertNotNull(findBinding); + Assert.assertNotNull(findBinding.getBindingTemplate()); + Assert.assertFalse(findBinding.getBindingTemplate().isEmpty()); + + for (int i = 0; i < findBinding.getBindingTemplate().size(); i++) { + if (findBinding.getBindingTemplate().get(i).getBindingKey().equals(TckBindingTemplate.JOE_BINDING_KEY)) { + return; + } + } + + Assert.fail("Binding wasn't returned"); + } finally { + tckBusinessService.deleteJoePublisherService(authInfoJoe); + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + } + /* if (findBinding.isTruncated()==null) { + findBinding.setTruncated(false); + } + //support for paging + while (!findBinding.isTruncated() && !findBinding.getBindingTemplate().isEmpty()) { + + findBinding = inquiry.findBinding(fb); + Assert.assertNotNull(findBinding); + + if (findBinding.isTruncated()) { + findBinding.setTruncated(false); + } + } + + Assert.fail("The expected service wasn't returned");*/ + } + + /** + * https://issues.apache.org/jira/browse/JUDDI-999 + * max length test for tmodel instance info + */ + @Test + public void testJUDDI_999() throws Exception { + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusinessService.saveJoePublisherService(authInfoJoe); + tckBindingTemplate. saveBinding(authInfoJoe, "uddi_data/joepublisher/bindingTemplateMaxLength.xml", JOE_BINDING_KEY); + + } finally { + tckBusinessService.deleteJoePublisherService(authInfoJoe); + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + } + } + + + /** + * https://issues.apache.org/jira/browse/JUDDI-999 + * too long length test for tmodel instance info + */ + + @Test(expected=org.apache.juddi.v3.error.ValueNotAllowedException.class) + public void testJUDDI_999_2() throws Exception { + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusinessService.saveJoePublisherService(authInfoJoe); + tckBindingTemplate.saveBinding(authInfoJoe, "uddi_data/joepublisher/bindingTemplateInvalid.xml", JOE_BINDING_KEY,false); + + } finally { + tckBusinessService.deleteJoePublisherService(authInfoJoe); + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + } + } + + @Test + public void testJuddi937ServiceLocatorWithCache() throws Exception { + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusinessService.saveJoePublisherService(authInfoJoe); + tckBindingTemplate.saveBinding(authInfoJoe, "uddi_data/joepublisher/bindingTemplate.xml", JOE_BINDING_KEY, false); + + //create a client using invm transport + UDDIClientContainer.removeAll(); + UDDIClient.clearServiceLocatorCaches(); + UDDIClient c = new UDDIClient("META-INF/uddi.xml"); + ServiceLocator serviceLocator = c.getServiceLocator("joe"); + serviceLocator.withSimpleCache(); + serviceLocator.clearCaches(); + String lookupEndpoint = serviceLocator.lookupEndpoint(TckBusinessService.JOE_SERVICE_KEY); + String lookupEndpoint2 = serviceLocator.lookupEndpoint(TckBusinessService.JOE_SERVICE_KEY); + System.out.println(TckCommon.DumpAllServices(authInfoJoe, c.getTransport("default").getUDDIInquiryService())); + Assert.assertNotEquals(lookupEndpoint, lookupEndpoint2); + } finally { + tckBusinessService.deleteJoePublisherService(authInfoJoe); + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + } + } + + + + @Test + public void testJuddi937ServiceLocatorWithoutCache() throws Exception { + try { + + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusinessService.saveJoePublisherService(authInfoJoe); + tckBindingTemplate.saveBinding(authInfoJoe, "uddi_data/joepublisher/bindingTemplate.xml", JOE_BINDING_KEY, false); + + //create a client using invm transport + UDDIClientContainer.removeAll(); + UDDIClient.clearServiceLocatorCaches(); + UDDIClient c = new UDDIClient("META-INF/uddi.xml"); + ServiceLocator serviceLocator = c.getServiceLocator("joe"); + serviceLocator.clearCaches(); + //serviceLocator.withSimpleCache(); + String lookupEndpoint = serviceLocator.lookupEndpoint(TckBusinessService.JOE_SERVICE_KEY); + String lookupEndpoint2 = serviceLocator.lookupEndpoint(TckBusinessService.JOE_SERVICE_KEY); + + System.out.println(TckCommon.DumpAllServices(authInfoJoe, c.getTransport("default").getUDDIInquiryService())); + Assert.assertEquals(lookupEndpoint, lookupEndpoint2); + } finally { + tckBusinessService.deleteJoePublisherService(authInfoJoe); + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + } + } +} diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_051_BindingTemplateWSDLTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_051_BindingTemplateWSDLTest.java similarity index 97% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/API_051_BindingTemplateWSDLTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_051_BindingTemplateWSDLTest.java index 851263e95..c417eeeab 100644 --- a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_051_BindingTemplateWSDLTest.java +++ b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_051_BindingTemplateWSDLTest.java @@ -1,144 +1,144 @@ -/* - * Copyright 2001-2009 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.net.MalformedURLException; -import java.rmi.RemoteException; -import java.util.Properties; - -import javax.wsdl.Definition; -import javax.wsdl.WSDLException; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.Registry; -import org.apache.juddi.jaxb.PrintUDDI; -import org.apache.juddi.v3.client.config.UDDIClerk; -import org.apache.juddi.v3.client.config.UDDIClient; -import org.apache.juddi.v3.client.mapping.URLLocalizer; -import org.apache.juddi.v3.client.mapping.URLLocalizerDefaultImpl; -import org.apache.juddi.v3.client.mapping.wsdl.ReadWSDL; -import org.apache.juddi.v3.client.mapping.wsdl.WSDL2UDDI; -import org.apache.juddi.v3.client.transport.TransportException; -import org.apache.juddi.v3.tck.TckBusiness; -import org.apache.juddi.v3.tck.TckPublisher; -import org.apache.juddi.v3.tck.TckSecurity; -import org.apache.juddi.v3.tck.TckTModel; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.uddi.api_v3.FindTModel; -import org.uddi.v3_service.UDDISecurityPortType; - -/** - * @author Jeff Faath - * @author Kurt T Stam - */ -public class API_051_BindingTemplateWSDLTest -{ - private static Log logger = LogFactory.getLog(API_051_BindingTemplateWSDLTest.class); - - private static API_010_PublisherTest api010 = new API_010_PublisherTest(); - private static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - private static TckBusiness tckBusiness = new TckBusiness(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - - private static String authInfoJoe = null; - - @BeforeClass - public static void setup() throws ConfigurationException { - Registry.start(); - logger.info("API_051_BindingTemplateWSDLTest"); - logger.debug("Getting auth token.."); - try { - api010.saveJoePublisher(); - authInfoJoe = TckSecurity.getAuthToken(new UDDISecurityImpl(), TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); - UDDISecurityPortType security = new UDDISecurityImpl(); - String authInfoUDDI = TckSecurity.getAuthToken(security, TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword()); - tckTModel.saveUDDIPublisherTmodel(authInfoUDDI); - tckTModel.saveTModels(authInfoUDDI, TckTModel.TMODELS_XML); - } catch (RemoteException e) { - logger.error(e.getMessage(), e); - Assert.fail("Could not obtain authInfo token."); - } - } - - @AfterClass - public static void stopRegistry() throws ConfigurationException { - tckTModel.deleteCreatedTModels(authInfoJoe); - Registry.stop(); - } - - @Test - public void testDirectCall() throws ConfigurationException, WSDLException, RemoteException, TransportException, MalformedURLException, Exception { - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - - UDDIClerk clerk = new UDDIClient("META-INF/uddi.xml").getClerk("joe"); - Properties properties = clerk.getUDDINode().getProperties(); - URLLocalizer urlLocalizer = new URLLocalizerDefaultImpl(); - - //get the wsdl - Definition wsdlDefinition = new ReadWSDL().readWSDL("wsdl/sample.wsdl"); - //set required properties - properties.put("keyDomain", "uddi.joepublisher.com"); - properties.put(org.apache.juddi.v3.client.config.Property.BUSINESS_KEY, "uddi:uddi.joepublisher.com:businessone"); - properties.put("nodeName", "api.example.org_80"); - WSDL2UDDI wsdl2UDDI = new WSDL2UDDI(clerk, urlLocalizer, properties); - //register all services in the wsdl - wsdl2UDDI.registerBusinessServices(wsdlDefinition); - //done - - String portTypeName = "StockQuotePortType"; - String namespace = "http://example.com/stockquote/"; - FindTModel findTModelForPortType = WSDL2UDDI.createFindPortTypeTModelForPortType(portTypeName, namespace); - System.out.println(new PrintUDDI().print(findTModelForPortType)); - - wsdl2UDDI.unRegisterBusinessServices(wsdlDefinition); - } finally { - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - } - } - - @Test - public void testClerkCall() throws ConfigurationException, WSDLException, RemoteException, TransportException, MalformedURLException { - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - - UDDIClerk clerk = new UDDIClient("META-INF/uddi.xml").getClerk("joe"); - clerk.registerWsdls(); - - - String portTypeName = "StockQuotePortType"; - String namespace = "http://example.com/stockquote/"; - FindTModel findTModelForPortType = WSDL2UDDI.createFindPortTypeTModelForPortType(portTypeName, namespace); - System.out.println(new PrintUDDI().print(findTModelForPortType)); - - clerk.unRegisterWsdls(); - } catch (Exception e) { - e.printStackTrace(); - Assert.fail(); - } finally { - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - } - } - - -} +/* + * Copyright 2001-2009 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.net.MalformedURLException; +import java.rmi.RemoteException; +import java.util.Properties; + +import javax.wsdl.Definition; +import javax.wsdl.WSDLException; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.Registry; +import org.apache.juddi.jaxb.PrintUDDI; +import org.apache.juddi.v3.client.config.UDDIClerk; +import org.apache.juddi.v3.client.config.UDDIClient; +import org.apache.juddi.v3.client.mapping.URLLocalizer; +import org.apache.juddi.v3.client.mapping.URLLocalizerDefaultImpl; +import org.apache.juddi.v3.client.mapping.wsdl.ReadWSDL; +import org.apache.juddi.v3.client.mapping.wsdl.WSDL2UDDI; +import org.apache.juddi.v3.client.transport.TransportException; +import org.apache.juddi.v3.tck.TckBusiness; +import org.apache.juddi.v3.tck.TckPublisher; +import org.apache.juddi.v3.tck.TckSecurity; +import org.apache.juddi.v3.tck.TckTModel; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.uddi.api_v3.FindTModel; +import org.uddi.v3_service.UDDISecurityPortType; + +/** + * @author Jeff Faath + * @author Kurt T Stam + */ +public class API_051_BindingTemplateWSDLTest +{ + private static Log logger = LogFactory.getLog(API_051_BindingTemplateWSDLTest.class); + + private static API_010_PublisherTest api010 = new API_010_PublisherTest(); + private static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + private static TckBusiness tckBusiness = new TckBusiness(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + + private static String authInfoJoe = null; + + @BeforeClass + public static void setup() throws ConfigurationException { + Registry.start(); + logger.info("API_051_BindingTemplateWSDLTest"); + logger.debug("Getting auth token.."); + try { + api010.saveJoePublisher(); + authInfoJoe = TckSecurity.getAuthToken(new UDDISecurityImpl(), TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); + UDDISecurityPortType security = new UDDISecurityImpl(); + String authInfoUDDI = TckSecurity.getAuthToken(security, TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword()); + tckTModel.saveUDDIPublisherTmodel(authInfoUDDI); + tckTModel.saveTModels(authInfoUDDI, TckTModel.TMODELS_XML); + } catch (RemoteException e) { + logger.error(e.getMessage(), e); + Assert.fail("Could not obtain authInfo token."); + } + } + + @AfterClass + public static void stopRegistry() throws ConfigurationException { + tckTModel.deleteCreatedTModels(authInfoJoe); + Registry.stop(); + } + + @Test + public void testDirectCall() throws ConfigurationException, WSDLException, RemoteException, TransportException, MalformedURLException, Exception { + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + + UDDIClerk clerk = new UDDIClient("META-INF/uddi.xml").getClerk("joe"); + Properties properties = clerk.getUDDINode().getProperties(); + URLLocalizer urlLocalizer = new URLLocalizerDefaultImpl(); + + //get the wsdl + Definition wsdlDefinition = new ReadWSDL().readWSDL("wsdl/sample.wsdl"); + //set required properties + properties.put("keyDomain", "uddi.joepublisher.com"); + properties.put(org.apache.juddi.v3.client.config.Property.BUSINESS_KEY, "uddi:uddi.joepublisher.com:businessone"); + properties.put("nodeName", "api.example.org_80"); + WSDL2UDDI wsdl2UDDI = new WSDL2UDDI(clerk, urlLocalizer, properties); + //register all services in the wsdl + wsdl2UDDI.registerBusinessServices(wsdlDefinition); + //done + + String portTypeName = "StockQuotePortType"; + String namespace = "http://example.com/stockquote/"; + FindTModel findTModelForPortType = WSDL2UDDI.createFindPortTypeTModelForPortType(portTypeName, namespace); + System.out.println(new PrintUDDI().print(findTModelForPortType)); + + wsdl2UDDI.unRegisterBusinessServices(wsdlDefinition); + } finally { + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + } + } + + @Test + public void testClerkCall() throws ConfigurationException, WSDLException, RemoteException, TransportException, MalformedURLException { + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + + UDDIClerk clerk = new UDDIClient("META-INF/uddi.xml").getClerk("joe"); + clerk.registerWsdls(); + + + String portTypeName = "StockQuotePortType"; + String namespace = "http://example.com/stockquote/"; + FindTModel findTModelForPortType = WSDL2UDDI.createFindPortTypeTModelForPortType(portTypeName, namespace); + System.out.println(new PrintUDDI().print(findTModelForPortType)); + + clerk.unRegisterWsdls(); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail(); + } finally { + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + } + } + + +} diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_060_PublisherAssertionTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_060_PublisherAssertionTest.java similarity index 98% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/API_060_PublisherAssertionTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_060_PublisherAssertionTest.java index c9fcb9d1a..6753acd0c 100644 --- a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_060_PublisherAssertionTest.java +++ b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_060_PublisherAssertionTest.java @@ -1,507 +1,507 @@ -/* - * Copyright 2001-2009 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -/** - * @author Jeff Faath - * @author Kurt T Stam - * @author Alex O'Ree - */ -import java.rmi.RemoteException; -import java.security.cert.CertificateException; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicReference; -import javax.xml.bind.JAXB; -import javax.xml.ws.Holder; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.Registry; -import org.apache.juddi.jaxb.EntityCreator; -import org.apache.juddi.v3.client.UDDIConstants; -import org.apache.juddi.v3.client.cryptor.DigSigUtil; -import org.apache.juddi.v3.tck.TckBusiness; -import org.apache.juddi.v3.tck.TckCommon; -import org.apache.juddi.v3.tck.TckFindEntity; -import org.apache.juddi.v3.tck.TckPublisher; -import org.apache.juddi.v3.tck.TckPublisherAssertion; -import org.apache.juddi.v3.tck.TckSecurity; -import org.apache.juddi.v3.tck.TckTModel; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.uddi.api_v3.AddPublisherAssertions; -import org.uddi.api_v3.AssertionStatusItem; -import org.uddi.api_v3.CompletionStatus; -import org.uddi.api_v3.DeletePublisherAssertions; -import org.uddi.api_v3.KeyedReference; -import org.uddi.api_v3.PublisherAssertion; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.v3_service.UDDISecurityPortType; - -public class API_060_PublisherAssertionTest { - - private static Log logger = LogFactory.getLog(API_060_PublisherAssertionTest.class); - - private static API_010_PublisherTest api010 = new API_010_PublisherTest(); - private static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - private static TckBusiness tckBusiness = new TckBusiness(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - private static TckPublisherAssertion tckAssertion = new TckPublisherAssertion(new UDDIPublicationImpl()); - private static TckFindEntity tckFindEntity = new TckFindEntity(new UDDIInquiryImpl()); - private static String authInfoJoe = null; - private static String authInfoSam = null; - private static String authInfoMary = null; - private static UDDIPublicationImpl pub = new UDDIPublicationImpl(); - - @BeforeClass - public static void setup() throws Exception { - Registry.start(); - logger.debug("Getting auth token.."); - try { - api010.saveJoePublisher(); - api010.saveSamSyndicator(); - UDDISecurityPortType security = new UDDISecurityImpl(); - authInfoJoe = TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); - authInfoSam = TckSecurity.getAuthToken(security, TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword()); - authInfoMary = TckSecurity.getAuthToken(security, TckPublisher.getMaryPublisherId(), TckPublisher.getMaryPassword()); - TckCommon.DumpAllTModelsOpInfo(authInfoJoe, new UDDIInquiryImpl()); - String root = TckSecurity.getAuthToken(security, TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword()); - tckTModel.saveUDDIPublisherTmodel(root); - tckTModel.saveTmodels(root); - } catch (RemoteException e) { - System.out.println("the test failed, dumping ownership information for all tmodels...."); - - logger.error(e.getMessage(), e); - Assert.fail("Could not obtain authInfo token." + e.getMessage()); - } - } - - @AfterClass - public static void stopRegistry() throws ConfigurationException { - Registry.stop(); - } - - @Test - public void testJoepublisherToSamSyndicator() { - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckTModel.saveSamSyndicatorTmodel(authInfoSam); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusiness.saveSamSyndicatorBusiness(authInfoSam); - tckAssertion.saveJoePublisherPublisherAssertion(authInfoJoe); - tckAssertion.deleteJoePublisherPublisherAssertion(authInfoJoe); - } finally { - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - tckTModel.deleteSamSyndicatorTmodel(authInfoSam); - } - } - - /** - * This test should find no publisher assertions because we only save - * them from the joe publisher side. - */ - @Test - public void testFindNoAssertions() { - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckTModel.saveSamSyndicatorTmodel(authInfoSam); - tckTModel.saveMaryPublisherTmodel(authInfoMary); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusiness.saveSamSyndicatorBusiness(authInfoSam); - tckBusiness.saveMaryPublisherBusiness(authInfoMary); - tckAssertion.saveJoePublisherPublisherAssertion(authInfoJoe); - tckAssertion.saveJoePublisherPublisherAssertion2(authInfoJoe); - - tckFindEntity.findRelatedBusiness_sortByName(true); - tckFindEntity.findRelatedBusinessToKey(true); - tckFindEntity.findRelatedBusinessFromKey(true); - - tckAssertion.deleteJoePublisherPublisherAssertion(authInfoJoe); - tckAssertion.deleteJoePublisherPublisherAssertion2(authInfoJoe); - } finally { - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckBusiness.deleteMaryPublisherBusiness(authInfoMary); - tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - tckTModel.deleteSamSyndicatorTmodel(authInfoSam); - tckTModel.deleteMaryPublisherTmodel(authInfoMary); - } - } - - /** - * This test should find 2 publisher assertions. - */ - @Test - public void testFindAssertions() { - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckTModel.saveSamSyndicatorTmodel(authInfoSam); - tckTModel.saveMaryPublisherTmodel(authInfoMary); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusiness.saveSamSyndicatorBusiness(authInfoSam); - tckBusiness.saveMaryPublisherBusiness(authInfoMary); - tckAssertion.saveJoePublisherPublisherAssertion(authInfoJoe); - tckAssertion.saveJoePublisherPublisherAssertion2(authInfoJoe); - tckAssertion.saveSamPublisherPublisherAssertion(authInfoSam); - tckAssertion.saveMaryPublisherPublisherAssertion(authInfoMary); - - tckFindEntity.findRelatedBusiness_sortByName(false); - tckFindEntity.findRelatedBusinessToKey(false); - tckFindEntity.findRelatedBusinessFromKey(false); - - tckAssertion.deleteJoePublisherPublisherAssertion(authInfoJoe); - tckAssertion.deleteJoePublisherPublisherAssertion2(authInfoJoe); - - } finally { - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckBusiness.deleteMaryPublisherBusiness(authInfoMary); - tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - tckTModel.deleteSamSyndicatorTmodel(authInfoSam); - tckTModel.deleteMaryPublisherTmodel(authInfoMary); - } - } - - /** - * covers - * JUDDI-908 - * - * @throws Exception - */ - @Test(expected = DispositionReportFaultMessage.class) - public void deleteAssertionNonowner() throws Exception { - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckTModel.saveSamSyndicatorTmodel(authInfoSam); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusiness.saveSamSyndicatorBusiness(authInfoSam); - tckAssertion.saveJoePublisherPublisherAssertion(authInfoJoe); - - DeletePublisherAssertions dp = new DeletePublisherAssertions(); - dp.setAuthInfo(authInfoMary); - - PublisherAssertion paIn = (PublisherAssertion) EntityCreator.buildFromDoc(TckPublisherAssertion.JOE_ASSERT_XML, "org.uddi.api_v3"); - dp.getPublisherAssertion().add(paIn); - - new UDDIPublicationImpl().deletePublisherAssertions(dp); - // - } finally { - tckAssertion.deleteJoePublisherPublisherAssertion(authInfoJoe); - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - tckTModel.deleteSamSyndicatorTmodel(authInfoSam); - } - } - - @Test - public void testSetPublisherAssertions() throws Exception { - //create 1/2 PA - - //use Set with no inputs - //confirm all are deleted - try { - - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckTModel.saveSamSyndicatorTmodel(authInfoSam); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusiness.saveSamSyndicatorBusiness(authInfoSam); - Holder> x = new Holder>(); - x.value = new ArrayList(); - logger.info("Clearing all Joe's publisher assertions...."); - pub.setPublisherAssertions(authInfoJoe, x); - - logger.info("Clearing all Sam's publisher assertions...."); - pub.setPublisherAssertions(authInfoSam, x); - - logger.info("Confirming we're clear"); - List before = pub.getPublisherAssertions(authInfoJoe); - Assert.assertNotNull(before); - Assert.assertTrue(before.isEmpty()); - System.out.println(before.size()); - for (int i = 0; i < before.size(); i++) { - JAXB.marshal(before.get(i), System.out); - } - - before = pub.getPublisherAssertions(authInfoSam); - Assert.assertNotNull(before); - Assert.assertTrue(before.isEmpty()); - System.out.println(before.size()); - for (int i = 0; i < before.size(); i++) { - JAXB.marshal(before.get(i), System.out); - } - - List assertionStatusReport = pub.getAssertionStatusReport(authInfoJoe, null); - Assert.assertTrue(assertionStatusReport.isEmpty()); - - assertionStatusReport = pub.getAssertionStatusReport(authInfoSam, null); - Assert.assertTrue(assertionStatusReport.isEmpty()); - - logger.info("Saving 1/2 publisher assertion...."); - List onehalfPA = tckAssertion.saveJoePublisherPublisherAssertion(authInfoJoe); - - before = pub.getPublisherAssertions(authInfoJoe); - Assert.assertNotNull(before); - Assert.assertFalse(before.isEmpty()); - System.out.println(before.size()); - for (int i = 0; i < before.size(); i++) { - JAXB.marshal(before.get(i), System.out); - } - //PublisherAssertion paIn = (PublisherAssertion)EntityCreator.buildFromDoc(TckPublisherAssertion.JOE_ASSERT_XML, "org.uddi.api_v3"); - //dp.getPublisherAssertion().add(paIn); - x = new Holder>(); - x.value = new ArrayList(); - logger.info("Clearing all publisher assertions...."); - pub.setPublisherAssertions(authInfoJoe, x); - System.out.println(x.value.size()); - for (int i = 0; i < x.value.size(); i++) { - JAXB.marshal(x.value.get(i), System.out); - } - - logger.info("Fetch all publisher assertions....there should be none"); - List publisherAssertions = pub.getPublisherAssertions(authInfoJoe); - System.out.println(publisherAssertions.size()); - for (int i = 0; i < publisherAssertions.size(); i++) { - JAXB.marshal(publisherAssertions.get(i), System.out); - } - Assert.assertNotNull(publisherAssertions); - Assert.assertTrue(publisherAssertions.isEmpty()); - // - } finally { - //tckAssertion.deleteJoePublisherPublisherAssertion(authInfoJoe); - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - tckTModel.deleteSamSyndicatorTmodel(authInfoSam); - } - } - - @Test - public void testSetPublisherAssertions2() throws Exception { - //create 1/2 PA - - //use Set with the same 1/2 PA - //confirm still present - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckTModel.saveSamSyndicatorTmodel(authInfoSam); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusiness.saveSamSyndicatorBusiness(authInfoSam); - List onehalfPA = tckAssertion.saveJoePublisherPublisherAssertion(authInfoJoe); - - List before = pub.getPublisherAssertions(authInfoJoe); - Assert.assertNotNull(before); - Assert.assertFalse(before.isEmpty()); - - pub.setPublisherAssertions(authInfoJoe, new Holder>(onehalfPA)); - List publisherAssertions = pub.getPublisherAssertions(authInfoJoe); - Assert.assertNotNull(publisherAssertions); - Assert.assertFalse(publisherAssertions.isEmpty()); - // - } finally { - //tckAssertion.deleteJoePublisherPublisherAssertion(authInfoJoe); - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - tckTModel.deleteSamSyndicatorTmodel(authInfoSam); - } - } - - @Test - public void testSetPublisherAssertions3() throws Exception { - //create 1/2 PA - //use Set with a new PA - //confirm first PA is gone and the new PA exists - try { - - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckTModel.saveSamSyndicatorTmodel(authInfoSam); - tckTModel.saveMaryPublisherTmodel(authInfoMary); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusiness.saveSamSyndicatorBusiness(authInfoSam); - tckBusiness.saveMaryPublisherBusiness(authInfoMary); - Holder> x = new Holder>(); - x.value = new ArrayList(); - logger.info("Clearing all Joe's publisher assertions...."); - pub.setPublisherAssertions(authInfoJoe, x); - - logger.info("Clearing all Sam's publisher assertions...."); - pub.setPublisherAssertions(authInfoSam, x); - - logger.info("Clearing all Mary's publisher assertions...."); - pub.setPublisherAssertions(authInfoMary, x); - - logger.info("Confirming we're clear"); - List before = pub.getPublisherAssertions(authInfoJoe); - Assert.assertNotNull(before); - - System.out.println(before.size()); - for (int i = 0; i < before.size(); i++) { - JAXB.marshal(before.get(i), System.out); - } - Assert.assertTrue(before.isEmpty()); - - before = pub.getPublisherAssertions(authInfoSam); - Assert.assertNotNull(before); - - System.out.println(before.size()); - for (int i = 0; i < before.size(); i++) { - JAXB.marshal(before.get(i), System.out); - } - Assert.assertTrue(before.isEmpty()); - - before = pub.getPublisherAssertions(authInfoMary); - Assert.assertNotNull(before); - - System.out.println(before.size()); - for (int i = 0; i < before.size(); i++) { - JAXB.marshal(before.get(i), System.out); - } - Assert.assertTrue(before.isEmpty()); - - List assertionStatusReport = pub.getAssertionStatusReport(authInfoJoe, null); - Assert.assertTrue(assertionStatusReport.isEmpty()); - - assertionStatusReport = pub.getAssertionStatusReport(authInfoSam, null); - Assert.assertTrue(assertionStatusReport.isEmpty()); - - assertionStatusReport = pub.getAssertionStatusReport(authInfoMary, null); - Assert.assertTrue(assertionStatusReport.isEmpty()); - - logger.info("Saving 1/2 publisher assertion...."); - List onehalfPA = tckAssertion.saveJoePublisherPublisherAssertion(authInfoJoe); - - before = pub.getPublisherAssertions(authInfoJoe); - Assert.assertNotNull(before); - Assert.assertFalse(before.isEmpty()); - System.out.println(before.size()); - for (int i = 0; i < before.size(); i++) { - JAXB.marshal(before.get(i), System.out); - } - //PublisherAssertion paIn = (PublisherAssertion)EntityCreator.buildFromDoc(TckPublisherAssertion.JOE_ASSERT_XML, "org.uddi.api_v3"); - //dp.getPublisherAssertion().add(paIn); - x = new Holder>(); - x.value = new ArrayList(); - PublisherAssertion pa = new PublisherAssertion(); - - pa.setFromKey(TckBusiness.JOE_BUSINESS_KEY); - pa.setToKey(TckBusiness.MARY_BUSINESS_KEY); - pa.setKeyedReference(new KeyedReference(UDDIConstants.RELATIONSHIPS, "parent-child", "child")); - - x.value.add(pa); - logger.info("Using set to clear existing and add a new publisher assertion...."); - pub.setPublisherAssertions(authInfoJoe, x); - System.out.println(x.value.size()); - for (int i = 0; i < x.value.size(); i++) { - JAXB.marshal(x.value.get(i), System.out); - } - - logger.info("Fetch all publisher assertions....there should be 1"); - List publisherAssertions = pub.getPublisherAssertions(authInfoJoe); - System.out.println(publisherAssertions.size()); - for (int i = 0; i < publisherAssertions.size(); i++) { - JAXB.marshal(publisherAssertions.get(i), System.out); - } - Assert.assertEquals(publisherAssertions.get(0).getFromKey(), pa.getFromKey()); - Assert.assertEquals(publisherAssertions.get(0).getToKey(), pa.getToKey()); - Assert.assertEquals(publisherAssertions.get(0).getKeyedReference().getKeyName(), pa.getKeyedReference().getKeyName()); - Assert.assertEquals(publisherAssertions.get(0).getKeyedReference().getKeyValue(), pa.getKeyedReference().getKeyValue()); - Assert.assertEquals(publisherAssertions.get(0).getKeyedReference().getTModelKey(), pa.getKeyedReference().getTModelKey()); - - // - } finally { - //tckAssertion.deleteJoePublisherPublisherAssertion(authInfoJoe); - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); - tckBusiness.deleteMaryPublisherBusiness(authInfoMary); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - tckTModel.deleteSamSyndicatorTmodel(authInfoSam); - tckTModel.deleteMaryPublisherTmodel(authInfoMary); - } - - } - DigSigUtil ds; - - void SetCertStoreSettigns() { - ds.put(DigSigUtil.SIGNATURE_KEYSTORE_FILE, "./src/test/resources/keystore.jks"); - ds.put(DigSigUtil.SIGNATURE_KEYSTORE_FILETYPE, "JKS"); - ds.put(DigSigUtil.SIGNATURE_KEYSTORE_FILE_PASSWORD, "Test"); - ds.put(DigSigUtil.SIGNATURE_KEYSTORE_KEY_ALIAS, "Test"); - ds.put(DigSigUtil.TRUSTSTORE_FILE, "./src/test/resources/truststore.jks"); - ds.put(DigSigUtil.TRUSTSTORE_FILETYPE, "JKS"); - ds.put(DigSigUtil.TRUSTSTORE_FILE_PASSWORD, "Test"); - } - - void Default() throws CertificateException { - ds = new DigSigUtil(); - SetCertStoreSettigns(); - ds.put(DigSigUtil.SIGNATURE_OPTION_CERT_INCLUSION_BASE64, "true"); - } - - @Test - public void testPublisherAssertionSignatures() throws Exception { - try { - Default(); - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckTModel.saveSamSyndicatorTmodel(authInfoSam); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusiness.saveSamSyndicatorBusiness(authInfoSam); - AddPublisherAssertions ap = new AddPublisherAssertions(); - ap.setAuthInfo(authInfoJoe); - - PublisherAssertion paIn = (PublisherAssertion) EntityCreator.buildFromDoc(TckPublisherAssertion.JOE_ASSERT_XML, "org.uddi.api_v3"); - paIn = ds.signUddiEntity(paIn); - - ap.getPublisherAssertion().add(paIn); - Assert.assertFalse(paIn.getSignature().isEmpty()); - pub.addPublisherAssertions(ap); - - List onehalfPA = tckAssertion.saveJoePublisherPublisherAssertion(authInfoJoe); - - - Assert.assertNotNull(onehalfPA); - Assert.assertFalse(onehalfPA.get(0).getSignature().isEmpty()); - Assert.assertFalse(onehalfPA.isEmpty()); - - Assert.assertNotNull(onehalfPA); - Assert.assertFalse(onehalfPA.get(0).getSignature().isEmpty()); - Assert.assertFalse(onehalfPA.isEmpty()); - Assert.assertEquals(paIn.getSignature().size(),onehalfPA.get(0).getSignature().size()); - Assert.assertEquals(paIn.getSignature().get(0).getId(),onehalfPA.get(0).getSignature().get(0).getId()); - Assert.assertEquals(paIn.getSignature().get(0).getKeyInfo().getId(),onehalfPA.get(0).getSignature().get(0).getKeyInfo().getId()); - Assert.assertEquals(paIn.getSignature().get(0).getKeyInfo().getContent().size(),onehalfPA.get(0).getSignature().get(0).getKeyInfo().getContent().size()); - - Assert.assertEquals(paIn.getSignature().get(0).getSignedInfo().getCanonicalizationMethod().getAlgorithm(),onehalfPA.get(0).getSignature().get(0).getSignedInfo().getCanonicalizationMethod().getAlgorithm()); - Assert.assertEquals(paIn.getSignature().get(0).getSignedInfo().getId(),onehalfPA.get(0).getSignature().get(0).getSignedInfo().getId()); - Assert.assertEquals(paIn.getSignature().get(0).getSignedInfo().getReference().size(),onehalfPA.get(0).getSignature().get(0).getSignedInfo().getReference().size()); - AtomicReference outmsg=new AtomicReference(); - boolean success=ds.verifySignedUddiEntity(onehalfPA.get(0), outmsg); - Assert.assertTrue(outmsg.get(), success); - - // - } finally { - //tckAssertion.deleteJoePublisherPublisherAssertion(authInfoJoe); - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - tckTModel.deleteSamSyndicatorTmodel(authInfoSam); - } - } -} +/* + * Copyright 2001-2009 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +/** + * @author Jeff Faath + * @author Kurt T Stam + * @author Alex O'Ree + */ +import java.rmi.RemoteException; +import java.security.cert.CertificateException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; +import javax.xml.bind.JAXB; +import javax.xml.ws.Holder; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.Registry; +import org.apache.juddi.jaxb.EntityCreator; +import org.apache.juddi.v3.client.UDDIConstants; +import org.apache.juddi.v3.client.cryptor.DigSigUtil; +import org.apache.juddi.v3.tck.TckBusiness; +import org.apache.juddi.v3.tck.TckCommon; +import org.apache.juddi.v3.tck.TckFindEntity; +import org.apache.juddi.v3.tck.TckPublisher; +import org.apache.juddi.v3.tck.TckPublisherAssertion; +import org.apache.juddi.v3.tck.TckSecurity; +import org.apache.juddi.v3.tck.TckTModel; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.uddi.api_v3.AddPublisherAssertions; +import org.uddi.api_v3.AssertionStatusItem; +import org.uddi.api_v3.CompletionStatus; +import org.uddi.api_v3.DeletePublisherAssertions; +import org.uddi.api_v3.KeyedReference; +import org.uddi.api_v3.PublisherAssertion; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.v3_service.UDDISecurityPortType; + +public class API_060_PublisherAssertionTest { + + private static Log logger = LogFactory.getLog(API_060_PublisherAssertionTest.class); + + private static API_010_PublisherTest api010 = new API_010_PublisherTest(); + private static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + private static TckBusiness tckBusiness = new TckBusiness(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + private static TckPublisherAssertion tckAssertion = new TckPublisherAssertion(new UDDIPublicationImpl()); + private static TckFindEntity tckFindEntity = new TckFindEntity(new UDDIInquiryImpl()); + private static String authInfoJoe = null; + private static String authInfoSam = null; + private static String authInfoMary = null; + private static UDDIPublicationImpl pub = new UDDIPublicationImpl(); + + @BeforeClass + public static void setup() throws Exception { + Registry.start(); + logger.debug("Getting auth token.."); + try { + api010.saveJoePublisher(); + api010.saveSamSyndicator(); + UDDISecurityPortType security = new UDDISecurityImpl(); + authInfoJoe = TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); + authInfoSam = TckSecurity.getAuthToken(security, TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword()); + authInfoMary = TckSecurity.getAuthToken(security, TckPublisher.getMaryPublisherId(), TckPublisher.getMaryPassword()); + TckCommon.DumpAllTModelsOpInfo(authInfoJoe, new UDDIInquiryImpl()); + String root = TckSecurity.getAuthToken(security, TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword()); + tckTModel.saveUDDIPublisherTmodel(root); + tckTModel.saveTmodels(root); + } catch (RemoteException e) { + System.out.println("the test failed, dumping ownership information for all tmodels...."); + + logger.error(e.getMessage(), e); + Assert.fail("Could not obtain authInfo token." + e.getMessage()); + } + } + + @AfterClass + public static void stopRegistry() throws ConfigurationException { + Registry.stop(); + } + + @Test + public void testJoepublisherToSamSyndicator() { + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckTModel.saveSamSyndicatorTmodel(authInfoSam); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusiness.saveSamSyndicatorBusiness(authInfoSam); + tckAssertion.saveJoePublisherPublisherAssertion(authInfoJoe); + tckAssertion.deleteJoePublisherPublisherAssertion(authInfoJoe); + } finally { + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + tckTModel.deleteSamSyndicatorTmodel(authInfoSam); + } + } + + /** + * This test should find no publisher assertions because we only save + * them from the joe publisher side. + */ + @Test + public void testFindNoAssertions() { + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckTModel.saveSamSyndicatorTmodel(authInfoSam); + tckTModel.saveMaryPublisherTmodel(authInfoMary); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusiness.saveSamSyndicatorBusiness(authInfoSam); + tckBusiness.saveMaryPublisherBusiness(authInfoMary); + tckAssertion.saveJoePublisherPublisherAssertion(authInfoJoe); + tckAssertion.saveJoePublisherPublisherAssertion2(authInfoJoe); + + tckFindEntity.findRelatedBusiness_sortByName(true); + tckFindEntity.findRelatedBusinessToKey(true); + tckFindEntity.findRelatedBusinessFromKey(true); + + tckAssertion.deleteJoePublisherPublisherAssertion(authInfoJoe); + tckAssertion.deleteJoePublisherPublisherAssertion2(authInfoJoe); + } finally { + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckBusiness.deleteMaryPublisherBusiness(authInfoMary); + tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + tckTModel.deleteSamSyndicatorTmodel(authInfoSam); + tckTModel.deleteMaryPublisherTmodel(authInfoMary); + } + } + + /** + * This test should find 2 publisher assertions. + */ + @Test + public void testFindAssertions() { + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckTModel.saveSamSyndicatorTmodel(authInfoSam); + tckTModel.saveMaryPublisherTmodel(authInfoMary); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusiness.saveSamSyndicatorBusiness(authInfoSam); + tckBusiness.saveMaryPublisherBusiness(authInfoMary); + tckAssertion.saveJoePublisherPublisherAssertion(authInfoJoe); + tckAssertion.saveJoePublisherPublisherAssertion2(authInfoJoe); + tckAssertion.saveSamPublisherPublisherAssertion(authInfoSam); + tckAssertion.saveMaryPublisherPublisherAssertion(authInfoMary); + + tckFindEntity.findRelatedBusiness_sortByName(false); + tckFindEntity.findRelatedBusinessToKey(false); + tckFindEntity.findRelatedBusinessFromKey(false); + + tckAssertion.deleteJoePublisherPublisherAssertion(authInfoJoe); + tckAssertion.deleteJoePublisherPublisherAssertion2(authInfoJoe); + + } finally { + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckBusiness.deleteMaryPublisherBusiness(authInfoMary); + tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + tckTModel.deleteSamSyndicatorTmodel(authInfoSam); + tckTModel.deleteMaryPublisherTmodel(authInfoMary); + } + } + + /** + * covers + * JUDDI-908 + * + * @throws Exception + */ + @Test(expected = DispositionReportFaultMessage.class) + public void deleteAssertionNonowner() throws Exception { + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckTModel.saveSamSyndicatorTmodel(authInfoSam); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusiness.saveSamSyndicatorBusiness(authInfoSam); + tckAssertion.saveJoePublisherPublisherAssertion(authInfoJoe); + + DeletePublisherAssertions dp = new DeletePublisherAssertions(); + dp.setAuthInfo(authInfoMary); + + PublisherAssertion paIn = (PublisherAssertion) EntityCreator.buildFromDoc(TckPublisherAssertion.JOE_ASSERT_XML, "org.uddi.api_v3"); + dp.getPublisherAssertion().add(paIn); + + new UDDIPublicationImpl().deletePublisherAssertions(dp); + // + } finally { + tckAssertion.deleteJoePublisherPublisherAssertion(authInfoJoe); + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + tckTModel.deleteSamSyndicatorTmodel(authInfoSam); + } + } + + @Test + public void testSetPublisherAssertions() throws Exception { + //create 1/2 PA + + //use Set with no inputs + //confirm all are deleted + try { + + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckTModel.saveSamSyndicatorTmodel(authInfoSam); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusiness.saveSamSyndicatorBusiness(authInfoSam); + Holder> x = new Holder>(); + x.value = new ArrayList(); + logger.info("Clearing all Joe's publisher assertions...."); + pub.setPublisherAssertions(authInfoJoe, x); + + logger.info("Clearing all Sam's publisher assertions...."); + pub.setPublisherAssertions(authInfoSam, x); + + logger.info("Confirming we're clear"); + List before = pub.getPublisherAssertions(authInfoJoe); + Assert.assertNotNull(before); + Assert.assertTrue(before.isEmpty()); + System.out.println(before.size()); + for (int i = 0; i < before.size(); i++) { + JAXB.marshal(before.get(i), System.out); + } + + before = pub.getPublisherAssertions(authInfoSam); + Assert.assertNotNull(before); + Assert.assertTrue(before.isEmpty()); + System.out.println(before.size()); + for (int i = 0; i < before.size(); i++) { + JAXB.marshal(before.get(i), System.out); + } + + List assertionStatusReport = pub.getAssertionStatusReport(authInfoJoe, null); + Assert.assertTrue(assertionStatusReport.isEmpty()); + + assertionStatusReport = pub.getAssertionStatusReport(authInfoSam, null); + Assert.assertTrue(assertionStatusReport.isEmpty()); + + logger.info("Saving 1/2 publisher assertion...."); + List onehalfPA = tckAssertion.saveJoePublisherPublisherAssertion(authInfoJoe); + + before = pub.getPublisherAssertions(authInfoJoe); + Assert.assertNotNull(before); + Assert.assertFalse(before.isEmpty()); + System.out.println(before.size()); + for (int i = 0; i < before.size(); i++) { + JAXB.marshal(before.get(i), System.out); + } + //PublisherAssertion paIn = (PublisherAssertion)EntityCreator.buildFromDoc(TckPublisherAssertion.JOE_ASSERT_XML, "org.uddi.api_v3"); + //dp.getPublisherAssertion().add(paIn); + x = new Holder>(); + x.value = new ArrayList(); + logger.info("Clearing all publisher assertions...."); + pub.setPublisherAssertions(authInfoJoe, x); + System.out.println(x.value.size()); + for (int i = 0; i < x.value.size(); i++) { + JAXB.marshal(x.value.get(i), System.out); + } + + logger.info("Fetch all publisher assertions....there should be none"); + List publisherAssertions = pub.getPublisherAssertions(authInfoJoe); + System.out.println(publisherAssertions.size()); + for (int i = 0; i < publisherAssertions.size(); i++) { + JAXB.marshal(publisherAssertions.get(i), System.out); + } + Assert.assertNotNull(publisherAssertions); + Assert.assertTrue(publisherAssertions.isEmpty()); + // + } finally { + //tckAssertion.deleteJoePublisherPublisherAssertion(authInfoJoe); + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + tckTModel.deleteSamSyndicatorTmodel(authInfoSam); + } + } + + @Test + public void testSetPublisherAssertions2() throws Exception { + //create 1/2 PA + + //use Set with the same 1/2 PA + //confirm still present + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckTModel.saveSamSyndicatorTmodel(authInfoSam); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusiness.saveSamSyndicatorBusiness(authInfoSam); + List onehalfPA = tckAssertion.saveJoePublisherPublisherAssertion(authInfoJoe); + + List before = pub.getPublisherAssertions(authInfoJoe); + Assert.assertNotNull(before); + Assert.assertFalse(before.isEmpty()); + + pub.setPublisherAssertions(authInfoJoe, new Holder>(onehalfPA)); + List publisherAssertions = pub.getPublisherAssertions(authInfoJoe); + Assert.assertNotNull(publisherAssertions); + Assert.assertFalse(publisherAssertions.isEmpty()); + // + } finally { + //tckAssertion.deleteJoePublisherPublisherAssertion(authInfoJoe); + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + tckTModel.deleteSamSyndicatorTmodel(authInfoSam); + } + } + + @Test + public void testSetPublisherAssertions3() throws Exception { + //create 1/2 PA + //use Set with a new PA + //confirm first PA is gone and the new PA exists + try { + + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckTModel.saveSamSyndicatorTmodel(authInfoSam); + tckTModel.saveMaryPublisherTmodel(authInfoMary); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusiness.saveSamSyndicatorBusiness(authInfoSam); + tckBusiness.saveMaryPublisherBusiness(authInfoMary); + Holder> x = new Holder>(); + x.value = new ArrayList(); + logger.info("Clearing all Joe's publisher assertions...."); + pub.setPublisherAssertions(authInfoJoe, x); + + logger.info("Clearing all Sam's publisher assertions...."); + pub.setPublisherAssertions(authInfoSam, x); + + logger.info("Clearing all Mary's publisher assertions...."); + pub.setPublisherAssertions(authInfoMary, x); + + logger.info("Confirming we're clear"); + List before = pub.getPublisherAssertions(authInfoJoe); + Assert.assertNotNull(before); + + System.out.println(before.size()); + for (int i = 0; i < before.size(); i++) { + JAXB.marshal(before.get(i), System.out); + } + Assert.assertTrue(before.isEmpty()); + + before = pub.getPublisherAssertions(authInfoSam); + Assert.assertNotNull(before); + + System.out.println(before.size()); + for (int i = 0; i < before.size(); i++) { + JAXB.marshal(before.get(i), System.out); + } + Assert.assertTrue(before.isEmpty()); + + before = pub.getPublisherAssertions(authInfoMary); + Assert.assertNotNull(before); + + System.out.println(before.size()); + for (int i = 0; i < before.size(); i++) { + JAXB.marshal(before.get(i), System.out); + } + Assert.assertTrue(before.isEmpty()); + + List assertionStatusReport = pub.getAssertionStatusReport(authInfoJoe, null); + Assert.assertTrue(assertionStatusReport.isEmpty()); + + assertionStatusReport = pub.getAssertionStatusReport(authInfoSam, null); + Assert.assertTrue(assertionStatusReport.isEmpty()); + + assertionStatusReport = pub.getAssertionStatusReport(authInfoMary, null); + Assert.assertTrue(assertionStatusReport.isEmpty()); + + logger.info("Saving 1/2 publisher assertion...."); + List onehalfPA = tckAssertion.saveJoePublisherPublisherAssertion(authInfoJoe); + + before = pub.getPublisherAssertions(authInfoJoe); + Assert.assertNotNull(before); + Assert.assertFalse(before.isEmpty()); + System.out.println(before.size()); + for (int i = 0; i < before.size(); i++) { + JAXB.marshal(before.get(i), System.out); + } + //PublisherAssertion paIn = (PublisherAssertion)EntityCreator.buildFromDoc(TckPublisherAssertion.JOE_ASSERT_XML, "org.uddi.api_v3"); + //dp.getPublisherAssertion().add(paIn); + x = new Holder>(); + x.value = new ArrayList(); + PublisherAssertion pa = new PublisherAssertion(); + + pa.setFromKey(TckBusiness.JOE_BUSINESS_KEY); + pa.setToKey(TckBusiness.MARY_BUSINESS_KEY); + pa.setKeyedReference(new KeyedReference(UDDIConstants.RELATIONSHIPS, "parent-child", "child")); + + x.value.add(pa); + logger.info("Using set to clear existing and add a new publisher assertion...."); + pub.setPublisherAssertions(authInfoJoe, x); + System.out.println(x.value.size()); + for (int i = 0; i < x.value.size(); i++) { + JAXB.marshal(x.value.get(i), System.out); + } + + logger.info("Fetch all publisher assertions....there should be 1"); + List publisherAssertions = pub.getPublisherAssertions(authInfoJoe); + System.out.println(publisherAssertions.size()); + for (int i = 0; i < publisherAssertions.size(); i++) { + JAXB.marshal(publisherAssertions.get(i), System.out); + } + Assert.assertEquals(publisherAssertions.get(0).getFromKey(), pa.getFromKey()); + Assert.assertEquals(publisherAssertions.get(0).getToKey(), pa.getToKey()); + Assert.assertEquals(publisherAssertions.get(0).getKeyedReference().getKeyName(), pa.getKeyedReference().getKeyName()); + Assert.assertEquals(publisherAssertions.get(0).getKeyedReference().getKeyValue(), pa.getKeyedReference().getKeyValue()); + Assert.assertEquals(publisherAssertions.get(0).getKeyedReference().getTModelKey(), pa.getKeyedReference().getTModelKey()); + + // + } finally { + //tckAssertion.deleteJoePublisherPublisherAssertion(authInfoJoe); + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); + tckBusiness.deleteMaryPublisherBusiness(authInfoMary); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + tckTModel.deleteSamSyndicatorTmodel(authInfoSam); + tckTModel.deleteMaryPublisherTmodel(authInfoMary); + } + + } + DigSigUtil ds; + + void SetCertStoreSettigns() { + ds.put(DigSigUtil.SIGNATURE_KEYSTORE_FILE, "./src/test/resources/keystore.jks"); + ds.put(DigSigUtil.SIGNATURE_KEYSTORE_FILETYPE, "JKS"); + ds.put(DigSigUtil.SIGNATURE_KEYSTORE_FILE_PASSWORD, "Test"); + ds.put(DigSigUtil.SIGNATURE_KEYSTORE_KEY_ALIAS, "Test"); + ds.put(DigSigUtil.TRUSTSTORE_FILE, "./src/test/resources/truststore.jks"); + ds.put(DigSigUtil.TRUSTSTORE_FILETYPE, "JKS"); + ds.put(DigSigUtil.TRUSTSTORE_FILE_PASSWORD, "Test"); + } + + void Default() throws CertificateException { + ds = new DigSigUtil(); + SetCertStoreSettigns(); + ds.put(DigSigUtil.SIGNATURE_OPTION_CERT_INCLUSION_BASE64, "true"); + } + + @Test + public void testPublisherAssertionSignatures() throws Exception { + try { + Default(); + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckTModel.saveSamSyndicatorTmodel(authInfoSam); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusiness.saveSamSyndicatorBusiness(authInfoSam); + AddPublisherAssertions ap = new AddPublisherAssertions(); + ap.setAuthInfo(authInfoJoe); + + PublisherAssertion paIn = (PublisherAssertion) EntityCreator.buildFromDoc(TckPublisherAssertion.JOE_ASSERT_XML, "org.uddi.api_v3"); + paIn = ds.signUddiEntity(paIn); + + ap.getPublisherAssertion().add(paIn); + Assert.assertFalse(paIn.getSignature().isEmpty()); + pub.addPublisherAssertions(ap); + + List onehalfPA = tckAssertion.saveJoePublisherPublisherAssertion(authInfoJoe); + + + Assert.assertNotNull(onehalfPA); + Assert.assertFalse(onehalfPA.get(0).getSignature().isEmpty()); + Assert.assertFalse(onehalfPA.isEmpty()); + + Assert.assertNotNull(onehalfPA); + Assert.assertFalse(onehalfPA.get(0).getSignature().isEmpty()); + Assert.assertFalse(onehalfPA.isEmpty()); + Assert.assertEquals(paIn.getSignature().size(),onehalfPA.get(0).getSignature().size()); + Assert.assertEquals(paIn.getSignature().get(0).getId(),onehalfPA.get(0).getSignature().get(0).getId()); + Assert.assertEquals(paIn.getSignature().get(0).getKeyInfo().getId(),onehalfPA.get(0).getSignature().get(0).getKeyInfo().getId()); + Assert.assertEquals(paIn.getSignature().get(0).getKeyInfo().getContent().size(),onehalfPA.get(0).getSignature().get(0).getKeyInfo().getContent().size()); + + Assert.assertEquals(paIn.getSignature().get(0).getSignedInfo().getCanonicalizationMethod().getAlgorithm(),onehalfPA.get(0).getSignature().get(0).getSignedInfo().getCanonicalizationMethod().getAlgorithm()); + Assert.assertEquals(paIn.getSignature().get(0).getSignedInfo().getId(),onehalfPA.get(0).getSignature().get(0).getSignedInfo().getId()); + Assert.assertEquals(paIn.getSignature().get(0).getSignedInfo().getReference().size(),onehalfPA.get(0).getSignature().get(0).getSignedInfo().getReference().size()); + AtomicReference outmsg=new AtomicReference(); + boolean success=ds.verifySignedUddiEntity(onehalfPA.get(0), outmsg); + Assert.assertTrue(outmsg.get(), success); + + // + } finally { + //tckAssertion.deleteJoePublisherPublisherAssertion(authInfoJoe); + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + tckTModel.deleteSamSyndicatorTmodel(authInfoSam); + } + } +} diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_070_FindEntityTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_070_FindEntityTest.java similarity index 98% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/API_070_FindEntityTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_070_FindEntityTest.java index 722dc0faf..f63ea4478 100644 --- a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_070_FindEntityTest.java +++ b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_070_FindEntityTest.java @@ -1,314 +1,314 @@ -/* - * Copyright 2001-2009 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.rmi.RemoteException; -import java.util.List; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.Registry; -import org.apache.juddi.v3.client.UDDIConstants; -import org.apache.juddi.v3.tck.TckBindingTemplate; -import org.apache.juddi.v3.tck.TckBusiness; -import org.apache.juddi.v3.tck.TckBusinessService; -import static org.apache.juddi.v3.tck.TckBusinessService.JOE_SERVICE_KEY_2; -import static org.apache.juddi.v3.tck.TckBusinessService.JOE_SERVICE_XML_2; -import org.apache.juddi.v3.tck.TckFindEntity; -import org.apache.juddi.v3.tck.TckPublisher; -import org.apache.juddi.v3.tck.TckSecurity; -import org.apache.juddi.v3.tck.TckTModel; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.uddi.api_v3.BindingDetail; -import org.uddi.api_v3.BindingTemplate; -import org.uddi.api_v3.CategoryBag; -import org.uddi.api_v3.FindBinding; -import org.uddi.api_v3.FindQualifiers; -import org.uddi.api_v3.FindTModel; -import org.uddi.api_v3.KeyedReference; -import org.uddi.api_v3.Name; -import org.uddi.api_v3.SaveTModel; -import org.uddi.api_v3.TModel; -import org.uddi.api_v3.TModelBag; -import org.uddi.api_v3.TModelList; - -/** - * @author Jeff Faath - * @author Kurt T Stam - */ -public class API_070_FindEntityTest { - - private static Log logger = LogFactory.getLog(API_070_FindEntityTest.class); - - private static API_010_PublisherTest api010 = new API_010_PublisherTest(); - private static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - private static TckBusiness tckBusiness = new TckBusiness(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - private static TckBusinessService tckBusinessService = new TckBusinessService(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - private static TckBindingTemplate tckBindingTemplate = new TckBindingTemplate(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - private static TckFindEntity tckFindEntity = new TckFindEntity(new UDDIInquiryImpl()); - - private static String authInfoJoe = null; - - @BeforeClass - public static void setup() throws ConfigurationException { - Registry.start(); - logger.debug("Getting auth token.."); - try { - tckTModel.saveUDDIPublisherTmodel(TckSecurity.getAuthToken(new UDDISecurityImpl(), TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword())); - tckTModel.saveTmodels(TckSecurity.getAuthToken(new UDDISecurityImpl(), TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword())); - api010.saveJoePublisher(); - authInfoJoe = TckSecurity.getAuthToken(new UDDISecurityImpl(), TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); - } catch (RemoteException e) { - logger.error(e.getMessage(), e); - Assert.fail("Could not obtain authInfo token."); - } - } - - @AfterClass - public static void stopRegistry() throws ConfigurationException { - Registry.stop(); - } - - @Test - public void findEntities() throws Exception { - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe, true); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusinessService.saveJoePublisherService(authInfoJoe); - //uddi:tmodelkey:categories:bindings - tckBindingTemplate.saveJoePublisherBinding(authInfoJoe); - tckFindEntity.findBusiness(); - tckFindEntity.findService(null); - tckFindEntity.findBinding(null); - tckFindEntity.findTModel(null); - tckFindEntity.findAllBusiness(); - tckFindEntity.getNonExitingBusiness(); - } finally { - tckBindingTemplate.deleteJoePublisherBinding(authInfoJoe); - tckBusinessService.deleteJoePublisherService(authInfoJoe); - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - } - - } - - @Test - public void findSignedEntities() throws Exception { - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe, true); - tckBusiness.saveJoePublisherBusinessX509Signature(authInfoJoe); - tckBusinessService.saveJoePublisherService(authInfoJoe); - tckBindingTemplate.saveJoePublisherBinding(authInfoJoe); - - tckFindEntity.findAllSignedBusiness(); - tckFindEntity.findService(UDDIConstants.SIGNATURE_PRESENT); - tckFindEntity.findBinding(UDDIConstants.SIGNATURE_PRESENT); - //tckFindEntity.findTModel(UDDIConstants.SIGNATURE_PRESENT); - - tckFindEntity.findAllBusiness(); - tckFindEntity.getNonExitingBusiness(); - } finally { - tckBindingTemplate.deleteJoePublisherBinding(authInfoJoe); - tckBusinessService.deleteJoePublisherService(authInfoJoe); - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - } - - } - - @Test - public void JUDDI_843_tModel() throws Exception { - - UDDIInquiryImpl inquiry = new UDDIInquiryImpl(); - - UDDIPublicationImpl pub = new UDDIPublicationImpl(); - SaveTModel stm = new SaveTModel(); - stm.setAuthInfo(authInfoJoe); - TModel tm = new TModel(); - tm.setName(new Name("Buenos Dias", "es-US")); - stm.getTModel().add(tm); - pub.saveTModel(stm); - - FindTModel ftm = new FindTModel(); - ftm.setAuthInfo(authInfoJoe); - ftm.setName(new Name("%", "es-US")); - ftm.setFindQualifiers(new FindQualifiers()); - ftm.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); - ftm.getFindQualifiers().getFindQualifier().add(UDDIConstants.SORT_BY_NAME_ASC); - ftm.getFindQualifiers().getFindQualifier().add(UDDIConstants.CASE_INSENSITIVE_MATCH); - TModelList findTModel = inquiry.findTModel(ftm); - Assert.assertNotNull(findTModel); - Assert.assertNotNull(findTModel.getTModelInfos()); - Assert.assertNotNull(findTModel.getTModelInfos().getTModelInfo()); - boolean found = false; - for (int i = 0; i < findTModel.getTModelInfos().getTModelInfo().size(); i++) { - if (findTModel.getTModelInfos().getTModelInfo().get(i).getName().getValue().equalsIgnoreCase("Buenos Dias") - && findTModel.getTModelInfos().getTModelInfo().get(i).getName().getLang().equalsIgnoreCase("es-US")) { - found = true; - break; - } - } - Assert.assertTrue("tMdoel search by name with language defined failed, item not found", found); - - } - - /** - * matches for tModel by catbag, default settings, exact match - * @throws Exception - */ - @Test - public void JUDDI_899() throws Exception { - UDDIInquiryImpl inquiry = new UDDIInquiryImpl(); - - - FindTModel ftm = new FindTModel(); - ftm.setAuthInfo(authInfoJoe); - ftm.setCategoryBag(new CategoryBag()); - ftm.getCategoryBag().getKeyedReference().add(new KeyedReference("uddi:uddi.org:categorization:types", "uddi-org:types:keyGenerator", "keyGenerator")); - TModelList findTModel = inquiry.findTModel(ftm); - Assert.assertNotNull(findTModel); - Assert.assertNotNull(findTModel.getTModelInfos()); - Assert.assertNotNull(findTModel.getTModelInfos().getTModelInfo()); - - } - - /** - * matches for tModel by catbag, default settings, approximate match - * @throws Exception - */ - @Test - public void JUDDI_899_1() throws Exception { - UDDIInquiryImpl inquiry = new UDDIInquiryImpl(); - - FindTModel ftm = new FindTModel(); - ftm.setFindQualifiers(new FindQualifiers()); - ftm.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); - ftm.setAuthInfo(authInfoJoe); - ftm.setCategoryBag(new CategoryBag()); - ftm.getCategoryBag().getKeyedReference().add(new KeyedReference("uddi:uddi.org:categorization:types", "uddi-org:types:keyGenerator", "key%")); - TModelList findTModel = inquiry.findTModel(ftm); - Assert.assertNotNull(findTModel); - Assert.assertNotNull(findTModel.getTModelInfos()); - Assert.assertNotNull(findTModel.getTModelInfos().getTModelInfo()); - - } - - /** - * matches for tModel by catbag, default settings, case insensitive - * @throws Exception - */ - @Test - public void JUDDI_899_2() throws Exception { - UDDIInquiryImpl inquiry = new UDDIInquiryImpl(); - - - FindTModel ftm = new FindTModel(); - ftm.setAuthInfo(authInfoJoe); - ftm.setFindQualifiers(new FindQualifiers()); - ftm.getFindQualifiers().getFindQualifier().add(UDDIConstants.CASE_INSENSITIVE_MATCH); - - ftm.setCategoryBag(new CategoryBag()); - //all of the defeault installed data is for "keyGenerator" - ftm.getCategoryBag().getKeyedReference().add(new KeyedReference("uddi:uddi.org:categorization:types", "uddi-org:types:keyGenerator", "keygenerator")); - TModelList findTModel = inquiry.findTModel(ftm); - Assert.assertNotNull(findTModel); - Assert.assertNotNull(findTModel.getTModelInfos()); - Assert.assertNotNull(findTModel.getTModelInfos().getTModelInfo()); - - } - - @Test - public void JUDDI_992() throws Exception { - try{ - - tckTModel.saveJoePublisherTmodel(authInfoJoe); - //save a business, service and bindings - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusinessService. saveService(authInfoJoe, JOE_SERVICE_XML_2, JOE_SERVICE_KEY_2); - - UDDIInquiryImpl inquiry = new UDDIInquiryImpl(); - FindBinding body = new FindBinding(); - body.setServiceKey(TckBusinessService.JOE_SERVICE_KEY_2); - body.setFindQualifiers(new FindQualifiers()); - body.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); - body.getFindQualifiers().getFindQualifier().add(UDDIConstants.SORT_BY_DATE_ASC); - BindingDetail result = inquiry.findBinding(body); - if (result == null) - Assert.fail("Null result from find binding operation"); - List btList = result.getBindingTemplate(); - if (btList == null || btList.size() == 0) - Assert.fail("No result from find binding operation"); - Assert.assertTrue(btList.size()==1); - - } - finally { - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - } - } - - /** - * find by binding by service key and category bag - *
-         * 
-         * <find_binding xmlns="urn:uddi-org:api_v2" xmlns:xml="http://www.w3.org/XML/1998/namespace" serviceKey="">
-            <findQualifiers>
-              <findQualifier>orAllKeys</findQualifier>
-            </findQualifiers>
-            <tModelBag>
-              <tModelKey>uddi:uddi.org:protocol:serverauthenticatedssl3</tModelKey>
-            </tModelBag>
-            <categoryBag>
-              <keyedReference tModelKey="uuid:f85a1fb1-2be1-4197-9a3f-fc310222cd34" keyName="category" keyValue="secure" />
-            </categoryBag>
-          </find_binding>
-         * 
- * @throws Exception - */ - @Test - public void JUDDI_992_2() throws Exception { - try{ - - tckTModel.saveJoePublisherTmodel(authInfoJoe); - //save a business, service and bindings - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusinessService. saveService(authInfoJoe, JOE_SERVICE_XML_2, JOE_SERVICE_KEY_2); - - UDDIInquiryImpl inquiry = new UDDIInquiryImpl(); - FindBinding body = new FindBinding(); - // body.setServiceKey(TckBusinessService.JOE_SERVICE_KEY_2); - body.setFindQualifiers(new FindQualifiers()); - body.getFindQualifiers().getFindQualifier().add(UDDIConstants.OR_ALL_KEYS); - body.setTModelBag(new TModelBag()); - body.getTModelBag().getTModelKey().add("uddi:uddi.org:transport:telephone"); - body.setCategoryBag(new CategoryBag()); - body.getCategoryBag().getKeyedReference().add(new KeyedReference("uddi:tmodelkey:categories:bindings", "category", "accesspoint")); - BindingDetail result = inquiry.findBinding(body); - if (result == null) - Assert.fail("Null result from find binding operation"); - List btList = result.getBindingTemplate(); - if (btList == null || btList.size() == 0) - Assert.fail("No result from find binding operation"); - Assert.assertTrue(btList.size()==1); - - } - finally { - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - } - } -} +/* + * Copyright 2001-2009 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.rmi.RemoteException; +import java.util.List; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.Registry; +import org.apache.juddi.v3.client.UDDIConstants; +import org.apache.juddi.v3.tck.TckBindingTemplate; +import org.apache.juddi.v3.tck.TckBusiness; +import org.apache.juddi.v3.tck.TckBusinessService; +import static org.apache.juddi.v3.tck.TckBusinessService.JOE_SERVICE_KEY_2; +import static org.apache.juddi.v3.tck.TckBusinessService.JOE_SERVICE_XML_2; +import org.apache.juddi.v3.tck.TckFindEntity; +import org.apache.juddi.v3.tck.TckPublisher; +import org.apache.juddi.v3.tck.TckSecurity; +import org.apache.juddi.v3.tck.TckTModel; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.uddi.api_v3.BindingDetail; +import org.uddi.api_v3.BindingTemplate; +import org.uddi.api_v3.CategoryBag; +import org.uddi.api_v3.FindBinding; +import org.uddi.api_v3.FindQualifiers; +import org.uddi.api_v3.FindTModel; +import org.uddi.api_v3.KeyedReference; +import org.uddi.api_v3.Name; +import org.uddi.api_v3.SaveTModel; +import org.uddi.api_v3.TModel; +import org.uddi.api_v3.TModelBag; +import org.uddi.api_v3.TModelList; + +/** + * @author Jeff Faath + * @author Kurt T Stam + */ +public class API_070_FindEntityTest { + + private static Log logger = LogFactory.getLog(API_070_FindEntityTest.class); + + private static API_010_PublisherTest api010 = new API_010_PublisherTest(); + private static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + private static TckBusiness tckBusiness = new TckBusiness(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + private static TckBusinessService tckBusinessService = new TckBusinessService(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + private static TckBindingTemplate tckBindingTemplate = new TckBindingTemplate(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + private static TckFindEntity tckFindEntity = new TckFindEntity(new UDDIInquiryImpl()); + + private static String authInfoJoe = null; + + @BeforeClass + public static void setup() throws ConfigurationException { + Registry.start(); + logger.debug("Getting auth token.."); + try { + tckTModel.saveUDDIPublisherTmodel(TckSecurity.getAuthToken(new UDDISecurityImpl(), TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword())); + tckTModel.saveTmodels(TckSecurity.getAuthToken(new UDDISecurityImpl(), TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword())); + api010.saveJoePublisher(); + authInfoJoe = TckSecurity.getAuthToken(new UDDISecurityImpl(), TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); + } catch (RemoteException e) { + logger.error(e.getMessage(), e); + Assert.fail("Could not obtain authInfo token."); + } + } + + @AfterClass + public static void stopRegistry() throws ConfigurationException { + Registry.stop(); + } + + @Test + public void findEntities() throws Exception { + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe, true); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusinessService.saveJoePublisherService(authInfoJoe); + //uddi:tmodelkey:categories:bindings + tckBindingTemplate.saveJoePublisherBinding(authInfoJoe); + tckFindEntity.findBusiness(); + tckFindEntity.findService(null); + tckFindEntity.findBinding(null); + tckFindEntity.findTModel(null); + tckFindEntity.findAllBusiness(); + tckFindEntity.getNonExitingBusiness(); + } finally { + tckBindingTemplate.deleteJoePublisherBinding(authInfoJoe); + tckBusinessService.deleteJoePublisherService(authInfoJoe); + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + } + + } + + @Test + public void findSignedEntities() throws Exception { + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe, true); + tckBusiness.saveJoePublisherBusinessX509Signature(authInfoJoe); + tckBusinessService.saveJoePublisherService(authInfoJoe); + tckBindingTemplate.saveJoePublisherBinding(authInfoJoe); + + tckFindEntity.findAllSignedBusiness(); + tckFindEntity.findService(UDDIConstants.SIGNATURE_PRESENT); + tckFindEntity.findBinding(UDDIConstants.SIGNATURE_PRESENT); + //tckFindEntity.findTModel(UDDIConstants.SIGNATURE_PRESENT); + + tckFindEntity.findAllBusiness(); + tckFindEntity.getNonExitingBusiness(); + } finally { + tckBindingTemplate.deleteJoePublisherBinding(authInfoJoe); + tckBusinessService.deleteJoePublisherService(authInfoJoe); + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + } + + } + + @Test + public void JUDDI_843_tModel() throws Exception { + + UDDIInquiryImpl inquiry = new UDDIInquiryImpl(); + + UDDIPublicationImpl pub = new UDDIPublicationImpl(); + SaveTModel stm = new SaveTModel(); + stm.setAuthInfo(authInfoJoe); + TModel tm = new TModel(); + tm.setName(new Name("Buenos Dias", "es-US")); + stm.getTModel().add(tm); + pub.saveTModel(stm); + + FindTModel ftm = new FindTModel(); + ftm.setAuthInfo(authInfoJoe); + ftm.setName(new Name("%", "es-US")); + ftm.setFindQualifiers(new FindQualifiers()); + ftm.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); + ftm.getFindQualifiers().getFindQualifier().add(UDDIConstants.SORT_BY_NAME_ASC); + ftm.getFindQualifiers().getFindQualifier().add(UDDIConstants.CASE_INSENSITIVE_MATCH); + TModelList findTModel = inquiry.findTModel(ftm); + Assert.assertNotNull(findTModel); + Assert.assertNotNull(findTModel.getTModelInfos()); + Assert.assertNotNull(findTModel.getTModelInfos().getTModelInfo()); + boolean found = false; + for (int i = 0; i < findTModel.getTModelInfos().getTModelInfo().size(); i++) { + if (findTModel.getTModelInfos().getTModelInfo().get(i).getName().getValue().equalsIgnoreCase("Buenos Dias") + && findTModel.getTModelInfos().getTModelInfo().get(i).getName().getLang().equalsIgnoreCase("es-US")) { + found = true; + break; + } + } + Assert.assertTrue("tMdoel search by name with language defined failed, item not found", found); + + } + + /** + * matches for tModel by catbag, default settings, exact match + * @throws Exception + */ + @Test + public void JUDDI_899() throws Exception { + UDDIInquiryImpl inquiry = new UDDIInquiryImpl(); + + + FindTModel ftm = new FindTModel(); + ftm.setAuthInfo(authInfoJoe); + ftm.setCategoryBag(new CategoryBag()); + ftm.getCategoryBag().getKeyedReference().add(new KeyedReference("uddi:uddi.org:categorization:types", "uddi-org:types:keyGenerator", "keyGenerator")); + TModelList findTModel = inquiry.findTModel(ftm); + Assert.assertNotNull(findTModel); + Assert.assertNotNull(findTModel.getTModelInfos()); + Assert.assertNotNull(findTModel.getTModelInfos().getTModelInfo()); + + } + + /** + * matches for tModel by catbag, default settings, approximate match + * @throws Exception + */ + @Test + public void JUDDI_899_1() throws Exception { + UDDIInquiryImpl inquiry = new UDDIInquiryImpl(); + + FindTModel ftm = new FindTModel(); + ftm.setFindQualifiers(new FindQualifiers()); + ftm.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); + ftm.setAuthInfo(authInfoJoe); + ftm.setCategoryBag(new CategoryBag()); + ftm.getCategoryBag().getKeyedReference().add(new KeyedReference("uddi:uddi.org:categorization:types", "uddi-org:types:keyGenerator", "key%")); + TModelList findTModel = inquiry.findTModel(ftm); + Assert.assertNotNull(findTModel); + Assert.assertNotNull(findTModel.getTModelInfos()); + Assert.assertNotNull(findTModel.getTModelInfos().getTModelInfo()); + + } + + /** + * matches for tModel by catbag, default settings, case insensitive + * @throws Exception + */ + @Test + public void JUDDI_899_2() throws Exception { + UDDIInquiryImpl inquiry = new UDDIInquiryImpl(); + + + FindTModel ftm = new FindTModel(); + ftm.setAuthInfo(authInfoJoe); + ftm.setFindQualifiers(new FindQualifiers()); + ftm.getFindQualifiers().getFindQualifier().add(UDDIConstants.CASE_INSENSITIVE_MATCH); + + ftm.setCategoryBag(new CategoryBag()); + //all of the defeault installed data is for "keyGenerator" + ftm.getCategoryBag().getKeyedReference().add(new KeyedReference("uddi:uddi.org:categorization:types", "uddi-org:types:keyGenerator", "keygenerator")); + TModelList findTModel = inquiry.findTModel(ftm); + Assert.assertNotNull(findTModel); + Assert.assertNotNull(findTModel.getTModelInfos()); + Assert.assertNotNull(findTModel.getTModelInfos().getTModelInfo()); + + } + + @Test + public void JUDDI_992() throws Exception { + try{ + + tckTModel.saveJoePublisherTmodel(authInfoJoe); + //save a business, service and bindings + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusinessService. saveService(authInfoJoe, JOE_SERVICE_XML_2, JOE_SERVICE_KEY_2); + + UDDIInquiryImpl inquiry = new UDDIInquiryImpl(); + FindBinding body = new FindBinding(); + body.setServiceKey(TckBusinessService.JOE_SERVICE_KEY_2); + body.setFindQualifiers(new FindQualifiers()); + body.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); + body.getFindQualifiers().getFindQualifier().add(UDDIConstants.SORT_BY_DATE_ASC); + BindingDetail result = inquiry.findBinding(body); + if (result == null) + Assert.fail("Null result from find binding operation"); + List btList = result.getBindingTemplate(); + if (btList == null || btList.size() == 0) + Assert.fail("No result from find binding operation"); + Assert.assertTrue(btList.size()==1); + + } + finally { + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + } + } + + /** + * find by binding by service key and category bag + *
+         * 
+         * <find_binding xmlns="urn:uddi-org:api_v2" xmlns:xml="http://www.w3.org/XML/1998/namespace" serviceKey="">
+            <findQualifiers>
+              <findQualifier>orAllKeys</findQualifier>
+            </findQualifiers>
+            <tModelBag>
+              <tModelKey>uddi:uddi.org:protocol:serverauthenticatedssl3</tModelKey>
+            </tModelBag>
+            <categoryBag>
+              <keyedReference tModelKey="uuid:f85a1fb1-2be1-4197-9a3f-fc310222cd34" keyName="category" keyValue="secure" />
+            </categoryBag>
+          </find_binding>
+         * 
+ * @throws Exception + */ + @Test + public void JUDDI_992_2() throws Exception { + try{ + + tckTModel.saveJoePublisherTmodel(authInfoJoe); + //save a business, service and bindings + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusinessService. saveService(authInfoJoe, JOE_SERVICE_XML_2, JOE_SERVICE_KEY_2); + + UDDIInquiryImpl inquiry = new UDDIInquiryImpl(); + FindBinding body = new FindBinding(); + // body.setServiceKey(TckBusinessService.JOE_SERVICE_KEY_2); + body.setFindQualifiers(new FindQualifiers()); + body.getFindQualifiers().getFindQualifier().add(UDDIConstants.OR_ALL_KEYS); + body.setTModelBag(new TModelBag()); + body.getTModelBag().getTModelKey().add("uddi:uddi.org:transport:telephone"); + body.setCategoryBag(new CategoryBag()); + body.getCategoryBag().getKeyedReference().add(new KeyedReference("uddi:tmodelkey:categories:bindings", "category", "accesspoint")); + BindingDetail result = inquiry.findBinding(body); + if (result == null) + Assert.fail("Null result from find binding operation"); + List btList = result.getBindingTemplate(); + if (btList == null || btList.size() == 0) + Assert.fail("No result from find binding operation"); + Assert.assertTrue(btList.size()==1); + + } + finally { + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + } + } +} diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_080_SubscriptionTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_080_SubscriptionTest.java similarity index 97% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/API_080_SubscriptionTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_080_SubscriptionTest.java index 36dd1e0e7..d6a42ecf8 100644 --- a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_080_SubscriptionTest.java +++ b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_080_SubscriptionTest.java @@ -1,161 +1,161 @@ -/* - * Copyright 2001-2009 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.rmi.RemoteException; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.Registry; -import org.apache.juddi.v3.tck.TckBindingTemplate; -import org.apache.juddi.v3.tck.TckBusiness; -import org.apache.juddi.v3.tck.TckBusinessService; -import org.apache.juddi.v3.tck.TckPublisher; -import org.apache.juddi.v3.tck.TckSecurity; -import org.apache.juddi.v3.tck.TckSubscription; -import org.apache.juddi.v3.tck.TckTModel; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * @author Jeff Faath - * @author Kurt T Stam - */ -public class API_080_SubscriptionTest -{ - private static Log logger = LogFactory.getLog(API_080_SubscriptionTest.class); - - private static API_010_PublisherTest api010 = new API_010_PublisherTest(); - private static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - private static TckBusiness tckBusiness = new TckBusiness(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - private static TckBusinessService tckBusinessService = new TckBusinessService(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - private static TckBindingTemplate tckBindingTemplate = new TckBindingTemplate(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - private static TckSubscription tckSubscription = new TckSubscription(new UDDISubscriptionImpl(), new UDDISecurityImpl(), new UDDIInquiryImpl()); - - private static String authInfoJoe = null; - private static String authInfoSam = null; - - @BeforeClass - public static void setup() throws ConfigurationException { - Registry.start(); - logger.info("API_080_SubscriptionTest"); - logger.debug("Getting auth token.."); - try { - api010.saveJoePublisher(); - authInfoJoe = TckSecurity.getAuthToken(new UDDISecurityImpl(), TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); - - api010.saveSamSyndicator(); - authInfoSam = TckSecurity.getAuthToken(new UDDISecurityImpl(), TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword()); - - String authInfoUDDI = TckSecurity.getAuthToken(new UDDISecurityImpl(), TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword()); - tckTModel.saveUDDIPublisherTmodel(authInfoUDDI); - tckTModel.saveTModels(authInfoUDDI, TckTModel.TMODELS_XML); - } catch (RemoteException e) { - logger.error(e.getMessage(), e); - Assert.fail("Could not obtain authInfo token."); - } - - } - - @AfterClass - public static void stopRegistry() throws ConfigurationException { - tckTModel.deleteCreatedTModels(authInfoJoe); - Registry.stop(); - } - - @Test - public void joePublisher() { - try { - tckTModel.saveJoePublisherTmodel(authInfoJoe); - tckBusiness.saveJoePublisherBusiness(authInfoJoe); - tckBusinessService.saveJoePublisherService(authInfoJoe); - tckBindingTemplate.saveJoePublisherBinding(authInfoJoe); - tckSubscription.saveJoePublisherSubscription(authInfoJoe); - tckSubscription.getJoePublisherSubscriptionResults(authInfoJoe); - } catch (Exception e) { - e.printStackTrace(); - Assert.fail(); - } catch (Throwable t) { - t.printStackTrace(); - Assert.fail(); - } - finally { - tckSubscription.deleteJoePublisherSubscription(authInfoJoe); - tckBindingTemplate.deleteJoePublisherBinding(authInfoJoe); - tckBusinessService.deleteJoePublisherService(authInfoJoe); - tckBusiness.deleteJoePublisherBusiness(authInfoJoe); - tckTModel.deleteJoePublisherTmodel(authInfoJoe); - } - - } - - @Test - public void samSyndicator() { - try { - tckTModel.saveSamSyndicatorTmodel(authInfoSam); - tckBusiness.saveSamSyndicatorBusiness(authInfoSam); - tckBusinessService.saveSamSyndicatorService(authInfoSam); - tckSubscription.saveSamSyndicatorSubscription(authInfoSam); - tckSubscription.getSamSyndicatorSubscriptionResults(authInfoSam); - } - finally { - tckSubscription.deleteSamSyndicatorSubscription(authInfoSam); - tckBusinessService.deleteSamSyndicatorService(authInfoSam); - tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); - tckTModel.deleteSamSyndicatorTmodel(authInfoSam); - } - - } - - @Test - public void samSyndicatorWithChunkingOnFind() { - try { - tckTModel.saveSamSyndicatorTmodel(authInfoSam); - tckBusiness.saveSamSyndicatorBusiness(authInfoSam); - tckBusinessService.saveSamSyndicatorService(authInfoSam); - tckSubscription.saveSamSyndicatorSubscriptionWithChunkingOnFind(authInfoSam); - tckSubscription.getSamSyndicatorSubscriptionResultsWithChunkingOnFind(authInfoSam); - } - finally { - tckSubscription.deleteSamSyndicatorSubscriptionWithChunkingOnFind(authInfoSam); - tckBusinessService.deleteSamSyndicatorService(authInfoSam); - tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); - tckTModel.deleteSamSyndicatorTmodel(authInfoSam); - } - - } - - @Test - public void samSyndicatorWithChunkingOnGet() { - try { - tckTModel.saveSamSyndicatorTmodel(authInfoSam); - tckBusiness.saveSamSyndicatorBusiness(authInfoSam); - tckBusinessService.saveSamSyndicatorService(authInfoSam); - tckSubscription.saveSamSyndicatorSubscriptionWithChunkingOnGet(authInfoSam); - tckSubscription.getSamSyndicatorSubscriptionResultsWithChunkingOnGet(authInfoSam); - } - finally { - tckSubscription.deleteSamSyndicatorSubscriptionWithChunkingOnGet(authInfoSam); - tckBusinessService.deleteSamSyndicatorService(authInfoSam); - tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); - tckTModel.deleteSamSyndicatorTmodel(authInfoSam); - } - - } - -} +/* + * Copyright 2001-2009 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.rmi.RemoteException; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.Registry; +import org.apache.juddi.v3.tck.TckBindingTemplate; +import org.apache.juddi.v3.tck.TckBusiness; +import org.apache.juddi.v3.tck.TckBusinessService; +import org.apache.juddi.v3.tck.TckPublisher; +import org.apache.juddi.v3.tck.TckSecurity; +import org.apache.juddi.v3.tck.TckSubscription; +import org.apache.juddi.v3.tck.TckTModel; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * @author Jeff Faath + * @author Kurt T Stam + */ +public class API_080_SubscriptionTest +{ + private static Log logger = LogFactory.getLog(API_080_SubscriptionTest.class); + + private static API_010_PublisherTest api010 = new API_010_PublisherTest(); + private static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + private static TckBusiness tckBusiness = new TckBusiness(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + private static TckBusinessService tckBusinessService = new TckBusinessService(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + private static TckBindingTemplate tckBindingTemplate = new TckBindingTemplate(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + private static TckSubscription tckSubscription = new TckSubscription(new UDDISubscriptionImpl(), new UDDISecurityImpl(), new UDDIInquiryImpl()); + + private static String authInfoJoe = null; + private static String authInfoSam = null; + + @BeforeClass + public static void setup() throws ConfigurationException { + Registry.start(); + logger.info("API_080_SubscriptionTest"); + logger.debug("Getting auth token.."); + try { + api010.saveJoePublisher(); + authInfoJoe = TckSecurity.getAuthToken(new UDDISecurityImpl(), TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); + + api010.saveSamSyndicator(); + authInfoSam = TckSecurity.getAuthToken(new UDDISecurityImpl(), TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword()); + + String authInfoUDDI = TckSecurity.getAuthToken(new UDDISecurityImpl(), TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword()); + tckTModel.saveUDDIPublisherTmodel(authInfoUDDI); + tckTModel.saveTModels(authInfoUDDI, TckTModel.TMODELS_XML); + } catch (RemoteException e) { + logger.error(e.getMessage(), e); + Assert.fail("Could not obtain authInfo token."); + } + + } + + @AfterClass + public static void stopRegistry() throws ConfigurationException { + tckTModel.deleteCreatedTModels(authInfoJoe); + Registry.stop(); + } + + @Test + public void joePublisher() { + try { + tckTModel.saveJoePublisherTmodel(authInfoJoe); + tckBusiness.saveJoePublisherBusiness(authInfoJoe); + tckBusinessService.saveJoePublisherService(authInfoJoe); + tckBindingTemplate.saveJoePublisherBinding(authInfoJoe); + tckSubscription.saveJoePublisherSubscription(authInfoJoe); + tckSubscription.getJoePublisherSubscriptionResults(authInfoJoe); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail(); + } catch (Throwable t) { + t.printStackTrace(); + Assert.fail(); + } + finally { + tckSubscription.deleteJoePublisherSubscription(authInfoJoe); + tckBindingTemplate.deleteJoePublisherBinding(authInfoJoe); + tckBusinessService.deleteJoePublisherService(authInfoJoe); + tckBusiness.deleteJoePublisherBusiness(authInfoJoe); + tckTModel.deleteJoePublisherTmodel(authInfoJoe); + } + + } + + @Test + public void samSyndicator() { + try { + tckTModel.saveSamSyndicatorTmodel(authInfoSam); + tckBusiness.saveSamSyndicatorBusiness(authInfoSam); + tckBusinessService.saveSamSyndicatorService(authInfoSam); + tckSubscription.saveSamSyndicatorSubscription(authInfoSam); + tckSubscription.getSamSyndicatorSubscriptionResults(authInfoSam); + } + finally { + tckSubscription.deleteSamSyndicatorSubscription(authInfoSam); + tckBusinessService.deleteSamSyndicatorService(authInfoSam); + tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); + tckTModel.deleteSamSyndicatorTmodel(authInfoSam); + } + + } + + @Test + public void samSyndicatorWithChunkingOnFind() { + try { + tckTModel.saveSamSyndicatorTmodel(authInfoSam); + tckBusiness.saveSamSyndicatorBusiness(authInfoSam); + tckBusinessService.saveSamSyndicatorService(authInfoSam); + tckSubscription.saveSamSyndicatorSubscriptionWithChunkingOnFind(authInfoSam); + tckSubscription.getSamSyndicatorSubscriptionResultsWithChunkingOnFind(authInfoSam); + } + finally { + tckSubscription.deleteSamSyndicatorSubscriptionWithChunkingOnFind(authInfoSam); + tckBusinessService.deleteSamSyndicatorService(authInfoSam); + tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); + tckTModel.deleteSamSyndicatorTmodel(authInfoSam); + } + + } + + @Test + public void samSyndicatorWithChunkingOnGet() { + try { + tckTModel.saveSamSyndicatorTmodel(authInfoSam); + tckBusiness.saveSamSyndicatorBusiness(authInfoSam); + tckBusinessService.saveSamSyndicatorService(authInfoSam); + tckSubscription.saveSamSyndicatorSubscriptionWithChunkingOnGet(authInfoSam); + tckSubscription.getSamSyndicatorSubscriptionResultsWithChunkingOnGet(authInfoSam); + } + finally { + tckSubscription.deleteSamSyndicatorSubscriptionWithChunkingOnGet(authInfoSam); + tckBusinessService.deleteSamSyndicatorService(authInfoSam); + tckBusiness.deleteSamSyndicatorBusiness(authInfoSam); + tckTModel.deleteSamSyndicatorTmodel(authInfoSam); + } + + } + +} diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_090_SubscriptionListenerIntegrationTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_090_SubscriptionListenerIntegrationTest.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/API_090_SubscriptionListenerIntegrationTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_090_SubscriptionListenerIntegrationTest.java diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_099_LoadTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_099_LoadTest.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/API_099_LoadTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_099_LoadTest.java diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_100_ClientSubscriptionInfoTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_100_ClientSubscriptionInfoTest.java similarity index 97% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/API_100_ClientSubscriptionInfoTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_100_ClientSubscriptionInfoTest.java index e6ede27d7..6a722923d 100644 --- a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_100_ClientSubscriptionInfoTest.java +++ b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_100_ClientSubscriptionInfoTest.java @@ -1,203 +1,203 @@ -/* - * Copyright 2001-2009 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.rmi.RemoteException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.Registry; -import org.apache.juddi.api_v3.Clerk; -import org.apache.juddi.api_v3.ClerkDetail; -import org.apache.juddi.api_v3.ClientSubscriptionInfo; -import org.apache.juddi.api_v3.ClientSubscriptionInfoDetail; -import org.apache.juddi.api_v3.DeleteClientSubscriptionInfo; -import org.apache.juddi.api_v3.GetClientSubscriptionInfoDetail; -import org.apache.juddi.api_v3.Node; -import org.apache.juddi.api_v3.NodeDetail; -import org.apache.juddi.api_v3.SaveClerk; -import org.apache.juddi.api_v3.SaveClientSubscriptionInfo; -import org.apache.juddi.api_v3.SaveNode; -import org.apache.juddi.v3.error.InvalidKeyPassedException; -import org.apache.juddi.v3.error.ValueNotAllowedException; -import org.apache.juddi.v3.tck.TckPublisher; -import org.apache.juddi.v3.tck.TckSecurity; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.v3_service.UDDISecurityPortType; - -/** - * @author Kurt T Stam - */ -public class API_100_ClientSubscriptionInfoTest { - - private JUDDIApiImpl publisher = new JUDDIApiImpl(); - private static Log logger = LogFactory.getLog(API_100_ClientSubscriptionInfoTest.class); - private static API_010_PublisherTest api010 = new API_010_PublisherTest(); - private static String authInfoJoe = null; - - @BeforeClass - public static void setup() throws ConfigurationException, RemoteException { - Registry.start(); - logger.debug("Getting auth tokens.."); - try { - api010.saveJoePublisher(); - UDDISecurityPortType security = new UDDISecurityImpl(); - authInfoJoe = TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); - } catch (DispositionReportFaultMessage e) { - logger.error(e.getMessage(), e); - Assert.fail("Could not obtain authInfo token."); - } - } - - @AfterClass - public static void stopRegistry() throws ConfigurationException { - Registry.stop(); - } - - @Test - public void addClientSubscriptionInfo() { - ClientSubscriptionInfo clientSubscriptionInfo = new ClientSubscriptionInfo(); - - Node node = new Node(); - node.setSecurityUrl("http://localhost:8080/services/securityUrl"); - node.setCustodyTransferUrl("http://localhost:8080/services/securityUrl"); - node.setDescription("description"); - node.setInquiryUrl("http://localhost:8080/services/securityUrl"); - node.setPublishUrl("http://localhost:8080/services/publishUrl"); - node.setSubscriptionListenerUrl("http://localhost:8080/services/subUrladdClientSubscriptionInfo"); - node.setProxyTransport("org.apache.juddi.v3.client.transport.JAXWSTransport"); - node.setSubscriptionUrl("http://localhost:8080/services/securityUrl"); - node.setName("default"); - node.setClientName("defaultClient"); - SaveNode saveNode = new SaveNode(); - saveNode.setAuthInfo(authInfoJoe); - saveNode.getNode().add(node); - - Clerk clerk = new Clerk(); - clerk.setName("clerkName"); - clerk.setPublisher("root"); - clerk.setNode(node); - SaveClerk saveClerk = new SaveClerk(); - saveClerk.setAuthInfo(authInfoJoe); - saveClerk.getClerk().add(clerk); - - clientSubscriptionInfo.setFromClerk(clerk); - - Node node2 = new Node(); - node2.setSecurityUrl("http://localhost:8080/services/securityUrl2"); - node2.setCustodyTransferUrl("https://localhost:8080/services/securityUrl2"); - node2.setDescription("description2"); - node2.setInquiryUrl("http://localhost:8080/services/securityUrl2"); - node2.setPublishUrl("http://localhost:8080/services/securityUrl2"); - node2.setProxyTransport("org.apache.juddi.v3.client.transport.JAXWSTransport"); - node2.setSubscriptionUrl("http://localhost:8080/services/securityUrl2"); - node2.setSubscriptionListenerUrl("http://localhost:8080/services/securityUrl2"); - node2.setName("default2"); - node2.setClientName("default2Client"); - saveNode.getNode().add(node2); - - Clerk clerk2 = new Clerk(); - clerk2.setName("clerkName2"); - clerk2.setPublisher("root"); - clerk2.setNode(node2); - saveClerk.getClerk().add(clerk2); - - clientSubscriptionInfo.setFromClerk(clerk); - - clientSubscriptionInfo.setSubscriptionKey("mykey"); - - SaveClientSubscriptionInfo saveClientSubscriptionInfo = new SaveClientSubscriptionInfo(); - saveClientSubscriptionInfo.setAuthInfo(authInfoJoe); - saveClientSubscriptionInfo.getClientSubscriptionInfo().add(clientSubscriptionInfo); - - ClientSubscriptionInfo clientSubscriptionInfo2 = new ClientSubscriptionInfo(); - clientSubscriptionInfo2.setSubscriptionKey("mykey2"); - clientSubscriptionInfo2.setFromClerk(clerk2); - saveClientSubscriptionInfo.getClientSubscriptionInfo().add(clientSubscriptionInfo2); - - try { - - NodeDetail nodeDetail = publisher.saveNode(saveNode); - ClerkDetail clerkDetail = publisher.saveClerk(saveClerk); - Assert.assertEquals(2,nodeDetail.getNode().size()); - Assert.assertEquals(2,clerkDetail.getClerk().size()); - - ClientSubscriptionInfoDetail detail = publisher.saveClientSubscriptionInfo(saveClientSubscriptionInfo); - Assert.assertEquals("mykey", detail.getClientSubscriptionInfo().get(0).getSubscriptionKey()); - - //GetClientSubscriptionInfoDetail getDetail = new GetClientSubscriptionInfoDetail(); - //getDetail.setAuthInfo(authInfoJoe); - //getDetail.getClientSubscriptionKey().add("mykey"); - Listkeys = new ArrayList(); - keys.add("mykey"); - GetClientSubscriptionInfoDetail req = new GetClientSubscriptionInfoDetail(); - req.setAuthInfo(authInfoJoe); - req.getClientSubscriptionKey().addAll(keys); - ClientSubscriptionInfoDetail detail2 = publisher.getClientSubscriptionInfoDetail(req); - Assert.assertEquals("mykey", detail2.getClientSubscriptionInfo().get(0).getSubscriptionKey()); - - DeleteClientSubscriptionInfo deleteInfo = new DeleteClientSubscriptionInfo(); - deleteInfo.setAuthInfo(authInfoJoe); - deleteInfo.getSubscriptionKey().add("mykey"); - publisher.deleteClientSubscriptionInfo(deleteInfo); - - try { - @SuppressWarnings("unused") - - ClientSubscriptionInfoDetail detail3 = publisher.getClientSubscriptionInfoDetail(req); - Assert.fail("We're expecting an InvalidKeyPassedException"); - } catch (Exception e) { - Assert.assertEquals(InvalidKeyPassedException.class, e.getClass()); - } - } catch(Exception e) { - logger.error(e.getMessage(), e); - Assert.fail("No exception should be thrown"); - } - } - - - - @Test(expected = ValueNotAllowedException.class) - public void addNodeInvalidProxy() throws Exception { - - Node node = new Node(); - node.setSecurityUrl("http://localhost:8080/services/securityUrl"); - node.setCustodyTransferUrl("http://localhost:8080/services/securityUrl"); - node.setDescription("description"); - node.setInquiryUrl("http://localhost:8080/services/securityUrl"); - node.setPublishUrl("http://localhost:8080/services/publishUrl"); - node.setSubscriptionListenerUrl("http://localhost:8080/services/subUrladdClientSubscriptionInfo"); - node.setProxyTransport("orgasdasdasdasd.apache.juddi.v3.client.transport.JAXWSTransport"); - node.setSubscriptionUrl("http://localhost:8080/services/securityUrl"); - node.setName("default"); - node.setClientName("defaultClient"); - SaveNode saveNode = new SaveNode(); - saveNode.setAuthInfo(authInfoJoe); - saveNode.getNode().add(node); - - NodeDetail nodeDetail = publisher.saveNode(saveNode); - Assert.fail(); - - - } - -} +/* + * Copyright 2001-2009 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.rmi.RemoteException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.Registry; +import org.apache.juddi.api_v3.Clerk; +import org.apache.juddi.api_v3.ClerkDetail; +import org.apache.juddi.api_v3.ClientSubscriptionInfo; +import org.apache.juddi.api_v3.ClientSubscriptionInfoDetail; +import org.apache.juddi.api_v3.DeleteClientSubscriptionInfo; +import org.apache.juddi.api_v3.GetClientSubscriptionInfoDetail; +import org.apache.juddi.api_v3.Node; +import org.apache.juddi.api_v3.NodeDetail; +import org.apache.juddi.api_v3.SaveClerk; +import org.apache.juddi.api_v3.SaveClientSubscriptionInfo; +import org.apache.juddi.api_v3.SaveNode; +import org.apache.juddi.v3.error.InvalidKeyPassedException; +import org.apache.juddi.v3.error.ValueNotAllowedException; +import org.apache.juddi.v3.tck.TckPublisher; +import org.apache.juddi.v3.tck.TckSecurity; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.v3_service.UDDISecurityPortType; + +/** + * @author Kurt T Stam + */ +public class API_100_ClientSubscriptionInfoTest { + + private JUDDIApiImpl publisher = new JUDDIApiImpl(); + private static Log logger = LogFactory.getLog(API_100_ClientSubscriptionInfoTest.class); + private static API_010_PublisherTest api010 = new API_010_PublisherTest(); + private static String authInfoJoe = null; + + @BeforeClass + public static void setup() throws ConfigurationException, RemoteException { + Registry.start(); + logger.debug("Getting auth tokens.."); + try { + api010.saveJoePublisher(); + UDDISecurityPortType security = new UDDISecurityImpl(); + authInfoJoe = TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); + } catch (DispositionReportFaultMessage e) { + logger.error(e.getMessage(), e); + Assert.fail("Could not obtain authInfo token."); + } + } + + @AfterClass + public static void stopRegistry() throws ConfigurationException { + Registry.stop(); + } + + @Test + public void addClientSubscriptionInfo() { + ClientSubscriptionInfo clientSubscriptionInfo = new ClientSubscriptionInfo(); + + Node node = new Node(); + node.setSecurityUrl("http://localhost:8080/services/securityUrl"); + node.setCustodyTransferUrl("http://localhost:8080/services/securityUrl"); + node.setDescription("description"); + node.setInquiryUrl("http://localhost:8080/services/securityUrl"); + node.setPublishUrl("http://localhost:8080/services/publishUrl"); + node.setSubscriptionListenerUrl("http://localhost:8080/services/subUrladdClientSubscriptionInfo"); + node.setProxyTransport("org.apache.juddi.v3.client.transport.JAXWSTransport"); + node.setSubscriptionUrl("http://localhost:8080/services/securityUrl"); + node.setName("default"); + node.setClientName("defaultClient"); + SaveNode saveNode = new SaveNode(); + saveNode.setAuthInfo(authInfoJoe); + saveNode.getNode().add(node); + + Clerk clerk = new Clerk(); + clerk.setName("clerkName"); + clerk.setPublisher("root"); + clerk.setNode(node); + SaveClerk saveClerk = new SaveClerk(); + saveClerk.setAuthInfo(authInfoJoe); + saveClerk.getClerk().add(clerk); + + clientSubscriptionInfo.setFromClerk(clerk); + + Node node2 = new Node(); + node2.setSecurityUrl("http://localhost:8080/services/securityUrl2"); + node2.setCustodyTransferUrl("https://localhost:8080/services/securityUrl2"); + node2.setDescription("description2"); + node2.setInquiryUrl("http://localhost:8080/services/securityUrl2"); + node2.setPublishUrl("http://localhost:8080/services/securityUrl2"); + node2.setProxyTransport("org.apache.juddi.v3.client.transport.JAXWSTransport"); + node2.setSubscriptionUrl("http://localhost:8080/services/securityUrl2"); + node2.setSubscriptionListenerUrl("http://localhost:8080/services/securityUrl2"); + node2.setName("default2"); + node2.setClientName("default2Client"); + saveNode.getNode().add(node2); + + Clerk clerk2 = new Clerk(); + clerk2.setName("clerkName2"); + clerk2.setPublisher("root"); + clerk2.setNode(node2); + saveClerk.getClerk().add(clerk2); + + clientSubscriptionInfo.setFromClerk(clerk); + + clientSubscriptionInfo.setSubscriptionKey("mykey"); + + SaveClientSubscriptionInfo saveClientSubscriptionInfo = new SaveClientSubscriptionInfo(); + saveClientSubscriptionInfo.setAuthInfo(authInfoJoe); + saveClientSubscriptionInfo.getClientSubscriptionInfo().add(clientSubscriptionInfo); + + ClientSubscriptionInfo clientSubscriptionInfo2 = new ClientSubscriptionInfo(); + clientSubscriptionInfo2.setSubscriptionKey("mykey2"); + clientSubscriptionInfo2.setFromClerk(clerk2); + saveClientSubscriptionInfo.getClientSubscriptionInfo().add(clientSubscriptionInfo2); + + try { + + NodeDetail nodeDetail = publisher.saveNode(saveNode); + ClerkDetail clerkDetail = publisher.saveClerk(saveClerk); + Assert.assertEquals(2,nodeDetail.getNode().size()); + Assert.assertEquals(2,clerkDetail.getClerk().size()); + + ClientSubscriptionInfoDetail detail = publisher.saveClientSubscriptionInfo(saveClientSubscriptionInfo); + Assert.assertEquals("mykey", detail.getClientSubscriptionInfo().get(0).getSubscriptionKey()); + + //GetClientSubscriptionInfoDetail getDetail = new GetClientSubscriptionInfoDetail(); + //getDetail.setAuthInfo(authInfoJoe); + //getDetail.getClientSubscriptionKey().add("mykey"); + Listkeys = new ArrayList(); + keys.add("mykey"); + GetClientSubscriptionInfoDetail req = new GetClientSubscriptionInfoDetail(); + req.setAuthInfo(authInfoJoe); + req.getClientSubscriptionKey().addAll(keys); + ClientSubscriptionInfoDetail detail2 = publisher.getClientSubscriptionInfoDetail(req); + Assert.assertEquals("mykey", detail2.getClientSubscriptionInfo().get(0).getSubscriptionKey()); + + DeleteClientSubscriptionInfo deleteInfo = new DeleteClientSubscriptionInfo(); + deleteInfo.setAuthInfo(authInfoJoe); + deleteInfo.getSubscriptionKey().add("mykey"); + publisher.deleteClientSubscriptionInfo(deleteInfo); + + try { + @SuppressWarnings("unused") + + ClientSubscriptionInfoDetail detail3 = publisher.getClientSubscriptionInfoDetail(req); + Assert.fail("We're expecting an InvalidKeyPassedException"); + } catch (Exception e) { + Assert.assertEquals(InvalidKeyPassedException.class, e.getClass()); + } + } catch(Exception e) { + logger.error(e.getMessage(), e); + Assert.fail("No exception should be thrown"); + } + } + + + + @Test(expected = ValueNotAllowedException.class) + public void addNodeInvalidProxy() throws Exception { + + Node node = new Node(); + node.setSecurityUrl("http://localhost:8080/services/securityUrl"); + node.setCustodyTransferUrl("http://localhost:8080/services/securityUrl"); + node.setDescription("description"); + node.setInquiryUrl("http://localhost:8080/services/securityUrl"); + node.setPublishUrl("http://localhost:8080/services/publishUrl"); + node.setSubscriptionListenerUrl("http://localhost:8080/services/subUrladdClientSubscriptionInfo"); + node.setProxyTransport("orgasdasdasdasd.apache.juddi.v3.client.transport.JAXWSTransport"); + node.setSubscriptionUrl("http://localhost:8080/services/securityUrl"); + node.setName("default"); + node.setClientName("defaultClient"); + SaveNode saveNode = new SaveNode(); + saveNode.setAuthInfo(authInfoJoe); + saveNode.getNode().add(node); + + NodeDetail nodeDetail = publisher.saveNode(saveNode); + Assert.fail(); + + + } + +} diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_110_FindBusinessTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_110_FindBusinessTest.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/API_110_FindBusinessTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_110_FindBusinessTest.java diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_120_CombineCategoryBagsFindServiceTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_120_CombineCategoryBagsFindServiceTest.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/API_120_CombineCategoryBagsFindServiceTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_120_CombineCategoryBagsFindServiceTest.java diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_130_CombineCategoryBagsFindBusinessTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_130_CombineCategoryBagsFindBusinessTest.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/API_130_CombineCategoryBagsFindBusinessTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_130_CombineCategoryBagsFindBusinessTest.java diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_140_NegativePublicationTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_140_NegativePublicationTest.java similarity index 97% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/API_140_NegativePublicationTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_140_NegativePublicationTest.java index 803a1e3f3..4b3d28adc 100644 --- a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_140_NegativePublicationTest.java +++ b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_140_NegativePublicationTest.java @@ -1,2444 +1,2444 @@ -/* - * Copyright 2001-2009 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.rmi.RemoteException; -import java.util.List; -import java.util.UUID; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.Registry; -import org.apache.juddi.api_v3.AccessPointType; -import org.apache.juddi.v3.error.InvalidKeyPassedException; -import org.apache.juddi.v3.error.ValueNotAllowedException; -import org.apache.juddi.v3.tck.TckPublisher; -import org.apache.juddi.v3.tck.TckSecurity; -import org.apache.juddi.v3.tck.TckTModel; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.uddi.api_v3.AccessPoint; -import org.uddi.api_v3.Address; -import org.uddi.api_v3.AddressLine; -import org.uddi.api_v3.BindingTemplate; -import org.uddi.api_v3.BindingTemplates; -import org.uddi.api_v3.BusinessDetail; -import org.uddi.api_v3.BusinessEntity; -import org.uddi.api_v3.BusinessInfos; -import org.uddi.api_v3.BusinessService; -import org.uddi.api_v3.BusinessServices; -import org.uddi.api_v3.CategoryBag; -import org.uddi.api_v3.Contact; -import org.uddi.api_v3.Contacts; -import org.uddi.api_v3.DeleteBusiness; -import org.uddi.api_v3.DeleteTModel; -import org.uddi.api_v3.Description; -import org.uddi.api_v3.DiscoveryURL; -import org.uddi.api_v3.DiscoveryURLs; -import org.uddi.api_v3.Email; -import org.uddi.api_v3.HostingRedirector; -import org.uddi.api_v3.KeyedReference; -import org.uddi.api_v3.Name; -import org.uddi.api_v3.PersonName; -import org.uddi.api_v3.Phone; -import org.uddi.api_v3.SaveBusiness; -import org.uddi.api_v3.SaveTModel; -import org.uddi.api_v3.ServiceInfos; -import org.uddi.api_v3.TModel; -import org.uddi.api_v3.TModelDetail; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.v3_service.UDDIInquiryPortType; -import org.uddi.v3_service.UDDIPublicationPortType; -import org.uddi.v3_service.UDDISecurityPortType; - -/** - * The Negative Publication tests validates adherence to UDDI's string - * validations, max lengths, null values (and more) by sending bogus requests to - * a Publication endpoint. Tests that succeed or return stack traces are - * actually failing test cases - * - * This is incomplete. items left to test: all service related entries, - * including binding templates business/contact/useType business/contact/address - * amd addressLine business/catgag, ident bag - * - * @author Alex O'Ree - */ -public class API_140_NegativePublicationTest { - - private static Log logger = LogFactory.getLog(API_140_NegativePublicationTest.class); - static UDDISecurityPortType security = new UDDISecurityImpl(); - static UDDIInquiryPortType inquiry = new UDDIInquiryImpl(); - static UDDIPublicationPortType publication = new UDDIPublicationImpl(); - static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - - protected static String authInfoJoe = null; - protected static String authInfoSam = null; - static final String str256 = "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"; - static final String str255 = "uddi:tmodelkey:categories:1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"; - static final String strkey256 = "uddi:tmodelkey:categories:11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"; - static final String strkey256_1 = "uddi:org.apache:omething.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.somethi.com"; - static final String str26 = "11111111111111111111111111"; - static final String str27 = "111111111111111111111111110"; - static final String str10 = "0123456789"; - static final String str11 = "01234567890"; - static final String str80 = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; - static final String str81 = "012345678901234567890123456789012345678901234567890123456789012345678901234567891"; - static final String TRANS = "rolled back"; - static final String str4096 = "12345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000XXXXXXXX"; - static final String str4097 = "12345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000XXXXXXXXZ"; - static final String str51 = "111111111111111111111111111111111111111111111111111"; - static final String str50 = "11111111111111111111111111111111111111111111111111"; - static final String MISSING_RESOURCE = "Can't find resource for bundle"; - - @AfterClass - public static void stopManager() throws ConfigurationException { - Registry.stop(); - } - - @BeforeClass - public static void startManager() throws ConfigurationException { - Registry.start(); - - logger.debug("Getting auth tokens.."); - try { - authInfoJoe = TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); - authInfoSam = TckSecurity.getAuthToken(security, TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword()); - Assert.assertNotNull(authInfoJoe); - Assert.assertNotNull(authInfoSam); - String authInfoUDDI = TckSecurity.getAuthToken(security, TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword()); - tckTModel.saveUDDIPublisherTmodel(authInfoUDDI); - tckTModel.saveTModels(authInfoUDDI, TckTModel.TMODELS_XML); - tckTModel.saveJoePublisherTmodel(authInfoJoe); - } catch (Exception e) { - logger.error(e.getMessage(), e); - Assert.fail("Could not obtain authInfo token."); - } - } - - static void HandleException(Exception ex) { - if (logger.isDebugEnabled()) { - System.err.println("Error caught of type " + ex.getClass().getCanonicalName()); - ex.printStackTrace(); - } - Assert.assertFalse(ex.getMessage().toLowerCase().contains(TRANS.toLowerCase())); - Assert.assertFalse(ex.getMessage().toLowerCase().contains(MISSING_RESOURCE.toLowerCase())); - if (! (ex instanceof ValueNotAllowedException)) { - Assert.fail(); - } - } - - // - @Test - public void BusinessNameSanityTest() { - System.out.println("BusinessNameSanityTest"); - } - - @Test(expected = ValueNotAllowedException.class) - public void BusinessKeyTooLongTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BusinessKeyTooLongTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("Hello Nurse"); - be.getName().add(n); - be.setBusinessKey(strkey256_1); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test(expected = ValueNotAllowedException.class) - public void BusinessNameTooShortTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BusinessNameTooShortTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue(""); - be.getName().add(n); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test - public void BusinessNameMinLengthTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BusinessNameMinLengthTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("1"); - be.getName().add(n); - sb.getBusinessEntity().add(be); - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - } - - @Test(expected = ValueNotAllowedException.class) - public void BusinessNameTooLongTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BusinessNameTooLongTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - //256 chars - n.setValue(str256); - be.getName().add(n); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - - } - - @Test - public void BusinessNameMaxLengthTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BusinessNameMaxLengthTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - //255 chars - n.setValue(str255); - be.getName().add(n); - sb.getBusinessEntity().add(be); - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - } - - @Test(expected = ValueNotAllowedException.class) - public void BusinessNameLangTooLongTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BusinessNameLangTooLongTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - - n.setValue("A Test business"); - //27 - n.setLang(str27); - be.getName().add(n); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - - } - - @Test - public void BusinessNameLangMaxLengthTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BusinessNameLangMaxLengthTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - - n.setValue("A Test business"); - n.setLang(str26); - - be.getName().add(n); - sb.getBusinessEntity().add(be); - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - } - - @Test(expected = ValueNotAllowedException.class) - public void BusinessDescriptionLangTooLongTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BusinessDescriptionLangTooLongTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - - n.setValue("A Test business"); - Description d = new Description(); - d.setValue("a description"); - //27 - d.setLang(str27); - be.getName().add(n); - be.getDescription().add(d); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - - } - - @Test - public void BusinessDescriptionLangMaxLengthTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BusinessDescriptionLangMaxLengthTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - - n.setValue("A Test business"); - Description d = new Description(); - d.setValue("a description"); - //26 - d.setLang(str26); - be.getDescription().add(d); - be.getName().add(n); - sb.getBusinessEntity().add(be); - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - } - - @Test - public void BusinessDescriptionMaxLengthTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BusinessDescriptionMaxLengthTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - - n.setValue("A Test business"); - Description d = new Description(); - d.setValue(str255); - be.getDescription().add(d); - be.getName().add(n); - sb.getBusinessEntity().add(be); - - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - } - - @Test(expected = ValueNotAllowedException.class) - public void BusinessDescriptionTooLongLengthTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BusinessDescriptionTooLongLengthTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - - n.setValue("A Test business"); - Description d = new Description(); - d.setValue(str256); - be.getDescription().add(d); - be.getName().add(n); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - - } - - @Test(expected = ValueNotAllowedException.class) - public void BusinessDiscoveryURLTooLongTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BusinessDiscoveryURLTooLongTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - - n.setValue("A Test business"); - be.getName().add(n); - be.setDiscoveryURLs(new DiscoveryURLs()); - DiscoveryURL d = new DiscoveryURL(); - d.setValue(str4097); - be.getDiscoveryURLs().getDiscoveryURL().add(d); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - - } - - @Test - public void BusinessDiscoveryURLMaxLengthTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BusinessDiscoveryURLMaxLengthTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - - n.setValue("A Test business"); - be.getName().add(n); - be.setDiscoveryURLs(new DiscoveryURLs()); - DiscoveryURL d = new DiscoveryURL(); - d.setValue(str4096); - be.getDiscoveryURLs().getDiscoveryURL().add(d); - sb.getBusinessEntity().add(be); - - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - } - - @Test - public void BusinessDiscoveryURLMaxLengthMaxUseTypeTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BusinessDiscoveryURLMaxLengthMaxUseTypeTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - - n.setValue("A Test business"); - be.getName().add(n); - be.setDiscoveryURLs(new DiscoveryURLs()); - DiscoveryURL d = new DiscoveryURL(); - d.setValue(str4096); - d.setUseType(str255); - be.getDiscoveryURLs().getDiscoveryURL().add(d); - sb.getBusinessEntity().add(be); - - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - } - - @Test(expected = ValueNotAllowedException.class) - public void BusinessDiscoveryURLMaxLengthToolongUseTypeTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BusinessDiscoveryURLMaxLengthToolongUseTypeTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - - n.setValue("A Test business"); - be.getName().add(n); - be.setDiscoveryURLs(new DiscoveryURLs()); - DiscoveryURL d = new DiscoveryURL(); - d.setValue(str4096); - d.setUseType(str256); - be.getDiscoveryURLs().getDiscoveryURL().add(d); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test - public void ContactMaxEmailMaxUseTypeTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ContactMaxEmailMaxUseTypeTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setContacts(ContactMaxEmailMaxUseType()); - sb.getBusinessEntity().add(be); - - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - } - - private Contacts ContactMaxEmailMaxUseType() { - Contacts cc = new Contacts(); - Contact c = new Contact(); - PersonName n = new PersonName(); - n.setValue("Bob"); - c.getPersonName().add(n); - Email m = new Email(); - m.setValue(str255); - m.setUseType(str255); - c.getEmail().add(m); - cc.getContact().add(c);; - return cc; - } - - private Contacts ContactTooLongEmailMaxUseType() { - Contacts cc = new Contacts(); - Contact c = new Contact(); - PersonName n = new PersonName(); - n.setValue("Bob"); - c.getPersonName().add(n); - Email m = new Email(); - m.setValue(str256); - m.setUseType(str255); - c.getEmail().add(m); - cc.getContact().add(c);; - return cc; - } - - private Contacts ContactEmailUseTypeToolong() { - Contacts cc = new Contacts(); - Contact c = new Contact(); - PersonName n = new PersonName(); - n.setValue("Bob"); - c.getPersonName().add(n); - Email m = new Email(); - m.setValue(str255); - m.setUseType(str256); - c.getEmail().add(m); - cc.getContact().add(c);; - return cc; - } - - private Contacts ContactMaxDescription() { - Contacts cc = new Contacts(); - Contact c = new Contact(); - PersonName n = new PersonName(); - n.setValue("Bob"); - c.getPersonName().add(n); - Email m = new Email(); - m.setValue(str255); - m.setUseType(str255); - c.getEmail().add(m); - Description d = new Description(); - d.setLang(str26); - d.setValue(str255); - c.getDescription().add(d); - cc.getContact().add(c);; - return cc; - } - - private Contacts ContactDescriptionTooLong() { - Contacts cc = new Contacts(); - Contact c = new Contact(); - PersonName n = new PersonName(); - n.setValue("Bob"); - c.getPersonName().add(n); - Email m = new Email(); - m.setValue(str255); - m.setUseType(str255); - c.getEmail().add(m); - Description d = new Description(); - d.setLang(str256); - d.setValue(str26); - c.getDescription().add(d); - cc.getContact().add(c);; - return cc; - } - - private Contacts ContactPhoneTooLong() { - Contacts cc = new Contacts(); - Contact c = new Contact(); - PersonName n = new PersonName(); - n.setValue("Bob"); - c.getPersonName().add(n); - Phone p = new Phone(); - p.setValue(str51); - c.getPhone().add(p); - cc.getContact().add(c);; - return cc; - } - - private Contacts ContactPhoneUseTypeTooLong() { - Contacts cc = new Contacts(); - Contact c = new Contact(); - PersonName n = new PersonName(); - n.setValue("Bob"); - c.getPersonName().add(n); - Phone p = new Phone(); - p.setValue(str50); - p.setUseType(str256); - c.getPhone().add(p); - cc.getContact().add(c);; - return cc; - } - - private Contacts ContactPhoneUseTypeMaxLen() { - Contacts cc = new Contacts(); - Contact c = new Contact(); - PersonName n = new PersonName(); - n.setValue("Bob"); - c.getPersonName().add(n); - Phone p = new Phone(); - p.setValue(str50); - p.setUseType(str255); - c.getPhone().add(p); - cc.getContact().add(c);; - return cc; - } - - private Contacts ContactPhoneMaxLength() { - Contacts cc = new Contacts(); - Contact c = new Contact(); - PersonName n = new PersonName(); - n.setValue("Bob"); - c.getPersonName().add(n); - Phone p = new Phone(); - p.setValue(str50); - c.getPhone().add(p); - cc.getContact().add(c);; - return cc; - } - - private Contacts ContactAddressAllMax(boolean oversizedLang, boolean oversizedTmodel, boolean oversizedSortCode, boolean oversizedUseType, - boolean oversizedAddressLineValue, boolean oversizedAddressKN, boolean oversizedAddressKV) { - Contacts cc = new Contacts(); - Contact c = new Contact(); - PersonName n = new PersonName(); - n.setValue("Bob"); - c.getPersonName().add(n); - - cc.getContact().add(c); - Address a = new Address(); - if (oversizedSortCode) { - a.setSortCode(str11); - } else { - a.setSortCode(str10); - } - if (oversizedLang) { - a.setLang(str27); - } else { - a.setLang(str26); - } - if (oversizedTmodel) { - a.setTModelKey(str256); - } else { - a.setTModelKey(str255); - } - if (oversizedUseType) { - a.setUseType(str256); - } else { - a.setUseType(str255); - } - if (oversizedSortCode) { - a.setSortCode(str11); - } else { - a.setSortCode(str10); - } - AddressLine al = new AddressLine(); - if (oversizedAddressKN) { - al.setKeyName(str256); //optional - } else { - al.setKeyName(str255); //optional - } - if (oversizedAddressKV) { - al.setKeyValue(str256); //optional - } else { - al.setKeyValue(str255); //optional - } - if (oversizedAddressLineValue) { - al.setValue(str81); //this one is required - } else { - al.setValue(str80); - } - a.getAddressLine().add(al); - c.getAddress().add(a); - return cc; - } - - private Contacts ContactDescriptionLangTooLong() { - Contacts cc = new Contacts(); - Contact c = new Contact(); - PersonName n = new PersonName(); - n.setValue("Bob"); - c.getPersonName().add(n); - Email m = new Email(); - m.setValue(str255); - m.setUseType(str255); - c.getEmail().add(m); - Description d = new Description(); - d.setLang(str255); - d.setValue(str27); - c.getDescription().add(d); - cc.getContact().add(c); - return cc; - } - - @Test(expected = ValueNotAllowedException.class) - public void ContactTooLongEmailMaxUseTypeTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ContactTooLongEmailMaxUseTypeTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setContacts(ContactTooLongEmailMaxUseType()); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test(expected = ValueNotAllowedException.class) - public void ContactMaxEmailToolongUseTypeTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ContactMaxEmailToolongUseTypeTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - - be.setContacts(ContactEmailUseTypeToolong()); - - - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test - public void ContactDescriptionMaxLangMaxtest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ContactDescriptionMaxLangMaxtest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setContacts(ContactMaxDescription()); - sb.getBusinessEntity().add(be); - - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - - } - - @Test (expected = ValueNotAllowedException.class) - public void ContactDescriptionTooLongtest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ContactDescriptionTooLongtest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setContacts(ContactDescriptionTooLong()); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test (expected = ValueNotAllowedException.class) - public void ContactDescriptionLangTooLongTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ContactDescriptionLangTooLongTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setContacts(ContactDescriptionLangTooLong()); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test - public void ContactPhoneMaxLentest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ContactPhoneMaxLentest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setContacts(ContactPhoneMaxLength()); - sb.getBusinessEntity().add(be); - - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - - } - - @Test(expected=ValueNotAllowedException.class) - public void ContactPhoneTooLongtest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ContactPhoneTooLongtest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setContacts(ContactPhoneTooLong()); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test - public void ContactPhoneMaxLongtest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ContactPhoneMaxLongtest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setContacts(ContactPhoneMaxLength()); - sb.getBusinessEntity().add(be); - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - } - - @Test - public void ContactPhoneMaxLongMaxUseTypetest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ContactPhoneMaxLongMaxUseTypetest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setContacts(ContactPhoneUseTypeMaxLen()); - sb.getBusinessEntity().add(be); - - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - } - - @Test(expected = ValueNotAllowedException.class) - public void ContactPhoneUseTypeTooLongtest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ContactPhoneUseTypeTooLongtest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setContacts(ContactPhoneUseTypeTooLong()); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test - public void ContactMaxAddressFFFFFFFtest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ContactMaxAddressFFFFFFFtest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setContacts(ContactAddressAllMax(false, false, false, false, false, false, false)); - sb.getBusinessEntity().add(be); - - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - - } - - @Test(expected=ValueNotAllowedException.class) - public void ContactMaxAddressTFFFFFFtest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ContactMaxAddressTFFFFFFtest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setContacts(ContactAddressAllMax(true, false, false, false, false, false, false)); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test(expected=ValueNotAllowedException.class) - public void ContactMaxAddressFTFFFFFtest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ContactMaxAddressFTFFFFFtest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setContacts(ContactAddressAllMax(false, true, false, false, false, false, false)); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test(expected=ValueNotAllowedException.class) - public void ContactMaxAddressFFTFFFFtest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ContactMaxAddressFFTFFFFtest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setContacts(ContactAddressAllMax(false, false, true, false, false, false, false)); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test(expected=ValueNotAllowedException.class) - public void ContactMaxAddressFFFTFFFtest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ContactMaxAddressFFFTFFFtest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setContacts(ContactAddressAllMax(false, false, false, true, false, false, false)); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test(expected=ValueNotAllowedException.class) - public void ContactMaxAddressFFFFTFFtest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ContactMaxAddressFFFFTFFtest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setContacts(ContactAddressAllMax(false, false, false, false, true, false, false)); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test(expected=ValueNotAllowedException.class) - public void ContactMaxAddressFFFFFTFtest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ContactMaxAddressFFFFFTFtest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setContacts(ContactAddressAllMax(false, false, false, false, false, true, false)); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test(expected=ValueNotAllowedException.class) - public void ContactMaxAddressFFFFFFTtest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ContactMaxAddressFFFFFFTtest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setContacts(ContactAddressAllMax(false, false, false, false, false, false, true)); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test - public void KeyReferenceMax() throws DispositionReportFaultMessage, RemoteException { - System.out.println("KeyReferenceMax"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setCategoryBag(new CategoryBag()); - KeyedReference kr = new KeyedReference(); - kr.setKeyName(str255); - kr.setKeyValue(str255); - kr.setTModelKey(str255); - be.getCategoryBag().getKeyedReference().add(kr); - sb.getBusinessEntity().add(be); - - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - } - - @Test(expected=ValueNotAllowedException.class) - public void KeyReferenceKeyTooLong() throws DispositionReportFaultMessage, RemoteException { - System.out.println("KeyReferenceKeyTooLong"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setCategoryBag(new CategoryBag()); - KeyedReference kr = new KeyedReference(); - kr.setKeyName(str255); - kr.setKeyValue(str255); - kr.setTModelKey(str256); - be.getCategoryBag().getKeyedReference().add(kr); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test(expected=ValueNotAllowedException.class) - public void KeyReferenceNameTooLong() throws DispositionReportFaultMessage, RemoteException { - System.out.println("KeyReferenceNameTooLong"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setCategoryBag(new CategoryBag()); - KeyedReference kr = new KeyedReference(); - kr.setKeyName(str256); - kr.setKeyValue(str255); - kr.setTModelKey(str255); - be.getCategoryBag().getKeyedReference().add(kr); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test(expected=ValueNotAllowedException.class) - public void KeyReferenceValueTooLong() throws DispositionReportFaultMessage, RemoteException { - System.out.println("KeyReferenceValueTooLong"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setCategoryBag(new CategoryBag()); - KeyedReference kr = new KeyedReference(); - kr.setKeyName(str255); - kr.setKeyValue(str256); - kr.setTModelKey(str255); - be.getCategoryBag().getKeyedReference().add(kr); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test(expected=ValueNotAllowedException.class) - public void ServiceNameTooLongTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ServiceNameTooLongTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setBusinessServices(new BusinessServices()); - BusinessService bs = new BusinessService(); - n = new Name(); - n.setValue(str256); - bs.getName().add(n); - be.getBusinessServices().getBusinessService().add(bs); - - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test - public void ServiceNameMaxLenTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ServiceNameMaxLenTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setBusinessServices(new BusinessServices()); - BusinessService bs = new BusinessService(); - n = new Name(); - n.setValue(str255); - bs.getName().add(n); - be.getBusinessServices().getBusinessService().add(bs); - - sb.getBusinessEntity().add(be); - - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - } - - @Test - public void ServiceNameMaxLangLenTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ServiceNameMaxLangLenTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setBusinessServices(new BusinessServices()); - BusinessService bs = new BusinessService(); - n = new Name(); - n.setValue(str255); - n.setLang(str26); - bs.getName().add(n); - be.getBusinessServices().getBusinessService().add(bs); - - sb.getBusinessEntity().add(be); - - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - } - - @Test(expected=ValueNotAllowedException.class) - public void ServiceNameTooLongLangTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ServiceNameTooLongLangTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setBusinessServices(new BusinessServices()); - BusinessService bs = new BusinessService(); - n = new Name(); - n.setValue(str255); - n.setLang(str27); - bs.getName().add(n); - be.getBusinessServices().getBusinessService().add(bs); - - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test(expected=ValueNotAllowedException.class) - public void ServiceDescTooLongTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ServiceDescTooLongTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setBusinessServices(new BusinessServices()); - BusinessService bs = new BusinessService(); - Description d = new Description(); - d.setValue(str256); - bs.getDescription().add(d); - n = new Name(); - n.setValue(str255); - bs.getName().add(n); - be.getBusinessServices().getBusinessService().add(bs); - - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test(expected=ValueNotAllowedException.class) - public void ServiceDescLangTooLongTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ServiceDescLangTooLongTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setBusinessServices(new BusinessServices()); - BusinessService bs = new BusinessService(); - Description d = new Description(); - d.setValue(str255); - d.setLang(str27); - bs.getDescription().add(d); - n = new Name(); - n.setValue(str255); - bs.getName().add(n); - be.getBusinessServices().getBusinessService().add(bs); - - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test - public void ServiceDescMaxLangTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ServiceDescMaxLangTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setBusinessServices(new BusinessServices()); - BusinessService bs = new BusinessService(); - Description d = new Description(); - d.setValue(str255); - d.setLang(str26); - bs.getDescription().add(d); - n = new Name(); - n.setValue(str255); - bs.getName().add(n); - be.getBusinessServices().getBusinessService().add(bs); - - sb.getBusinessEntity().add(be); - - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - - } - - @Test - public void ServiceMaxCatBagTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ServiceDescMaxLangTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setBusinessServices(new BusinessServices()); - BusinessService bs = new BusinessService(); - Description d = new Description(); - d.setValue(str255); - d.setLang(str26); - bs.getDescription().add(d); - n = new Name(); - n.setValue(str255); - bs.getName().add(n); - bs.setCategoryBag(new CategoryBag()); - KeyedReference kr = new KeyedReference(); - kr.setKeyName(str255); - kr.setKeyValue(str255); - kr.setTModelKey(str255); - bs.getCategoryBag().getKeyedReference().add(kr); - be.getBusinessServices().getBusinessService().add(bs); - - sb.getBusinessEntity().add(be); - - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - } - - @Test(expected=ValueNotAllowedException.class) - public void ServiceMaxCatBagTooBigTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("ServiceMaxCatBagTooBigTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setBusinessServices(new BusinessServices()); - BusinessService bs = new BusinessService(); - Description d = new Description(); - d.setValue(str255); - d.setLang(str26); - bs.getDescription().add(d); - n = new Name(); - n.setValue(str255); - bs.getName().add(n); - bs.setCategoryBag(new CategoryBag()); - KeyedReference kr = new KeyedReference(); - kr.setKeyName(str256); - kr.setKeyValue(str256); - kr.setTModelKey(str256); - bs.getCategoryBag().getKeyedReference().add(kr); - be.getBusinessServices().getBusinessService().add(bs); - - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test(expected=ValueNotAllowedException.class) - public void BindingTemplateNoAccessPointTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BindingTemplateNoAccessPointTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setBusinessServices(new BusinessServices()); - BusinessService bs = new BusinessService(); - - n = new Name(); - n.setValue(str255); - bs.getName().add(n); - BindingTemplate bt = new BindingTemplate(); - bs.setBindingTemplates(new BindingTemplates()); - bs.getBindingTemplates().getBindingTemplate().add(bt); - - be.getBusinessServices().getBusinessService().add(bs); - - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test - public void BindingTemplateAccessPointMaxUseTypeTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BindingTemplateAccessPointMaxUseTypeTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setBusinessServices(new BusinessServices()); - BusinessService bs = new BusinessService(); - - n = new Name(); - n.setValue(str255); - bs.getName().add(n); - BindingTemplate bt = new BindingTemplate(); - bs.setBindingTemplates(new BindingTemplates()); - AccessPoint ap = new AccessPoint(); - ap.setUseType(str255); - ap.setValue("http://localhost"); - bt.setAccessPoint(ap); - bs.getBindingTemplates().getBindingTemplate().add(bt); - - be.getBusinessServices().getBusinessService().add(bs); - - sb.getBusinessEntity().add(be); - - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - } - - @Test(expected=ValueNotAllowedException.class) - public void BindingTemplateAccessPointUseTypeTooLongTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BindingTemplateAccessPointUseTypeTooLongTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setBusinessServices(new BusinessServices()); - BusinessService bs = new BusinessService(); - - n = new Name(); - n.setValue(str255); - bs.getName().add(n); - BindingTemplate bt = new BindingTemplate(); - bs.setBindingTemplates(new BindingTemplates()); - AccessPoint ap = new AccessPoint(); - ap.setUseType(str256); - ap.setValue("http://localhost"); - bt.setAccessPoint(ap); - bs.getBindingTemplates().getBindingTemplate().add(bt); - - be.getBusinessServices().getBusinessService().add(bs); - - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test(expected=ValueNotAllowedException.class) - public void BindingTemplateAccessPointValueTooLongTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BindingTemplateAccessPointValueTooLongTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setBusinessServices(new BusinessServices()); - BusinessService bs = new BusinessService(); - - n = new Name(); - n.setValue(str255); - bs.getName().add(n); - BindingTemplate bt = new BindingTemplate(); - bs.setBindingTemplates(new BindingTemplates()); - AccessPoint ap = new AccessPoint(); - ap.setUseType(str255); - ap.setValue(str4097); - bt.setAccessPoint(ap); - bs.getBindingTemplates().getBindingTemplate().add(bt); - - be.getBusinessServices().getBusinessService().add(bs); - - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test - public void BindingTemplateAccessPointMaxValueTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BindingTemplateAccessPointMaxValueTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setBusinessServices(new BusinessServices()); - BusinessService bs = new BusinessService(); - - n = new Name(); - n.setValue(str255); - bs.getName().add(n); - BindingTemplate bt = new BindingTemplate(); - bs.setBindingTemplates(new BindingTemplates()); - AccessPoint ap = new AccessPoint(); - ap.setUseType(str255); - ap.setValue(str4096); - bt.setAccessPoint(ap); - bs.getBindingTemplates().getBindingTemplate().add(bt); - - be.getBusinessServices().getBusinessService().add(bs); - - sb.getBusinessEntity().add(be); - - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - } - - @Test(expected=ValueNotAllowedException.class) - public void BindingTemplateNoAccessPointNoRedirectorTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BindingTemplateNoAccessPointNoRedirectorTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setBusinessServices(new BusinessServices()); - BusinessService bs = new BusinessService(); - - - n = new Name(); - n.setValue(str255); - bs.getName().add(n); - BindingTemplate bt = new BindingTemplate(); - bs.setBindingTemplates(new BindingTemplates()); - - bs.getBindingTemplates().getBindingTemplate().add(bt); - - be.getBusinessServices().getBusinessService().add(bs); - - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test(expected=ValueNotAllowedException.class) - public void BindingTemplateAccessPointAndRedirectorTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BindingTemplateAccessPointAndRedirectorTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setBusinessServices(new BusinessServices()); - BusinessService bs = new BusinessService(); - - n = new Name(); - n.setValue(str255); - bs.getName().add(n); - BindingTemplate bt = new BindingTemplate(); - bs.setBindingTemplates(new BindingTemplates()); - bt.setAccessPoint(new AccessPoint()); - bt.getAccessPoint().setUseType(str26); - - bt.setHostingRedirector(new HostingRedirector()); - - bt.getHostingRedirector().setBindingKey(str26); - bs.getBindingTemplates().getBindingTemplate().add(bt); - - be.getBusinessServices().getBusinessService().add(bs); - - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test - public void BindingTemplateHostRedirectorReferencalIntegritytest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BindingTemplateHostRedirectorReferencalIntegritytest"); - //TODO create a binding template, get the key, use the key as the specific redirector - String url = "http://juddi.apache.org"; - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setBusinessServices(new BusinessServices()); - BusinessService bs = new BusinessService(); - - n = new Name(); - n.setValue("A first business service"); - bs.getName().add(n); - BindingTemplate bt = new BindingTemplate(); - bs.setBindingTemplates(new BindingTemplates()); - bt.setAccessPoint(new AccessPoint()); - bt.getAccessPoint().setValue(url); - - //bt.setHostingRedirector(new HostingRedirector()); - //bt.getHostingRedirector().setBindingKey(str255); - bs.getBindingTemplates().getBindingTemplate().add(bt); - - be.getBusinessServices().getBusinessService().add(bs); - - sb.getBusinessEntity().add(be); - - System.out.println("Saving the business with the first service"); - BusinessDetail saveBusiness = publication.saveBusiness(sb); - - PrintBusinessDetails(saveBusiness.getBusinessEntity()); - - //setup the next one - bs = new BusinessService(); - n = new Name(); - n.setValue("A a redirected business service"); - bt = new BindingTemplate(); - bt.setHostingRedirector(new HostingRedirector()); - bt.getHostingRedirector().setBindingKey(saveBusiness.getBusinessEntity().get(0).getBusinessServices().getBusinessService().get(0).getBindingTemplates().getBindingTemplate().get(0).getBindingKey()); - bs.getName().add(n); - bs.setBindingTemplates(new BindingTemplates()); - bs.getBindingTemplates().getBindingTemplate().add(bt); - saveBusiness.getBusinessEntity().get(0).getBusinessServices().getBusinessService().add(bs); - - sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - sb.getBusinessEntity().add(saveBusiness.getBusinessEntity().get(0)); - - //This SHOULD be allowed - System.out.println("Saving the business with the first and second service as a host redirect"); - saveBusiness = publication.saveBusiness(sb); - PrintBusinessDetails(saveBusiness.getBusinessEntity()); - - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - } - - @Test - public void BindingTemplateAccessPointAsBindingTemplateReferencalIntegritytest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BindingTemplateAccessPointAsBindingTemplateReferencalIntegritytest"); - //create a binding template, get the key, use the key as the specific redirector - String url = "http://juddi.apache.org"; - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setBusinessServices(new BusinessServices()); - BusinessService bs = new BusinessService(); - - n = new Name(); - n.setValue("A first business service"); - bs.getName().add(n); - BindingTemplate bt = new BindingTemplate(); - bs.setBindingTemplates(new BindingTemplates()); - bt.setAccessPoint(new AccessPoint()); - bt.getAccessPoint().setValue(url); - - //bt.setHostingRedirector(new HostingRedirector()); - //bt.getHostingRedirector().setBindingKey(str255); - bs.getBindingTemplates().getBindingTemplate().add(bt); - - be.getBusinessServices().getBusinessService().add(bs); - - sb.getBusinessEntity().add(be); - System.out.println("Saving the business with the first service"); - BusinessDetail saveBusiness = publication.saveBusiness(sb); - - PrintBusinessDetails(saveBusiness.getBusinessEntity()); - - //setup the next one - bs = new BusinessService(); - n = new Name(); - n.setValue("A a redirected business service"); - bt = new BindingTemplate(); - bt.setAccessPoint(new AccessPoint()); - bt.getAccessPoint().setUseType(AccessPointType.BINDING_TEMPLATE.toString()); - bt.getAccessPoint().setValue(saveBusiness.getBusinessEntity().get(0).getBusinessServices().getBusinessService().get(0).getBindingTemplates().getBindingTemplate().get(0).getBindingKey()); - bs.getName().add(n); - bs.setBindingTemplates(new BindingTemplates()); - bs.getBindingTemplates().getBindingTemplate().add(bt); - saveBusiness.getBusinessEntity().get(0).getBusinessServices().getBusinessService().add(bs); - - sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - sb.getBusinessEntity().add(saveBusiness.getBusinessEntity().get(0)); - - //This SHOULD be allowed - System.out.println("Saving the business with the first and second service as a host redirect"); - saveBusiness = publication.saveBusiness(sb); - PrintBusinessDetails(saveBusiness.getBusinessEntity()); - - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - } - - @Test(expected=ValueNotAllowedException.class) - public void BindingTemplateAccessPointAsBindingTemplateINVALIDReferencalIntegritytest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BindingTemplateAccessPointAsBindingTemplateINVALIDReferencalIntegritytest"); - //create a binding template, get the key, use the key as the specific redirector - SaveBusiness sb; - try { - - sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - - BusinessEntity be = new BusinessEntity(); - Name bsn = new Name(); - bsn.setValue("A bogus business"); - be.getName().add(bsn); - - BusinessService bs = new BusinessService(); - Name n = new Name(); - n.setValue("A a redirected business service"); - BindingTemplate bt = new BindingTemplate(); - bt.setAccessPoint(new AccessPoint()); - bt.getAccessPoint().setUseType(AccessPointType.BINDING_TEMPLATE.toString()); - bt.getAccessPoint().setValue("uddi:" + UUID.randomUUID().toString()); - bs.getName().add(n); - bs.setBindingTemplates(new BindingTemplates()); - bs.getBindingTemplates().getBindingTemplate().add(bt); - be.setBusinessServices(new BusinessServices()); - be.getBusinessServices().getBusinessService().add(bs); - sb.getBusinessEntity().add(be); - BusinessDetail saveBusiness = publication.saveBusiness(sb); - - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test(expected=ValueNotAllowedException.class) - public void BindingTemplateHostRedirectorTooLongTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BindingTemplateHostRedirectorTooLongTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setBusinessServices(new BusinessServices()); - BusinessService bs = new BusinessService(); - - n = new Name(); - n.setValue(str255); - bs.getName().add(n); - BindingTemplate bt = new BindingTemplate(); - bs.setBindingTemplates(new BindingTemplates()); - - bt.setHostingRedirector(new HostingRedirector()); - bt.getHostingRedirector().setBindingKey(str256); - bs.getBindingTemplates().getBindingTemplate().add(bt); - - be.getBusinessServices().getBusinessService().add(bs); - - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test - public void BindingTemplateAccessPointMaxLengthTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BindingTemplateAccessPointMaxLengthTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setBusinessServices(new BusinessServices()); - BusinessService bs = new BusinessService(); - - n = new Name(); - n.setValue(str255); - bs.getName().add(n); - BindingTemplate bt = new BindingTemplate(); - bs.setBindingTemplates(new BindingTemplates()); - bt.setAccessPoint(new AccessPoint()); - bt.getAccessPoint().setValue(str4096); - - bs.getBindingTemplates().getBindingTemplate().add(bt); - - be.getBusinessServices().getBusinessService().add(bs); - - sb.getBusinessEntity().add(be); - - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - } - - @Test(expected=ValueNotAllowedException.class) - public void BindingTemplateAccessPointTooLongTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("BindingTemplateAccessPointTooLongTest"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("A Test business"); - be.getName().add(n); - be.setBusinessServices(new BusinessServices()); - BusinessService bs = new BusinessService(); - - n = new Name(); - n.setValue(str255); - bs.getName().add(n); - BindingTemplate bt = new BindingTemplate(); - - bs.setBindingTemplates(new BindingTemplates()); - bt.setAccessPoint(new AccessPoint()); - bt.getAccessPoint().setValue(str4097); - - bs.getBindingTemplates().getBindingTemplate().add(bt); - - be.getBusinessServices().getBusinessService().add(bs); - - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - publication.deleteBusiness(db); - Assert.fail("request should have been rejected"); - - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - // - static final String validTmodelKeyGenMax = "uddi:www.mycoolxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxcompany.com:keygenerator"; - static final String validTmodelKeyGenTooLong = "uddi:www.mycoolzxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxcompany.com:keygenerator"; - - //create a basic key gen - @Test - public void CreateKeyGenMaxLengthTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("CreateKeyGenMaxLengthTest"); - - SaveTModel st = new SaveTModel(); - st.setAuthInfo(authInfoJoe); - TModel tm = new TModel(); - tm.setName(new Name()); - tm.getName().setValue("My Cool Company Keymodel generator"); - tm.getName().setLang("en"); - tm.setCategoryBag(new CategoryBag()); - KeyedReference kr = new KeyedReference(); - kr.setTModelKey("uddi:uddi.org:categorization:types"); - kr.setKeyName("uddi-org:keyGenerator"); - kr.setKeyValue("keyGenerator"); - tm.getCategoryBag().getKeyedReference().add(kr); - tm.setTModelKey(validTmodelKeyGenMax); - st.getTModel().add(tm); - - @SuppressWarnings("unused") - TModelDetail saveTModel = publication.saveTModel(st); - DeleteTModel dm = new DeleteTModel(); - dm.setAuthInfo(authInfoJoe); - dm.getTModelKey().add(validTmodelKeyGenMax); - publication.deleteTModel(dm); - - } - - //create a oversized tmodel keygen fail - @Test(expected=ValueNotAllowedException.class) - public void CreateKeyGenTooLongTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("CreateKeyGenTooLongTest"); - - SaveTModel st = new SaveTModel(); - st.setAuthInfo(authInfoJoe); - TModel tm = new TModel(); - tm.setName(new Name()); - tm.getName().setValue("My Cool Company Keymodel generator"); - tm.getName().setLang("en"); - tm.setCategoryBag(new CategoryBag()); - KeyedReference kr = new KeyedReference(); - kr.setTModelKey("uddi:uddi.org:categorization:types"); - kr.setKeyName("uddi-org:keyGenerator"); - kr.setKeyValue("keyGenerator"); - tm.getCategoryBag().getKeyedReference().add(kr); - tm.setTModelKey(validTmodelKeyGenTooLong); - st.getTModel().add(tm); - try { - @SuppressWarnings("unused") - TModelDetail saveTModel = publication.saveTModel(st); - Assert.fail("request should have been rejected"); - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - - } - - //create a tmodel with a key gen defined valid, with oversized Name - @Test(expected=ValueNotAllowedException.class) - public void CreateKeyGenKeyDescriptionTooLongTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("CreateKeyGenKeyDescriptionTooLongTest"); - - SaveTModel st = new SaveTModel(); - st.setAuthInfo(authInfoJoe); - TModel tm = new TModel(); - tm.setName(new Name()); - tm.getName().setValue("Key gen name"); - tm.getName().setLang("en"); - Description d = new Description(); - d.setValue(str256); - tm.getDescription().add(d); - tm.setCategoryBag(new CategoryBag()); - KeyedReference kr = new KeyedReference(); - kr.setTModelKey("uddi:uddi.org:categorization:types"); - kr.setKeyName("uddi-org:keyGenerator"); - kr.setKeyValue("keyGenerator"); - tm.getCategoryBag().getKeyedReference().add(kr); - tm.setTModelKey("uddi:uddi.joepublisher.com:mycustomkey"); - st.getTModel().add(tm); - try { - @SuppressWarnings("unused") - TModelDetail saveTModel = publication.saveTModel(st); - Assert.fail("request should have been rejected"); - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - @Test(expected=ValueNotAllowedException.class) - public void CreateKeyGenKeyDescriptionLangTooLongTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("CreateKeyGenKeyDescriptionTooLongTest"); - - SaveTModel st = new SaveTModel(); - st.setAuthInfo(authInfoJoe); - TModel tm = new TModel(); - tm.setName(new Name()); - tm.getName().setValue("Key gen name"); - tm.getName().setLang("en"); - Description d = new Description(); - d.setValue("A description"); - d.setLang(str256); - tm.getDescription().add(d); - tm.setCategoryBag(new CategoryBag()); - KeyedReference kr = new KeyedReference(); - kr.setTModelKey("uddi:uddi.org:categorization:types"); - kr.setKeyName("uddi-org:keyGenerator"); - kr.setKeyValue("keyGenerator"); - tm.getCategoryBag().getKeyedReference().add(kr); - String key = UUID.randomUUID().toString(); - tm.setTModelKey(key); - st.getTModel().add(tm); - try { - @SuppressWarnings("unused") - TModelDetail saveTModel = publication.saveTModel(st); - Assert.fail("request should have been rejected"); - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } finally { - //TODO delete the key - } - } - - @Test(expected=ValueNotAllowedException.class) - public void CreateKeyGenNameLangTooLongTest() throws DispositionReportFaultMessage, RemoteException { - System.out.println("CreateKeyGenNameLangTooLongTest"); - - SaveTModel st = new SaveTModel(); - st.setAuthInfo(authInfoJoe); - TModel tm = new TModel(); - tm.setName(new Name()); - tm.getName().setValue("hello world"); - tm.getName().setLang(str27); - tm.setCategoryBag(new CategoryBag()); - KeyedReference kr = new KeyedReference(); - kr.setTModelKey("uddi:uddi.org:categorization:types"); - kr.setKeyName("uddi-org:keyGenerator"); - kr.setKeyValue("keyGenerator"); - tm.getCategoryBag().getKeyedReference().add(kr); - tm.setTModelKey(validTmodelKeyGenTooLong); - st.getTModel().add(tm); - try { - @SuppressWarnings("unused") - TModelDetail saveTModel = publication.saveTModel(st); - Assert.fail("request should have been rejected"); - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - } - - //create a tmodel with a key gen defined valid, regular tmodel, - //then a business, service, binding template, tmodel instance infos, attach tmodel with some data, success - //create a tmodel without a key gen defined- fail - @Test(expected=InvalidKeyPassedException.class) - public void CreateTmodelnoKeyGen() throws DispositionReportFaultMessage, RemoteException { - System.out.println("CreateTmodelnoKeyGen"); - - SaveTModel st = new SaveTModel(); - st.setAuthInfo(authInfoJoe); - TModel tm = new TModel(); - tm.setName(new Name()); - tm.getName().setValue("My Cool Company's tmodel"); - tm.getName().setLang("en"); - - tm.setTModelKey("uddi:uddi.joepublisher.com:nokeygenerator:customkey"); - st.getTModel().add(tm); - try { - @SuppressWarnings("unused") - TModelDetail saveTModel = publication.saveTModel(st); - Assert.fail("request should have been rejected"); - } catch (ValueNotAllowedException ex) { - HandleException(ex); - throw ex; - } - - } - - @Test - public void BindingTemplateTmodelInstanceInfoTest() { - System.out.println("BindingTemplateTmodelInstanceInfoTest"); - //create a key gen - //create a tmodels - //create a business, service, binding with tmodel instance infos - - } - - //TODO binding template tmodel instance info - //TODO tmodel tests - //TODO create tests for enforcing ref integrity of tmodel keys, after enforcing this, the tests in this class will need to be heavily revised - // - /** - * Converts category bags of tmodels to a readable string - * - * @param categoryBag - * @return - */ - public static String CatBagToString(CategoryBag categoryBag) { - StringBuilder sb = new StringBuilder(); - if (categoryBag == null) { - return "no data"; - } - for (int i = 0; i < categoryBag.getKeyedReference().size(); i++) { - sb.append(KeyedReferenceToString(categoryBag.getKeyedReference().get(i))); - } - for (int i = 0; i < categoryBag.getKeyedReferenceGroup().size(); i++) { - sb.append("Key Ref Grp: TModelKey="); - for (int k = 0; k < categoryBag.getKeyedReferenceGroup().get(i).getKeyedReference().size(); k++) { - sb.append(KeyedReferenceToString(categoryBag.getKeyedReferenceGroup().get(i).getKeyedReference().get(k))); - } - } - return sb.toString(); - } - - public static String KeyedReferenceToString(KeyedReference item) { - StringBuilder sb = new StringBuilder(); - sb.append("Key Ref: Name="). - append(item.getKeyName()). - append(" Value="). - append(item.getKeyValue()). - append(" tModel="). - append(item.getTModelKey()). - append(System.getProperty("line.separator")); - return sb.toString(); - } - - public static void PrintContacts(Contacts contacts) { - if (contacts == null) { - return; - } - for (int i = 0; i < contacts.getContact().size(); i++) { - System.out.println("Contact " + i + " type:" + contacts.getContact().get(i).getUseType()); - for (int k = 0; k < contacts.getContact().get(i).getPersonName().size(); k++) { - System.out.println("Name: " + contacts.getContact().get(i).getPersonName().get(k).getValue()); - } - for (int k = 0; k < contacts.getContact().get(i).getEmail().size(); k++) { - System.out.println("Email: " + contacts.getContact().get(i).getEmail().get(k).getValue()); - } - for (int k = 0; k < contacts.getContact().get(i).getAddress().size(); k++) { - System.out.println("Address sort code " + contacts.getContact().get(i).getAddress().get(k).getSortCode()); - System.out.println("Address use type " + contacts.getContact().get(i).getAddress().get(k).getUseType()); - System.out.println("Address tmodel key " + contacts.getContact().get(i).getAddress().get(k).getTModelKey()); - for (int x = 0; x < contacts.getContact().get(i).getAddress().get(k).getAddressLine().size(); x++) { - System.out.println("Address line value " + contacts.getContact().get(i).getAddress().get(k).getAddressLine().get(x).getValue()); - System.out.println("Address line key name " + contacts.getContact().get(i).getAddress().get(k).getAddressLine().get(x).getKeyName()); - System.out.println("Address line key value " + contacts.getContact().get(i).getAddress().get(k).getAddressLine().get(x).getKeyValue()); - } - } - for (int k = 0; k < contacts.getContact().get(i).getDescription().size(); k++) { - System.out.println("Desc: " + contacts.getContact().get(i).getDescription().get(k).getValue()); - } - for (int k = 0; k < contacts.getContact().get(i).getPhone().size(); k++) { - System.out.println("Phone: " + contacts.getContact().get(i).getPhone().get(k).getValue()); - } - } - - } - - /** - * This function is useful for translating UDDI's somewhat complex data - * format to something that is more useful. - * - * @param bindingTemplates - */ - public static void PrintBindingTemplates(BindingTemplates bindingTemplates) { - if (bindingTemplates == null) { - return; - } - for (int i = 0; i < bindingTemplates.getBindingTemplate().size(); i++) { - System.out.println("Binding Key: " + bindingTemplates.getBindingTemplate().get(i).getBindingKey()); - - if (bindingTemplates.getBindingTemplate().get(i).getAccessPoint() != null) { - System.out.println("Access Point: " + bindingTemplates.getBindingTemplate().get(i).getAccessPoint().getValue() + " type " + bindingTemplates.getBindingTemplate().get(i).getAccessPoint().getUseType()); - } - - if (bindingTemplates.getBindingTemplate().get(i).getHostingRedirector() != null) { - System.out.println("Hosting Redirection: " + bindingTemplates.getBindingTemplate().get(i).getHostingRedirector().getBindingKey()); - } - } - } - - public static void PrintBusinessInfo(BusinessInfos businessInfos) { - if (businessInfos == null) { - System.out.println("No data returned"); - } else { - for (int i = 0; i < businessInfos.getBusinessInfo().size(); i++) { - System.out.println("==============================================="); - System.out.println("Business Key: " + businessInfos.getBusinessInfo().get(i).getBusinessKey()); - System.out.println("Name: " + ListToString(businessInfos.getBusinessInfo().get(i).getName())); - - System.out.println("Name: " + ListToDescString(businessInfos.getBusinessInfo().get(i).getDescription())); - System.out.println("Services:"); - PrintServiceInfo(businessInfos.getBusinessInfo().get(i).getServiceInfos()); - } - } - } - - public static String ListToString(List name) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < name.size(); i++) { - sb.append(name.get(i).getValue()).append(" "); - } - return sb.toString(); - } - - public static String ListToDescString(List name) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < name.size(); i++) { - sb.append(name.get(i).getValue()).append(" "); - } - return sb.toString(); - } - - public static void PrintServiceInfo(ServiceInfos serviceInfos) { - for (int i = 0; i < serviceInfos.getServiceInfo().size(); i++) { - System.out.println("-------------------------------------------"); - System.out.println("Service Key: " + serviceInfos.getServiceInfo().get(i).getServiceKey()); - System.out.println("Owning Business Key: " + serviceInfos.getServiceInfo().get(i).getBusinessKey()); - System.out.println("Name: " + ListToString(serviceInfos.getServiceInfo().get(i).getName())); - } - } - - public static void PrintBusinessDetails(List businessDetail) { - - - for (int i = 0; i < businessDetail.size(); i++) { - System.out.println("Business Detail - key: " + businessDetail.get(i).getBusinessKey()); - System.out.println("Name: " + ListToString(businessDetail.get(i).getName())); - System.out.println("CategoryBag: " + CatBagToString(businessDetail.get(i).getCategoryBag())); - PrintContacts(businessDetail.get(i).getContacts()); - } - } - -} +/* + * Copyright 2001-2009 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.rmi.RemoteException; +import java.util.List; +import java.util.UUID; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.Registry; +import org.apache.juddi.api_v3.AccessPointType; +import org.apache.juddi.v3.error.InvalidKeyPassedException; +import org.apache.juddi.v3.error.ValueNotAllowedException; +import org.apache.juddi.v3.tck.TckPublisher; +import org.apache.juddi.v3.tck.TckSecurity; +import org.apache.juddi.v3.tck.TckTModel; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.uddi.api_v3.AccessPoint; +import org.uddi.api_v3.Address; +import org.uddi.api_v3.AddressLine; +import org.uddi.api_v3.BindingTemplate; +import org.uddi.api_v3.BindingTemplates; +import org.uddi.api_v3.BusinessDetail; +import org.uddi.api_v3.BusinessEntity; +import org.uddi.api_v3.BusinessInfos; +import org.uddi.api_v3.BusinessService; +import org.uddi.api_v3.BusinessServices; +import org.uddi.api_v3.CategoryBag; +import org.uddi.api_v3.Contact; +import org.uddi.api_v3.Contacts; +import org.uddi.api_v3.DeleteBusiness; +import org.uddi.api_v3.DeleteTModel; +import org.uddi.api_v3.Description; +import org.uddi.api_v3.DiscoveryURL; +import org.uddi.api_v3.DiscoveryURLs; +import org.uddi.api_v3.Email; +import org.uddi.api_v3.HostingRedirector; +import org.uddi.api_v3.KeyedReference; +import org.uddi.api_v3.Name; +import org.uddi.api_v3.PersonName; +import org.uddi.api_v3.Phone; +import org.uddi.api_v3.SaveBusiness; +import org.uddi.api_v3.SaveTModel; +import org.uddi.api_v3.ServiceInfos; +import org.uddi.api_v3.TModel; +import org.uddi.api_v3.TModelDetail; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.v3_service.UDDIInquiryPortType; +import org.uddi.v3_service.UDDIPublicationPortType; +import org.uddi.v3_service.UDDISecurityPortType; + +/** + * The Negative Publication tests validates adherence to UDDI's string + * validations, max lengths, null values (and more) by sending bogus requests to + * a Publication endpoint. Tests that succeed or return stack traces are + * actually failing test cases + * + * This is incomplete. items left to test: all service related entries, + * including binding templates business/contact/useType business/contact/address + * amd addressLine business/catgag, ident bag + * + * @author Alex O'Ree + */ +public class API_140_NegativePublicationTest { + + private static Log logger = LogFactory.getLog(API_140_NegativePublicationTest.class); + static UDDISecurityPortType security = new UDDISecurityImpl(); + static UDDIInquiryPortType inquiry = new UDDIInquiryImpl(); + static UDDIPublicationPortType publication = new UDDIPublicationImpl(); + static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + + protected static String authInfoJoe = null; + protected static String authInfoSam = null; + static final String str256 = "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"; + static final String str255 = "uddi:tmodelkey:categories:1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"; + static final String strkey256 = "uddi:tmodelkey:categories:11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"; + static final String strkey256_1 = "uddi:org.apache:omething.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.somethi.com"; + static final String str26 = "11111111111111111111111111"; + static final String str27 = "111111111111111111111111110"; + static final String str10 = "0123456789"; + static final String str11 = "01234567890"; + static final String str80 = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; + static final String str81 = "012345678901234567890123456789012345678901234567890123456789012345678901234567891"; + static final String TRANS = "rolled back"; + static final String str4096 = "12345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000XXXXXXXX"; + static final String str4097 = "12345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000XXXXXXXXZ"; + static final String str51 = "111111111111111111111111111111111111111111111111111"; + static final String str50 = "11111111111111111111111111111111111111111111111111"; + static final String MISSING_RESOURCE = "Can't find resource for bundle"; + + @AfterClass + public static void stopManager() throws ConfigurationException { + Registry.stop(); + } + + @BeforeClass + public static void startManager() throws ConfigurationException { + Registry.start(); + + logger.debug("Getting auth tokens.."); + try { + authInfoJoe = TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); + authInfoSam = TckSecurity.getAuthToken(security, TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword()); + Assert.assertNotNull(authInfoJoe); + Assert.assertNotNull(authInfoSam); + String authInfoUDDI = TckSecurity.getAuthToken(security, TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword()); + tckTModel.saveUDDIPublisherTmodel(authInfoUDDI); + tckTModel.saveTModels(authInfoUDDI, TckTModel.TMODELS_XML); + tckTModel.saveJoePublisherTmodel(authInfoJoe); + } catch (Exception e) { + logger.error(e.getMessage(), e); + Assert.fail("Could not obtain authInfo token."); + } + } + + static void HandleException(Exception ex) { + if (logger.isDebugEnabled()) { + System.err.println("Error caught of type " + ex.getClass().getCanonicalName()); + ex.printStackTrace(); + } + Assert.assertFalse(ex.getMessage().toLowerCase().contains(TRANS.toLowerCase())); + Assert.assertFalse(ex.getMessage().toLowerCase().contains(MISSING_RESOURCE.toLowerCase())); + if (! (ex instanceof ValueNotAllowedException)) { + Assert.fail(); + } + } + + // + @Test + public void BusinessNameSanityTest() { + System.out.println("BusinessNameSanityTest"); + } + + @Test(expected = ValueNotAllowedException.class) + public void BusinessKeyTooLongTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BusinessKeyTooLongTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("Hello Nurse"); + be.getName().add(n); + be.setBusinessKey(strkey256_1); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test(expected = ValueNotAllowedException.class) + public void BusinessNameTooShortTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BusinessNameTooShortTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue(""); + be.getName().add(n); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test + public void BusinessNameMinLengthTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BusinessNameMinLengthTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("1"); + be.getName().add(n); + sb.getBusinessEntity().add(be); + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + } + + @Test(expected = ValueNotAllowedException.class) + public void BusinessNameTooLongTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BusinessNameTooLongTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + //256 chars + n.setValue(str256); + be.getName().add(n); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + + } + + @Test + public void BusinessNameMaxLengthTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BusinessNameMaxLengthTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + //255 chars + n.setValue(str255); + be.getName().add(n); + sb.getBusinessEntity().add(be); + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + } + + @Test(expected = ValueNotAllowedException.class) + public void BusinessNameLangTooLongTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BusinessNameLangTooLongTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + + n.setValue("A Test business"); + //27 + n.setLang(str27); + be.getName().add(n); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + + } + + @Test + public void BusinessNameLangMaxLengthTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BusinessNameLangMaxLengthTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + + n.setValue("A Test business"); + n.setLang(str26); + + be.getName().add(n); + sb.getBusinessEntity().add(be); + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + } + + @Test(expected = ValueNotAllowedException.class) + public void BusinessDescriptionLangTooLongTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BusinessDescriptionLangTooLongTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + + n.setValue("A Test business"); + Description d = new Description(); + d.setValue("a description"); + //27 + d.setLang(str27); + be.getName().add(n); + be.getDescription().add(d); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + + } + + @Test + public void BusinessDescriptionLangMaxLengthTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BusinessDescriptionLangMaxLengthTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + + n.setValue("A Test business"); + Description d = new Description(); + d.setValue("a description"); + //26 + d.setLang(str26); + be.getDescription().add(d); + be.getName().add(n); + sb.getBusinessEntity().add(be); + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + } + + @Test + public void BusinessDescriptionMaxLengthTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BusinessDescriptionMaxLengthTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + + n.setValue("A Test business"); + Description d = new Description(); + d.setValue(str255); + be.getDescription().add(d); + be.getName().add(n); + sb.getBusinessEntity().add(be); + + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + } + + @Test(expected = ValueNotAllowedException.class) + public void BusinessDescriptionTooLongLengthTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BusinessDescriptionTooLongLengthTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + + n.setValue("A Test business"); + Description d = new Description(); + d.setValue(str256); + be.getDescription().add(d); + be.getName().add(n); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + + } + + @Test(expected = ValueNotAllowedException.class) + public void BusinessDiscoveryURLTooLongTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BusinessDiscoveryURLTooLongTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + + n.setValue("A Test business"); + be.getName().add(n); + be.setDiscoveryURLs(new DiscoveryURLs()); + DiscoveryURL d = new DiscoveryURL(); + d.setValue(str4097); + be.getDiscoveryURLs().getDiscoveryURL().add(d); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + + } + + @Test + public void BusinessDiscoveryURLMaxLengthTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BusinessDiscoveryURLMaxLengthTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + + n.setValue("A Test business"); + be.getName().add(n); + be.setDiscoveryURLs(new DiscoveryURLs()); + DiscoveryURL d = new DiscoveryURL(); + d.setValue(str4096); + be.getDiscoveryURLs().getDiscoveryURL().add(d); + sb.getBusinessEntity().add(be); + + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + } + + @Test + public void BusinessDiscoveryURLMaxLengthMaxUseTypeTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BusinessDiscoveryURLMaxLengthMaxUseTypeTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + + n.setValue("A Test business"); + be.getName().add(n); + be.setDiscoveryURLs(new DiscoveryURLs()); + DiscoveryURL d = new DiscoveryURL(); + d.setValue(str4096); + d.setUseType(str255); + be.getDiscoveryURLs().getDiscoveryURL().add(d); + sb.getBusinessEntity().add(be); + + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + } + + @Test(expected = ValueNotAllowedException.class) + public void BusinessDiscoveryURLMaxLengthToolongUseTypeTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BusinessDiscoveryURLMaxLengthToolongUseTypeTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + + n.setValue("A Test business"); + be.getName().add(n); + be.setDiscoveryURLs(new DiscoveryURLs()); + DiscoveryURL d = new DiscoveryURL(); + d.setValue(str4096); + d.setUseType(str256); + be.getDiscoveryURLs().getDiscoveryURL().add(d); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test + public void ContactMaxEmailMaxUseTypeTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ContactMaxEmailMaxUseTypeTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setContacts(ContactMaxEmailMaxUseType()); + sb.getBusinessEntity().add(be); + + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + } + + private Contacts ContactMaxEmailMaxUseType() { + Contacts cc = new Contacts(); + Contact c = new Contact(); + PersonName n = new PersonName(); + n.setValue("Bob"); + c.getPersonName().add(n); + Email m = new Email(); + m.setValue(str255); + m.setUseType(str255); + c.getEmail().add(m); + cc.getContact().add(c);; + return cc; + } + + private Contacts ContactTooLongEmailMaxUseType() { + Contacts cc = new Contacts(); + Contact c = new Contact(); + PersonName n = new PersonName(); + n.setValue("Bob"); + c.getPersonName().add(n); + Email m = new Email(); + m.setValue(str256); + m.setUseType(str255); + c.getEmail().add(m); + cc.getContact().add(c);; + return cc; + } + + private Contacts ContactEmailUseTypeToolong() { + Contacts cc = new Contacts(); + Contact c = new Contact(); + PersonName n = new PersonName(); + n.setValue("Bob"); + c.getPersonName().add(n); + Email m = new Email(); + m.setValue(str255); + m.setUseType(str256); + c.getEmail().add(m); + cc.getContact().add(c);; + return cc; + } + + private Contacts ContactMaxDescription() { + Contacts cc = new Contacts(); + Contact c = new Contact(); + PersonName n = new PersonName(); + n.setValue("Bob"); + c.getPersonName().add(n); + Email m = new Email(); + m.setValue(str255); + m.setUseType(str255); + c.getEmail().add(m); + Description d = new Description(); + d.setLang(str26); + d.setValue(str255); + c.getDescription().add(d); + cc.getContact().add(c);; + return cc; + } + + private Contacts ContactDescriptionTooLong() { + Contacts cc = new Contacts(); + Contact c = new Contact(); + PersonName n = new PersonName(); + n.setValue("Bob"); + c.getPersonName().add(n); + Email m = new Email(); + m.setValue(str255); + m.setUseType(str255); + c.getEmail().add(m); + Description d = new Description(); + d.setLang(str256); + d.setValue(str26); + c.getDescription().add(d); + cc.getContact().add(c);; + return cc; + } + + private Contacts ContactPhoneTooLong() { + Contacts cc = new Contacts(); + Contact c = new Contact(); + PersonName n = new PersonName(); + n.setValue("Bob"); + c.getPersonName().add(n); + Phone p = new Phone(); + p.setValue(str51); + c.getPhone().add(p); + cc.getContact().add(c);; + return cc; + } + + private Contacts ContactPhoneUseTypeTooLong() { + Contacts cc = new Contacts(); + Contact c = new Contact(); + PersonName n = new PersonName(); + n.setValue("Bob"); + c.getPersonName().add(n); + Phone p = new Phone(); + p.setValue(str50); + p.setUseType(str256); + c.getPhone().add(p); + cc.getContact().add(c);; + return cc; + } + + private Contacts ContactPhoneUseTypeMaxLen() { + Contacts cc = new Contacts(); + Contact c = new Contact(); + PersonName n = new PersonName(); + n.setValue("Bob"); + c.getPersonName().add(n); + Phone p = new Phone(); + p.setValue(str50); + p.setUseType(str255); + c.getPhone().add(p); + cc.getContact().add(c);; + return cc; + } + + private Contacts ContactPhoneMaxLength() { + Contacts cc = new Contacts(); + Contact c = new Contact(); + PersonName n = new PersonName(); + n.setValue("Bob"); + c.getPersonName().add(n); + Phone p = new Phone(); + p.setValue(str50); + c.getPhone().add(p); + cc.getContact().add(c);; + return cc; + } + + private Contacts ContactAddressAllMax(boolean oversizedLang, boolean oversizedTmodel, boolean oversizedSortCode, boolean oversizedUseType, + boolean oversizedAddressLineValue, boolean oversizedAddressKN, boolean oversizedAddressKV) { + Contacts cc = new Contacts(); + Contact c = new Contact(); + PersonName n = new PersonName(); + n.setValue("Bob"); + c.getPersonName().add(n); + + cc.getContact().add(c); + Address a = new Address(); + if (oversizedSortCode) { + a.setSortCode(str11); + } else { + a.setSortCode(str10); + } + if (oversizedLang) { + a.setLang(str27); + } else { + a.setLang(str26); + } + if (oversizedTmodel) { + a.setTModelKey(str256); + } else { + a.setTModelKey(str255); + } + if (oversizedUseType) { + a.setUseType(str256); + } else { + a.setUseType(str255); + } + if (oversizedSortCode) { + a.setSortCode(str11); + } else { + a.setSortCode(str10); + } + AddressLine al = new AddressLine(); + if (oversizedAddressKN) { + al.setKeyName(str256); //optional + } else { + al.setKeyName(str255); //optional + } + if (oversizedAddressKV) { + al.setKeyValue(str256); //optional + } else { + al.setKeyValue(str255); //optional + } + if (oversizedAddressLineValue) { + al.setValue(str81); //this one is required + } else { + al.setValue(str80); + } + a.getAddressLine().add(al); + c.getAddress().add(a); + return cc; + } + + private Contacts ContactDescriptionLangTooLong() { + Contacts cc = new Contacts(); + Contact c = new Contact(); + PersonName n = new PersonName(); + n.setValue("Bob"); + c.getPersonName().add(n); + Email m = new Email(); + m.setValue(str255); + m.setUseType(str255); + c.getEmail().add(m); + Description d = new Description(); + d.setLang(str255); + d.setValue(str27); + c.getDescription().add(d); + cc.getContact().add(c); + return cc; + } + + @Test(expected = ValueNotAllowedException.class) + public void ContactTooLongEmailMaxUseTypeTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ContactTooLongEmailMaxUseTypeTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setContacts(ContactTooLongEmailMaxUseType()); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test(expected = ValueNotAllowedException.class) + public void ContactMaxEmailToolongUseTypeTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ContactMaxEmailToolongUseTypeTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + + be.setContacts(ContactEmailUseTypeToolong()); + + + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test + public void ContactDescriptionMaxLangMaxtest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ContactDescriptionMaxLangMaxtest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setContacts(ContactMaxDescription()); + sb.getBusinessEntity().add(be); + + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + + } + + @Test (expected = ValueNotAllowedException.class) + public void ContactDescriptionTooLongtest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ContactDescriptionTooLongtest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setContacts(ContactDescriptionTooLong()); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test (expected = ValueNotAllowedException.class) + public void ContactDescriptionLangTooLongTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ContactDescriptionLangTooLongTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setContacts(ContactDescriptionLangTooLong()); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test + public void ContactPhoneMaxLentest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ContactPhoneMaxLentest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setContacts(ContactPhoneMaxLength()); + sb.getBusinessEntity().add(be); + + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + + } + + @Test(expected=ValueNotAllowedException.class) + public void ContactPhoneTooLongtest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ContactPhoneTooLongtest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setContacts(ContactPhoneTooLong()); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test + public void ContactPhoneMaxLongtest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ContactPhoneMaxLongtest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setContacts(ContactPhoneMaxLength()); + sb.getBusinessEntity().add(be); + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + } + + @Test + public void ContactPhoneMaxLongMaxUseTypetest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ContactPhoneMaxLongMaxUseTypetest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setContacts(ContactPhoneUseTypeMaxLen()); + sb.getBusinessEntity().add(be); + + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + } + + @Test(expected = ValueNotAllowedException.class) + public void ContactPhoneUseTypeTooLongtest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ContactPhoneUseTypeTooLongtest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setContacts(ContactPhoneUseTypeTooLong()); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test + public void ContactMaxAddressFFFFFFFtest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ContactMaxAddressFFFFFFFtest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setContacts(ContactAddressAllMax(false, false, false, false, false, false, false)); + sb.getBusinessEntity().add(be); + + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + + } + + @Test(expected=ValueNotAllowedException.class) + public void ContactMaxAddressTFFFFFFtest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ContactMaxAddressTFFFFFFtest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setContacts(ContactAddressAllMax(true, false, false, false, false, false, false)); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test(expected=ValueNotAllowedException.class) + public void ContactMaxAddressFTFFFFFtest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ContactMaxAddressFTFFFFFtest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setContacts(ContactAddressAllMax(false, true, false, false, false, false, false)); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test(expected=ValueNotAllowedException.class) + public void ContactMaxAddressFFTFFFFtest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ContactMaxAddressFFTFFFFtest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setContacts(ContactAddressAllMax(false, false, true, false, false, false, false)); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test(expected=ValueNotAllowedException.class) + public void ContactMaxAddressFFFTFFFtest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ContactMaxAddressFFFTFFFtest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setContacts(ContactAddressAllMax(false, false, false, true, false, false, false)); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test(expected=ValueNotAllowedException.class) + public void ContactMaxAddressFFFFTFFtest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ContactMaxAddressFFFFTFFtest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setContacts(ContactAddressAllMax(false, false, false, false, true, false, false)); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test(expected=ValueNotAllowedException.class) + public void ContactMaxAddressFFFFFTFtest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ContactMaxAddressFFFFFTFtest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setContacts(ContactAddressAllMax(false, false, false, false, false, true, false)); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test(expected=ValueNotAllowedException.class) + public void ContactMaxAddressFFFFFFTtest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ContactMaxAddressFFFFFFTtest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setContacts(ContactAddressAllMax(false, false, false, false, false, false, true)); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test + public void KeyReferenceMax() throws DispositionReportFaultMessage, RemoteException { + System.out.println("KeyReferenceMax"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setCategoryBag(new CategoryBag()); + KeyedReference kr = new KeyedReference(); + kr.setKeyName(str255); + kr.setKeyValue(str255); + kr.setTModelKey(str255); + be.getCategoryBag().getKeyedReference().add(kr); + sb.getBusinessEntity().add(be); + + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + } + + @Test(expected=ValueNotAllowedException.class) + public void KeyReferenceKeyTooLong() throws DispositionReportFaultMessage, RemoteException { + System.out.println("KeyReferenceKeyTooLong"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setCategoryBag(new CategoryBag()); + KeyedReference kr = new KeyedReference(); + kr.setKeyName(str255); + kr.setKeyValue(str255); + kr.setTModelKey(str256); + be.getCategoryBag().getKeyedReference().add(kr); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test(expected=ValueNotAllowedException.class) + public void KeyReferenceNameTooLong() throws DispositionReportFaultMessage, RemoteException { + System.out.println("KeyReferenceNameTooLong"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setCategoryBag(new CategoryBag()); + KeyedReference kr = new KeyedReference(); + kr.setKeyName(str256); + kr.setKeyValue(str255); + kr.setTModelKey(str255); + be.getCategoryBag().getKeyedReference().add(kr); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test(expected=ValueNotAllowedException.class) + public void KeyReferenceValueTooLong() throws DispositionReportFaultMessage, RemoteException { + System.out.println("KeyReferenceValueTooLong"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setCategoryBag(new CategoryBag()); + KeyedReference kr = new KeyedReference(); + kr.setKeyName(str255); + kr.setKeyValue(str256); + kr.setTModelKey(str255); + be.getCategoryBag().getKeyedReference().add(kr); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test(expected=ValueNotAllowedException.class) + public void ServiceNameTooLongTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ServiceNameTooLongTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setBusinessServices(new BusinessServices()); + BusinessService bs = new BusinessService(); + n = new Name(); + n.setValue(str256); + bs.getName().add(n); + be.getBusinessServices().getBusinessService().add(bs); + + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test + public void ServiceNameMaxLenTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ServiceNameMaxLenTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setBusinessServices(new BusinessServices()); + BusinessService bs = new BusinessService(); + n = new Name(); + n.setValue(str255); + bs.getName().add(n); + be.getBusinessServices().getBusinessService().add(bs); + + sb.getBusinessEntity().add(be); + + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + } + + @Test + public void ServiceNameMaxLangLenTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ServiceNameMaxLangLenTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setBusinessServices(new BusinessServices()); + BusinessService bs = new BusinessService(); + n = new Name(); + n.setValue(str255); + n.setLang(str26); + bs.getName().add(n); + be.getBusinessServices().getBusinessService().add(bs); + + sb.getBusinessEntity().add(be); + + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + } + + @Test(expected=ValueNotAllowedException.class) + public void ServiceNameTooLongLangTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ServiceNameTooLongLangTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setBusinessServices(new BusinessServices()); + BusinessService bs = new BusinessService(); + n = new Name(); + n.setValue(str255); + n.setLang(str27); + bs.getName().add(n); + be.getBusinessServices().getBusinessService().add(bs); + + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test(expected=ValueNotAllowedException.class) + public void ServiceDescTooLongTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ServiceDescTooLongTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setBusinessServices(new BusinessServices()); + BusinessService bs = new BusinessService(); + Description d = new Description(); + d.setValue(str256); + bs.getDescription().add(d); + n = new Name(); + n.setValue(str255); + bs.getName().add(n); + be.getBusinessServices().getBusinessService().add(bs); + + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test(expected=ValueNotAllowedException.class) + public void ServiceDescLangTooLongTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ServiceDescLangTooLongTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setBusinessServices(new BusinessServices()); + BusinessService bs = new BusinessService(); + Description d = new Description(); + d.setValue(str255); + d.setLang(str27); + bs.getDescription().add(d); + n = new Name(); + n.setValue(str255); + bs.getName().add(n); + be.getBusinessServices().getBusinessService().add(bs); + + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test + public void ServiceDescMaxLangTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ServiceDescMaxLangTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setBusinessServices(new BusinessServices()); + BusinessService bs = new BusinessService(); + Description d = new Description(); + d.setValue(str255); + d.setLang(str26); + bs.getDescription().add(d); + n = new Name(); + n.setValue(str255); + bs.getName().add(n); + be.getBusinessServices().getBusinessService().add(bs); + + sb.getBusinessEntity().add(be); + + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + + } + + @Test + public void ServiceMaxCatBagTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ServiceDescMaxLangTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setBusinessServices(new BusinessServices()); + BusinessService bs = new BusinessService(); + Description d = new Description(); + d.setValue(str255); + d.setLang(str26); + bs.getDescription().add(d); + n = new Name(); + n.setValue(str255); + bs.getName().add(n); + bs.setCategoryBag(new CategoryBag()); + KeyedReference kr = new KeyedReference(); + kr.setKeyName(str255); + kr.setKeyValue(str255); + kr.setTModelKey(str255); + bs.getCategoryBag().getKeyedReference().add(kr); + be.getBusinessServices().getBusinessService().add(bs); + + sb.getBusinessEntity().add(be); + + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + } + + @Test(expected=ValueNotAllowedException.class) + public void ServiceMaxCatBagTooBigTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("ServiceMaxCatBagTooBigTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setBusinessServices(new BusinessServices()); + BusinessService bs = new BusinessService(); + Description d = new Description(); + d.setValue(str255); + d.setLang(str26); + bs.getDescription().add(d); + n = new Name(); + n.setValue(str255); + bs.getName().add(n); + bs.setCategoryBag(new CategoryBag()); + KeyedReference kr = new KeyedReference(); + kr.setKeyName(str256); + kr.setKeyValue(str256); + kr.setTModelKey(str256); + bs.getCategoryBag().getKeyedReference().add(kr); + be.getBusinessServices().getBusinessService().add(bs); + + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test(expected=ValueNotAllowedException.class) + public void BindingTemplateNoAccessPointTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BindingTemplateNoAccessPointTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setBusinessServices(new BusinessServices()); + BusinessService bs = new BusinessService(); + + n = new Name(); + n.setValue(str255); + bs.getName().add(n); + BindingTemplate bt = new BindingTemplate(); + bs.setBindingTemplates(new BindingTemplates()); + bs.getBindingTemplates().getBindingTemplate().add(bt); + + be.getBusinessServices().getBusinessService().add(bs); + + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test + public void BindingTemplateAccessPointMaxUseTypeTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BindingTemplateAccessPointMaxUseTypeTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setBusinessServices(new BusinessServices()); + BusinessService bs = new BusinessService(); + + n = new Name(); + n.setValue(str255); + bs.getName().add(n); + BindingTemplate bt = new BindingTemplate(); + bs.setBindingTemplates(new BindingTemplates()); + AccessPoint ap = new AccessPoint(); + ap.setUseType(str255); + ap.setValue("http://localhost"); + bt.setAccessPoint(ap); + bs.getBindingTemplates().getBindingTemplate().add(bt); + + be.getBusinessServices().getBusinessService().add(bs); + + sb.getBusinessEntity().add(be); + + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + } + + @Test(expected=ValueNotAllowedException.class) + public void BindingTemplateAccessPointUseTypeTooLongTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BindingTemplateAccessPointUseTypeTooLongTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setBusinessServices(new BusinessServices()); + BusinessService bs = new BusinessService(); + + n = new Name(); + n.setValue(str255); + bs.getName().add(n); + BindingTemplate bt = new BindingTemplate(); + bs.setBindingTemplates(new BindingTemplates()); + AccessPoint ap = new AccessPoint(); + ap.setUseType(str256); + ap.setValue("http://localhost"); + bt.setAccessPoint(ap); + bs.getBindingTemplates().getBindingTemplate().add(bt); + + be.getBusinessServices().getBusinessService().add(bs); + + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test(expected=ValueNotAllowedException.class) + public void BindingTemplateAccessPointValueTooLongTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BindingTemplateAccessPointValueTooLongTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setBusinessServices(new BusinessServices()); + BusinessService bs = new BusinessService(); + + n = new Name(); + n.setValue(str255); + bs.getName().add(n); + BindingTemplate bt = new BindingTemplate(); + bs.setBindingTemplates(new BindingTemplates()); + AccessPoint ap = new AccessPoint(); + ap.setUseType(str255); + ap.setValue(str4097); + bt.setAccessPoint(ap); + bs.getBindingTemplates().getBindingTemplate().add(bt); + + be.getBusinessServices().getBusinessService().add(bs); + + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test + public void BindingTemplateAccessPointMaxValueTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BindingTemplateAccessPointMaxValueTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setBusinessServices(new BusinessServices()); + BusinessService bs = new BusinessService(); + + n = new Name(); + n.setValue(str255); + bs.getName().add(n); + BindingTemplate bt = new BindingTemplate(); + bs.setBindingTemplates(new BindingTemplates()); + AccessPoint ap = new AccessPoint(); + ap.setUseType(str255); + ap.setValue(str4096); + bt.setAccessPoint(ap); + bs.getBindingTemplates().getBindingTemplate().add(bt); + + be.getBusinessServices().getBusinessService().add(bs); + + sb.getBusinessEntity().add(be); + + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + } + + @Test(expected=ValueNotAllowedException.class) + public void BindingTemplateNoAccessPointNoRedirectorTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BindingTemplateNoAccessPointNoRedirectorTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setBusinessServices(new BusinessServices()); + BusinessService bs = new BusinessService(); + + + n = new Name(); + n.setValue(str255); + bs.getName().add(n); + BindingTemplate bt = new BindingTemplate(); + bs.setBindingTemplates(new BindingTemplates()); + + bs.getBindingTemplates().getBindingTemplate().add(bt); + + be.getBusinessServices().getBusinessService().add(bs); + + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test(expected=ValueNotAllowedException.class) + public void BindingTemplateAccessPointAndRedirectorTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BindingTemplateAccessPointAndRedirectorTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setBusinessServices(new BusinessServices()); + BusinessService bs = new BusinessService(); + + n = new Name(); + n.setValue(str255); + bs.getName().add(n); + BindingTemplate bt = new BindingTemplate(); + bs.setBindingTemplates(new BindingTemplates()); + bt.setAccessPoint(new AccessPoint()); + bt.getAccessPoint().setUseType(str26); + + bt.setHostingRedirector(new HostingRedirector()); + + bt.getHostingRedirector().setBindingKey(str26); + bs.getBindingTemplates().getBindingTemplate().add(bt); + + be.getBusinessServices().getBusinessService().add(bs); + + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test + public void BindingTemplateHostRedirectorReferencalIntegritytest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BindingTemplateHostRedirectorReferencalIntegritytest"); + //TODO create a binding template, get the key, use the key as the specific redirector + String url = "http://juddi.apache.org"; + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setBusinessServices(new BusinessServices()); + BusinessService bs = new BusinessService(); + + n = new Name(); + n.setValue("A first business service"); + bs.getName().add(n); + BindingTemplate bt = new BindingTemplate(); + bs.setBindingTemplates(new BindingTemplates()); + bt.setAccessPoint(new AccessPoint()); + bt.getAccessPoint().setValue(url); + + //bt.setHostingRedirector(new HostingRedirector()); + //bt.getHostingRedirector().setBindingKey(str255); + bs.getBindingTemplates().getBindingTemplate().add(bt); + + be.getBusinessServices().getBusinessService().add(bs); + + sb.getBusinessEntity().add(be); + + System.out.println("Saving the business with the first service"); + BusinessDetail saveBusiness = publication.saveBusiness(sb); + + PrintBusinessDetails(saveBusiness.getBusinessEntity()); + + //setup the next one + bs = new BusinessService(); + n = new Name(); + n.setValue("A a redirected business service"); + bt = new BindingTemplate(); + bt.setHostingRedirector(new HostingRedirector()); + bt.getHostingRedirector().setBindingKey(saveBusiness.getBusinessEntity().get(0).getBusinessServices().getBusinessService().get(0).getBindingTemplates().getBindingTemplate().get(0).getBindingKey()); + bs.getName().add(n); + bs.setBindingTemplates(new BindingTemplates()); + bs.getBindingTemplates().getBindingTemplate().add(bt); + saveBusiness.getBusinessEntity().get(0).getBusinessServices().getBusinessService().add(bs); + + sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + sb.getBusinessEntity().add(saveBusiness.getBusinessEntity().get(0)); + + //This SHOULD be allowed + System.out.println("Saving the business with the first and second service as a host redirect"); + saveBusiness = publication.saveBusiness(sb); + PrintBusinessDetails(saveBusiness.getBusinessEntity()); + + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + } + + @Test + public void BindingTemplateAccessPointAsBindingTemplateReferencalIntegritytest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BindingTemplateAccessPointAsBindingTemplateReferencalIntegritytest"); + //create a binding template, get the key, use the key as the specific redirector + String url = "http://juddi.apache.org"; + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setBusinessServices(new BusinessServices()); + BusinessService bs = new BusinessService(); + + n = new Name(); + n.setValue("A first business service"); + bs.getName().add(n); + BindingTemplate bt = new BindingTemplate(); + bs.setBindingTemplates(new BindingTemplates()); + bt.setAccessPoint(new AccessPoint()); + bt.getAccessPoint().setValue(url); + + //bt.setHostingRedirector(new HostingRedirector()); + //bt.getHostingRedirector().setBindingKey(str255); + bs.getBindingTemplates().getBindingTemplate().add(bt); + + be.getBusinessServices().getBusinessService().add(bs); + + sb.getBusinessEntity().add(be); + System.out.println("Saving the business with the first service"); + BusinessDetail saveBusiness = publication.saveBusiness(sb); + + PrintBusinessDetails(saveBusiness.getBusinessEntity()); + + //setup the next one + bs = new BusinessService(); + n = new Name(); + n.setValue("A a redirected business service"); + bt = new BindingTemplate(); + bt.setAccessPoint(new AccessPoint()); + bt.getAccessPoint().setUseType(AccessPointType.BINDING_TEMPLATE.toString()); + bt.getAccessPoint().setValue(saveBusiness.getBusinessEntity().get(0).getBusinessServices().getBusinessService().get(0).getBindingTemplates().getBindingTemplate().get(0).getBindingKey()); + bs.getName().add(n); + bs.setBindingTemplates(new BindingTemplates()); + bs.getBindingTemplates().getBindingTemplate().add(bt); + saveBusiness.getBusinessEntity().get(0).getBusinessServices().getBusinessService().add(bs); + + sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + sb.getBusinessEntity().add(saveBusiness.getBusinessEntity().get(0)); + + //This SHOULD be allowed + System.out.println("Saving the business with the first and second service as a host redirect"); + saveBusiness = publication.saveBusiness(sb); + PrintBusinessDetails(saveBusiness.getBusinessEntity()); + + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + } + + @Test(expected=ValueNotAllowedException.class) + public void BindingTemplateAccessPointAsBindingTemplateINVALIDReferencalIntegritytest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BindingTemplateAccessPointAsBindingTemplateINVALIDReferencalIntegritytest"); + //create a binding template, get the key, use the key as the specific redirector + SaveBusiness sb; + try { + + sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + + BusinessEntity be = new BusinessEntity(); + Name bsn = new Name(); + bsn.setValue("A bogus business"); + be.getName().add(bsn); + + BusinessService bs = new BusinessService(); + Name n = new Name(); + n.setValue("A a redirected business service"); + BindingTemplate bt = new BindingTemplate(); + bt.setAccessPoint(new AccessPoint()); + bt.getAccessPoint().setUseType(AccessPointType.BINDING_TEMPLATE.toString()); + bt.getAccessPoint().setValue("uddi:" + UUID.randomUUID().toString()); + bs.getName().add(n); + bs.setBindingTemplates(new BindingTemplates()); + bs.getBindingTemplates().getBindingTemplate().add(bt); + be.setBusinessServices(new BusinessServices()); + be.getBusinessServices().getBusinessService().add(bs); + sb.getBusinessEntity().add(be); + BusinessDetail saveBusiness = publication.saveBusiness(sb); + + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test(expected=ValueNotAllowedException.class) + public void BindingTemplateHostRedirectorTooLongTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BindingTemplateHostRedirectorTooLongTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setBusinessServices(new BusinessServices()); + BusinessService bs = new BusinessService(); + + n = new Name(); + n.setValue(str255); + bs.getName().add(n); + BindingTemplate bt = new BindingTemplate(); + bs.setBindingTemplates(new BindingTemplates()); + + bt.setHostingRedirector(new HostingRedirector()); + bt.getHostingRedirector().setBindingKey(str256); + bs.getBindingTemplates().getBindingTemplate().add(bt); + + be.getBusinessServices().getBusinessService().add(bs); + + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test + public void BindingTemplateAccessPointMaxLengthTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BindingTemplateAccessPointMaxLengthTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setBusinessServices(new BusinessServices()); + BusinessService bs = new BusinessService(); + + n = new Name(); + n.setValue(str255); + bs.getName().add(n); + BindingTemplate bt = new BindingTemplate(); + bs.setBindingTemplates(new BindingTemplates()); + bt.setAccessPoint(new AccessPoint()); + bt.getAccessPoint().setValue(str4096); + + bs.getBindingTemplates().getBindingTemplate().add(bt); + + be.getBusinessServices().getBusinessService().add(bs); + + sb.getBusinessEntity().add(be); + + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + } + + @Test(expected=ValueNotAllowedException.class) + public void BindingTemplateAccessPointTooLongTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("BindingTemplateAccessPointTooLongTest"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("A Test business"); + be.getName().add(n); + be.setBusinessServices(new BusinessServices()); + BusinessService bs = new BusinessService(); + + n = new Name(); + n.setValue(str255); + bs.getName().add(n); + BindingTemplate bt = new BindingTemplate(); + + bs.setBindingTemplates(new BindingTemplates()); + bt.setAccessPoint(new AccessPoint()); + bt.getAccessPoint().setValue(str4097); + + bs.getBindingTemplates().getBindingTemplate().add(bt); + + be.getBusinessServices().getBusinessService().add(bs); + + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + publication.deleteBusiness(db); + Assert.fail("request should have been rejected"); + + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + // + static final String validTmodelKeyGenMax = "uddi:www.mycoolxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxcompany.com:keygenerator"; + static final String validTmodelKeyGenTooLong = "uddi:www.mycoolzxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxcompany.com:keygenerator"; + + //create a basic key gen + @Test + public void CreateKeyGenMaxLengthTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("CreateKeyGenMaxLengthTest"); + + SaveTModel st = new SaveTModel(); + st.setAuthInfo(authInfoJoe); + TModel tm = new TModel(); + tm.setName(new Name()); + tm.getName().setValue("My Cool Company Keymodel generator"); + tm.getName().setLang("en"); + tm.setCategoryBag(new CategoryBag()); + KeyedReference kr = new KeyedReference(); + kr.setTModelKey("uddi:uddi.org:categorization:types"); + kr.setKeyName("uddi-org:keyGenerator"); + kr.setKeyValue("keyGenerator"); + tm.getCategoryBag().getKeyedReference().add(kr); + tm.setTModelKey(validTmodelKeyGenMax); + st.getTModel().add(tm); + + @SuppressWarnings("unused") + TModelDetail saveTModel = publication.saveTModel(st); + DeleteTModel dm = new DeleteTModel(); + dm.setAuthInfo(authInfoJoe); + dm.getTModelKey().add(validTmodelKeyGenMax); + publication.deleteTModel(dm); + + } + + //create a oversized tmodel keygen fail + @Test(expected=ValueNotAllowedException.class) + public void CreateKeyGenTooLongTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("CreateKeyGenTooLongTest"); + + SaveTModel st = new SaveTModel(); + st.setAuthInfo(authInfoJoe); + TModel tm = new TModel(); + tm.setName(new Name()); + tm.getName().setValue("My Cool Company Keymodel generator"); + tm.getName().setLang("en"); + tm.setCategoryBag(new CategoryBag()); + KeyedReference kr = new KeyedReference(); + kr.setTModelKey("uddi:uddi.org:categorization:types"); + kr.setKeyName("uddi-org:keyGenerator"); + kr.setKeyValue("keyGenerator"); + tm.getCategoryBag().getKeyedReference().add(kr); + tm.setTModelKey(validTmodelKeyGenTooLong); + st.getTModel().add(tm); + try { + @SuppressWarnings("unused") + TModelDetail saveTModel = publication.saveTModel(st); + Assert.fail("request should have been rejected"); + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + + } + + //create a tmodel with a key gen defined valid, with oversized Name + @Test(expected=ValueNotAllowedException.class) + public void CreateKeyGenKeyDescriptionTooLongTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("CreateKeyGenKeyDescriptionTooLongTest"); + + SaveTModel st = new SaveTModel(); + st.setAuthInfo(authInfoJoe); + TModel tm = new TModel(); + tm.setName(new Name()); + tm.getName().setValue("Key gen name"); + tm.getName().setLang("en"); + Description d = new Description(); + d.setValue(str256); + tm.getDescription().add(d); + tm.setCategoryBag(new CategoryBag()); + KeyedReference kr = new KeyedReference(); + kr.setTModelKey("uddi:uddi.org:categorization:types"); + kr.setKeyName("uddi-org:keyGenerator"); + kr.setKeyValue("keyGenerator"); + tm.getCategoryBag().getKeyedReference().add(kr); + tm.setTModelKey("uddi:uddi.joepublisher.com:mycustomkey"); + st.getTModel().add(tm); + try { + @SuppressWarnings("unused") + TModelDetail saveTModel = publication.saveTModel(st); + Assert.fail("request should have been rejected"); + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + @Test(expected=ValueNotAllowedException.class) + public void CreateKeyGenKeyDescriptionLangTooLongTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("CreateKeyGenKeyDescriptionTooLongTest"); + + SaveTModel st = new SaveTModel(); + st.setAuthInfo(authInfoJoe); + TModel tm = new TModel(); + tm.setName(new Name()); + tm.getName().setValue("Key gen name"); + tm.getName().setLang("en"); + Description d = new Description(); + d.setValue("A description"); + d.setLang(str256); + tm.getDescription().add(d); + tm.setCategoryBag(new CategoryBag()); + KeyedReference kr = new KeyedReference(); + kr.setTModelKey("uddi:uddi.org:categorization:types"); + kr.setKeyName("uddi-org:keyGenerator"); + kr.setKeyValue("keyGenerator"); + tm.getCategoryBag().getKeyedReference().add(kr); + String key = UUID.randomUUID().toString(); + tm.setTModelKey(key); + st.getTModel().add(tm); + try { + @SuppressWarnings("unused") + TModelDetail saveTModel = publication.saveTModel(st); + Assert.fail("request should have been rejected"); + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } finally { + //TODO delete the key + } + } + + @Test(expected=ValueNotAllowedException.class) + public void CreateKeyGenNameLangTooLongTest() throws DispositionReportFaultMessage, RemoteException { + System.out.println("CreateKeyGenNameLangTooLongTest"); + + SaveTModel st = new SaveTModel(); + st.setAuthInfo(authInfoJoe); + TModel tm = new TModel(); + tm.setName(new Name()); + tm.getName().setValue("hello world"); + tm.getName().setLang(str27); + tm.setCategoryBag(new CategoryBag()); + KeyedReference kr = new KeyedReference(); + kr.setTModelKey("uddi:uddi.org:categorization:types"); + kr.setKeyName("uddi-org:keyGenerator"); + kr.setKeyValue("keyGenerator"); + tm.getCategoryBag().getKeyedReference().add(kr); + tm.setTModelKey(validTmodelKeyGenTooLong); + st.getTModel().add(tm); + try { + @SuppressWarnings("unused") + TModelDetail saveTModel = publication.saveTModel(st); + Assert.fail("request should have been rejected"); + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + } + + //create a tmodel with a key gen defined valid, regular tmodel, + //then a business, service, binding template, tmodel instance infos, attach tmodel with some data, success + //create a tmodel without a key gen defined- fail + @Test(expected=InvalidKeyPassedException.class) + public void CreateTmodelnoKeyGen() throws DispositionReportFaultMessage, RemoteException { + System.out.println("CreateTmodelnoKeyGen"); + + SaveTModel st = new SaveTModel(); + st.setAuthInfo(authInfoJoe); + TModel tm = new TModel(); + tm.setName(new Name()); + tm.getName().setValue("My Cool Company's tmodel"); + tm.getName().setLang("en"); + + tm.setTModelKey("uddi:uddi.joepublisher.com:nokeygenerator:customkey"); + st.getTModel().add(tm); + try { + @SuppressWarnings("unused") + TModelDetail saveTModel = publication.saveTModel(st); + Assert.fail("request should have been rejected"); + } catch (ValueNotAllowedException ex) { + HandleException(ex); + throw ex; + } + + } + + @Test + public void BindingTemplateTmodelInstanceInfoTest() { + System.out.println("BindingTemplateTmodelInstanceInfoTest"); + //create a key gen + //create a tmodels + //create a business, service, binding with tmodel instance infos + + } + + //TODO binding template tmodel instance info + //TODO tmodel tests + //TODO create tests for enforcing ref integrity of tmodel keys, after enforcing this, the tests in this class will need to be heavily revised + // + /** + * Converts category bags of tmodels to a readable string + * + * @param categoryBag + * @return + */ + public static String CatBagToString(CategoryBag categoryBag) { + StringBuilder sb = new StringBuilder(); + if (categoryBag == null) { + return "no data"; + } + for (int i = 0; i < categoryBag.getKeyedReference().size(); i++) { + sb.append(KeyedReferenceToString(categoryBag.getKeyedReference().get(i))); + } + for (int i = 0; i < categoryBag.getKeyedReferenceGroup().size(); i++) { + sb.append("Key Ref Grp: TModelKey="); + for (int k = 0; k < categoryBag.getKeyedReferenceGroup().get(i).getKeyedReference().size(); k++) { + sb.append(KeyedReferenceToString(categoryBag.getKeyedReferenceGroup().get(i).getKeyedReference().get(k))); + } + } + return sb.toString(); + } + + public static String KeyedReferenceToString(KeyedReference item) { + StringBuilder sb = new StringBuilder(); + sb.append("Key Ref: Name="). + append(item.getKeyName()). + append(" Value="). + append(item.getKeyValue()). + append(" tModel="). + append(item.getTModelKey()). + append(System.getProperty("line.separator")); + return sb.toString(); + } + + public static void PrintContacts(Contacts contacts) { + if (contacts == null) { + return; + } + for (int i = 0; i < contacts.getContact().size(); i++) { + System.out.println("Contact " + i + " type:" + contacts.getContact().get(i).getUseType()); + for (int k = 0; k < contacts.getContact().get(i).getPersonName().size(); k++) { + System.out.println("Name: " + contacts.getContact().get(i).getPersonName().get(k).getValue()); + } + for (int k = 0; k < contacts.getContact().get(i).getEmail().size(); k++) { + System.out.println("Email: " + contacts.getContact().get(i).getEmail().get(k).getValue()); + } + for (int k = 0; k < contacts.getContact().get(i).getAddress().size(); k++) { + System.out.println("Address sort code " + contacts.getContact().get(i).getAddress().get(k).getSortCode()); + System.out.println("Address use type " + contacts.getContact().get(i).getAddress().get(k).getUseType()); + System.out.println("Address tmodel key " + contacts.getContact().get(i).getAddress().get(k).getTModelKey()); + for (int x = 0; x < contacts.getContact().get(i).getAddress().get(k).getAddressLine().size(); x++) { + System.out.println("Address line value " + contacts.getContact().get(i).getAddress().get(k).getAddressLine().get(x).getValue()); + System.out.println("Address line key name " + contacts.getContact().get(i).getAddress().get(k).getAddressLine().get(x).getKeyName()); + System.out.println("Address line key value " + contacts.getContact().get(i).getAddress().get(k).getAddressLine().get(x).getKeyValue()); + } + } + for (int k = 0; k < contacts.getContact().get(i).getDescription().size(); k++) { + System.out.println("Desc: " + contacts.getContact().get(i).getDescription().get(k).getValue()); + } + for (int k = 0; k < contacts.getContact().get(i).getPhone().size(); k++) { + System.out.println("Phone: " + contacts.getContact().get(i).getPhone().get(k).getValue()); + } + } + + } + + /** + * This function is useful for translating UDDI's somewhat complex data + * format to something that is more useful. + * + * @param bindingTemplates + */ + public static void PrintBindingTemplates(BindingTemplates bindingTemplates) { + if (bindingTemplates == null) { + return; + } + for (int i = 0; i < bindingTemplates.getBindingTemplate().size(); i++) { + System.out.println("Binding Key: " + bindingTemplates.getBindingTemplate().get(i).getBindingKey()); + + if (bindingTemplates.getBindingTemplate().get(i).getAccessPoint() != null) { + System.out.println("Access Point: " + bindingTemplates.getBindingTemplate().get(i).getAccessPoint().getValue() + " type " + bindingTemplates.getBindingTemplate().get(i).getAccessPoint().getUseType()); + } + + if (bindingTemplates.getBindingTemplate().get(i).getHostingRedirector() != null) { + System.out.println("Hosting Redirection: " + bindingTemplates.getBindingTemplate().get(i).getHostingRedirector().getBindingKey()); + } + } + } + + public static void PrintBusinessInfo(BusinessInfos businessInfos) { + if (businessInfos == null) { + System.out.println("No data returned"); + } else { + for (int i = 0; i < businessInfos.getBusinessInfo().size(); i++) { + System.out.println("==============================================="); + System.out.println("Business Key: " + businessInfos.getBusinessInfo().get(i).getBusinessKey()); + System.out.println("Name: " + ListToString(businessInfos.getBusinessInfo().get(i).getName())); + + System.out.println("Name: " + ListToDescString(businessInfos.getBusinessInfo().get(i).getDescription())); + System.out.println("Services:"); + PrintServiceInfo(businessInfos.getBusinessInfo().get(i).getServiceInfos()); + } + } + } + + public static String ListToString(List name) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < name.size(); i++) { + sb.append(name.get(i).getValue()).append(" "); + } + return sb.toString(); + } + + public static String ListToDescString(List name) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < name.size(); i++) { + sb.append(name.get(i).getValue()).append(" "); + } + return sb.toString(); + } + + public static void PrintServiceInfo(ServiceInfos serviceInfos) { + for (int i = 0; i < serviceInfos.getServiceInfo().size(); i++) { + System.out.println("-------------------------------------------"); + System.out.println("Service Key: " + serviceInfos.getServiceInfo().get(i).getServiceKey()); + System.out.println("Owning Business Key: " + serviceInfos.getServiceInfo().get(i).getBusinessKey()); + System.out.println("Name: " + ListToString(serviceInfos.getServiceInfo().get(i).getName())); + } + } + + public static void PrintBusinessDetails(List businessDetail) { + + + for (int i = 0; i < businessDetail.size(); i++) { + System.out.println("Business Detail - key: " + businessDetail.get(i).getBusinessKey()); + System.out.println("Name: " + ListToString(businessDetail.get(i).getName())); + System.out.println("CategoryBag: " + CatBagToString(businessDetail.get(i).getCategoryBag())); + PrintContacts(businessDetail.get(i).getContacts()); + } + } + +} diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_141_JIRATest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_141_JIRATest.java similarity index 97% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/API_141_JIRATest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_141_JIRATest.java index f71336b89..57c3c9a5a 100644 --- a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_141_JIRATest.java +++ b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_141_JIRATest.java @@ -1,1419 +1,1419 @@ -/* - * Copyright 2001-2009 The Apache Software Foundation. - * - * 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 org.apache.juddi.api.impl; - -import java.security.cert.CertificateException; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicReference; - -import javax.xml.soap.SOAPFault; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.juddi.Registry; -import org.apache.juddi.api_v3.GetEntityHistoryMessageRequest; -import org.apache.juddi.api_v3.GetEntityHistoryMessageResponse; -import org.apache.juddi.api_v3.SubscriptionWrapper; -import org.apache.juddi.jaxb.PrintUDDI; -import org.apache.juddi.v3.client.UDDIConstants; -import org.apache.juddi.v3.client.config.UDDIClient; -import org.apache.juddi.v3.client.cryptor.DigSigUtil; -import org.apache.juddi.v3.error.ValueNotAllowedException; -import org.apache.juddi.v3.tck.TckBusiness; -import org.apache.juddi.v3.tck.TckBusinessService; -import org.apache.juddi.v3.tck.TckPublisher; -import org.apache.juddi.v3.tck.TckSecurity; -import org.apache.juddi.v3.tck.TckTModel; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.uddi.api_v3.AccessPoint; -import org.uddi.api_v3.BindingTemplate; -import org.uddi.api_v3.BindingTemplates; -import org.uddi.api_v3.BusinessDetail; -import org.uddi.api_v3.BusinessEntity; -import org.uddi.api_v3.BusinessInfos; -import org.uddi.api_v3.BusinessList; -import org.uddi.api_v3.BusinessService; -import org.uddi.api_v3.BusinessServices; -import org.uddi.api_v3.CategoryBag; -import org.uddi.api_v3.Contacts; -import org.uddi.api_v3.DeleteBusiness; -import org.uddi.api_v3.DeleteTModel; -import org.uddi.api_v3.Description; -import org.uddi.api_v3.FindBusiness; -import org.uddi.api_v3.FindQualifiers; -import org.uddi.api_v3.FindService; -import org.uddi.api_v3.FindTModel; -import org.uddi.api_v3.GetBusinessDetail; -import org.uddi.api_v3.KeyedReference; -import org.uddi.api_v3.Name; -import org.uddi.api_v3.SaveBinding; -import org.uddi.api_v3.SaveBusiness; -import org.uddi.api_v3.SaveService; -import org.uddi.api_v3.SaveTModel; -import org.uddi.api_v3.ServiceDetail; -import org.uddi.api_v3.ServiceInfos; -import org.uddi.api_v3.ServiceList; -import org.uddi.api_v3.TModel; -import org.uddi.api_v3.TModelDetail; -import org.uddi.api_v3.TModelList; -import org.uddi.v3_service.DispositionReportFaultMessage; -import org.uddi.v3_service.UDDIInquiryPortType; -import org.uddi.v3_service.UDDIPublicationPortType; -import org.uddi.v3_service.UDDISecurityPortType; - -/** - * This test class provides test cases of items discovered or reported through - * the Juddi JIRA issue tracker The idea is that these tests apply to any UDDI - * registry and that the tests are either implied or derived requirements - * defined in the UDDI spec that were missed in other test cases for Juddi. - * - * @author Alex O'Ree - */ -public class API_141_JIRATest { - - private static Log logger = LogFactory.getLog(API_141_JIRATest.class); - static UDDISecurityPortType security = new UDDISecurityImpl(); - static UDDIInquiryPortType inquiry = new UDDIInquiryImpl(); - static UDDIPublicationPortType publication = new UDDIPublicationImpl(); - static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); - protected static String authInfoJoe = null; - protected static String authInfoSam = null; - private static UDDIClient manager; - static final String str256 = "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"; - static final String str255 = "uddi:tmodelkey:categories:1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"; - static final String strkey256 = "uddi:tmodelkey:categories:11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"; - static final String strkey256_1 = "uddi:org.apache:omething.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.somethi.com"; - static final String str26 = "11111111111111111111111111"; - static final String str27 = "111111111111111111111111110"; - static final String str10 = "0123456789"; - static final String str11 = "01234567890"; - static final String str80 = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; - static final String str81 = "012345678901234567890123456789012345678901234567890123456789012345678901234567891"; - static final String TRANS = "The transaction has been rolled back"; - static final String str4096 = "12345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000XXXXXXXX"; - static final String str4097 = "12345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000XXXXXXXXZ"; - static final String str51 = "111111111111111111111111111111111111111111111111111"; - static final String str50 = "11111111111111111111111111111111111111111111111111"; - static final String MISSING_RESOURCE = "Can't find resource for bundle"; - - @AfterClass - public static void stopManager() throws ConfigurationException { - Registry.stop(); - } - - @BeforeClass - public static void startManager() throws ConfigurationException { - Registry.start(); - - logger.debug("Getting auth tokens.."); - try { - authInfoJoe = TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); - authInfoSam = TckSecurity.getAuthToken(security, TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword()); - Assert.assertNotNull(authInfoJoe); - Assert.assertNotNull(authInfoSam); - String authInfoUDDI = TckSecurity.getAuthToken(security, TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword()); - tckTModel.saveUDDIPublisherTmodel(authInfoUDDI); - tckTModel.saveTModels(authInfoUDDI, TckTModel.TMODELS_XML); - tckTModel.saveJoePublisherTmodel(authInfoJoe); - } catch (Exception e) { - logger.error(e.getMessage(), e); - Assert.fail("Could not obtain authInfo token."); - } - } - - static void HandleException(Exception ex) { - System.err.println("Error caught of type " + ex.getClass().getCanonicalName()); - ex.printStackTrace(); - if (ex.getMessage() != null) { - Assert.assertFalse(ex.getMessage().contains(TRANS)); - Assert.assertFalse(ex.getMessage().contains(MISSING_RESOURCE)); - } - if (ex instanceof SOAPFault) { - SOAPFault sf = (SOAPFault) ex; - if (!sf.getTextContent().contains("org.apache.juddi.v3.error.ValueNotAllowedException")) { - Assert.fail(); - } - } - } - - @Test - public void JUDDI_JIRA_571_Part1_Test() { - //add a business - //add a business with lang defined - //find business with lang defined, expecting one result - //find business without lang defined, expecting 2 results - List businesskeysToDelete = new ArrayList(); - String failuremsg = ""; - System.out.println("JUDDI_JIRA_571_Part1_Test"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - be.setBusinessKey(TckTModel.JOE_PUBLISHER_KEY_PREFIX + UUID.randomUUID().toString()); - Name n = new Name(); - n.setValue("JUDDI_JIRA_571_Part1_Test no lang"); - be.getName().add(n); - sb.getBusinessEntity().add(be); - - be = new BusinessEntity(); - be.setBusinessKey(TckTModel.JOE_PUBLISHER_KEY_PREFIX + UUID.randomUUID().toString()); - n = new Name(); - n.setValue("JUDDI_JIRA_571_Part1_Test with lang"); - n.setLang("en"); - be.getName().add(n); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - businesskeysToDelete.add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - businesskeysToDelete.add(saveBusiness.getBusinessEntity().get(1).getBusinessKey()); - - } catch (Exception ex) { - HandleException(ex); - Assert.fail("unexpected failure"); - } - - int found1 = 0; - FindBusiness fb = new FindBusiness(); - fb.setAuthInfo(authInfoJoe); - n = new Name(); - n.setValue("%"); - fb.getName().add(n); - fb.setFindQualifiers(new FindQualifiers()); - fb.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); - try { - BusinessList findBusiness = inquiry.findBusiness(fb); - if (findBusiness.getBusinessInfos() != null) { - for (int i = 0; i < findBusiness.getBusinessInfos().getBusinessInfo().size(); i++) { - if (businesskeysToDelete.contains(findBusiness.getBusinessInfos().getBusinessInfo().get(i).getBusinessKey())) { - found1++; - } - } - } - } catch (Exception ex) { - HandleException(ex); - Assert.fail("unexpected failure"); - } - if (found1 != 2) { - failuremsg += "No lang defined, " + found1 + " records found instead of 2"; - } - - - - found1 = 0; - fb = new FindBusiness(); - fb.setAuthInfo(authInfoJoe); - n = new Name(); - n.setLang("en"); - n.setValue("%"); - fb.getName().add(n); - fb.setFindQualifiers(new FindQualifiers()); - fb.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); - try { - BusinessList findBusiness = inquiry.findBusiness(fb); - if (findBusiness.getBusinessInfos() != null) { - for (int i = 0; i < findBusiness.getBusinessInfos().getBusinessInfo().size(); i++) { - if (businesskeysToDelete.contains(findBusiness.getBusinessInfos().getBusinessInfo().get(i).getBusinessKey())) { - found1++; - } - } - } - } catch (Exception ex) { - HandleException(ex); - Assert.fail("unexpected failure"); - } - if (found1 != 1) { - failuremsg += "Lang defined, " + found1 + " records found instead of 1"; - } - - - DeleteBusinesses(businesskeysToDelete); - if (failuremsg.length() > 0) { - Assert.fail(failuremsg); - } - System.out.println("Pass"); - - } - - @Test - public void JUDDI_JIRA_571_Part2_Test() { - //add a service - //add a service with lang defined - //find service with lang defined, expecting one result - //find service without lang defined, expecting 2 results - - - - List businesskeysToDelete = new ArrayList(); - List targetServiceKeys = new ArrayList(); - String failuremsg = ""; - System.out.println("JUDDI_JIRA_571_Part2_Test"); - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - be.setBusinessKey(TckTModel.JOE_PUBLISHER_KEY_PREFIX + UUID.randomUUID().toString()); - Name n = new Name(); - n.setValue("JUDDI_JIRA_571_Part2_Test no lang"); - be.getName().add(n); - sb.getBusinessEntity().add(be); - - BusinessService bs = new BusinessService(); - n = new Name(); - bs.setServiceKey(TckTModel.JOE_PUBLISHER_KEY_PREFIX + UUID.randomUUID().toString()); - bs.setBusinessKey(be.getBusinessKey()); - n.setValue("Service1 No Lang"); - bs.getName().add(n); - be.setBusinessServices(new BusinessServices()); - be.getBusinessServices().getBusinessService().add(bs); - - bs = new BusinessService(); - bs.setServiceKey(TckTModel.JOE_PUBLISHER_KEY_PREFIX + UUID.randomUUID().toString()); - bs.setBusinessKey(be.getBusinessKey()); - n = new Name(); - n.setValue("Service2 Lang"); - n.setLang("en"); - bs.getName().add(n); - be.getBusinessServices().getBusinessService().add(bs); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - businesskeysToDelete.add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - targetServiceKeys.add(saveBusiness.getBusinessEntity().get(0).getBusinessServices().getBusinessService().get(0).getServiceKey()); - targetServiceKeys.add(saveBusiness.getBusinessEntity().get(0).getBusinessServices().getBusinessService().get(1).getServiceKey()); - - } catch (Exception ex) { - HandleException(ex); - Assert.fail("unexpected failure"); - } - - int found1 = 0; - FindService fb = new FindService(); - fb.setAuthInfo(authInfoJoe); - n = new Name(); - n.setValue("%"); - fb.getName().add(n); - fb.setFindQualifiers(new FindQualifiers()); - fb.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); - try { - ServiceList findBusiness = inquiry.findService(fb); - if (findBusiness.getServiceInfos() != null) { - for (int i = 0; i < findBusiness.getServiceInfos().getServiceInfo().size(); i++) { - if (targetServiceKeys.contains(findBusiness.getServiceInfos().getServiceInfo().get(i).getServiceKey())) { - found1++; - } - } - } - } catch (Exception ex) { - HandleException(ex); - Assert.fail("unexpected failure"); - } - if (found1 != 2) { - failuremsg += "No lang defined, " + found1 + " records found instead of 2"; - } - - - - found1 = 0; - fb = new FindService(); - fb.setAuthInfo(authInfoJoe); - n = new Name(); - n.setLang("en"); - n.setValue("%"); - fb.getName().add(n); - fb.setFindQualifiers(new FindQualifiers()); - fb.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); - try { - ServiceList findBusiness = inquiry.findService(fb); - if (findBusiness.getServiceInfos() != null) { - for (int i = 0; i < findBusiness.getServiceInfos().getServiceInfo().size(); i++) { - if (businesskeysToDelete.contains(findBusiness.getServiceInfos().getServiceInfo().get(i).getBusinessKey())) { - found1++; - } - } - } - } catch (Exception ex) { - HandleException(ex); - Assert.fail("unexpected failure"); - } - if (found1 != 1) { - failuremsg += "Lang defined, " + found1 + " records found instead of 1"; - } - - - DeleteBusinesses(businesskeysToDelete); - if (failuremsg.length() > 0) { - Assert.fail(failuremsg); - } - System.out.println("Pass"); - - } - - @Test - public void JUDDI_571_Part3_Test() { - //add a tmodel - //add a tmodel with lang defined - //find tmodel with lang defined, expecting one result - //find tmodel without lang defined, expecting 2 results - - - List businesskeysToDelete = new ArrayList(); - - String failuremsg = ""; - System.out.println("JUDDI_571_Part3_Test"); - SaveTModel sb = new SaveTModel(); - sb.setAuthInfo(authInfoJoe); - TModel be = new TModel(); - be.setTModelKey(TckTModel.JOE_PUBLISHER_KEY_PREFIX + UUID.randomUUID().toString()); - Name n = new Name(); - n.setValue("JUDDI_571_Part3_Test no lang"); - be.setName(n); - sb.getTModel().add(be); - - be = new TModel(); - be.setTModelKey(TckTModel.JOE_PUBLISHER_KEY_PREFIX + UUID.randomUUID().toString()); - n = new Name(); - n.setValue("JUDDI_571_Part3_Test lang"); - n.setLang("en"); - be.setName(n); - sb.getTModel().add(be); - - try { - TModelDetail saveTModel = publication.saveTModel(sb); - businesskeysToDelete.add(saveTModel.getTModel().get(0).getTModelKey()); - businesskeysToDelete.add(saveTModel.getTModel().get(1).getTModelKey()); - } catch (Exception ex) { - HandleException(ex); - Assert.fail("unexpected failure"); - } - - int found1 = 0; - FindTModel fb = new FindTModel(); - fb.setAuthInfo(authInfoJoe); - n = new Name(); - n.setValue("%JUDDI_571_Part3_Test%"); - fb.setName(n); - fb.setFindQualifiers(new FindQualifiers()); - fb.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); - try { - TModelList findTModel = inquiry.findTModel(fb); - if (findTModel.getTModelInfos() != null) { - for (int i = 0; i < findTModel.getTModelInfos().getTModelInfo().size(); i++) { - if (businesskeysToDelete.contains(findTModel.getTModelInfos().getTModelInfo().get(i).getTModelKey())) { - found1++; - } - } - } - } catch (Exception ex) { - HandleException(ex); - Assert.fail("unexpected failure"); - } - if (found1 != 2) { - failuremsg += "No lang defined, " + found1 + " records found instead of 2"; - } - - - - found1 = 0; - fb = new FindTModel(); - fb.setAuthInfo(authInfoJoe); - n = new Name(); - n.setLang("en"); - n.setValue("%JUDDI_571_Part3_Test%"); - fb.setName(n); - fb.setFindQualifiers(new FindQualifiers()); - fb.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); - try { - TModelList findTModel = inquiry.findTModel(fb); - if (findTModel.getTModelInfos() != null) { - for (int i = 0; i < findTModel.getTModelInfos().getTModelInfo().size(); i++) { - if (businesskeysToDelete.contains(findTModel.getTModelInfos().getTModelInfo().get(i).getTModelKey())) { - found1++; - } - } - } - } catch (Exception ex) { - HandleException(ex); - Assert.fail("unexpected failure"); - } - if (found1 != 1) { - failuremsg += "Lang defined, " + found1 + " records found instead of 1"; - } - - - DeleteTModels(businesskeysToDelete); - if (failuremsg.length() > 0) { - Assert.fail(failuremsg); - } - System.out.println("Pass"); - - } - - @Test - public void JUDDI_574() { - //make a test model with a lang - - //search for it by name - - //confirm that the lang is present - - List businesskeysToDelete = new ArrayList(); - - String failuremsg = ""; - System.out.println("JUDDI_574"); - SaveTModel sb = new SaveTModel(); - sb.setAuthInfo(authInfoJoe); - TModel be = new TModel(); - be.setTModelKey(TckTModel.JOE_PUBLISHER_KEY_PREFIX + UUID.randomUUID().toString()); - Name n = new Name(); - n.setValue("JUDDI_574"); - n.setLang("en"); - be.setName(n); - sb.getTModel().add(be); - - try { - TModelDetail saveTModel = publication.saveTModel(sb); - businesskeysToDelete.add(saveTModel.getTModel().get(0).getTModelKey()); - System.out.println("tmodel created with key " + saveTModel.getTModel().get(0).getTModelKey()); - } catch (Exception ex) { - HandleException(ex); - Assert.fail("unexpected failure"); - } - int found1 = 0; - FindTModel fb = new FindTModel(); - fb.setAuthInfo(authInfoJoe); - n = new Name(); - n.setValue("JUDDI_574"); - fb.setName(n); - fb.setFindQualifiers(new FindQualifiers()); - fb.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); - try { - TModelList findTModel = inquiry.findTModel(fb); - if (findTModel.getTModelInfos() != null) { - for (int i = 0; i < findTModel.getTModelInfos().getTModelInfo().size(); i++) { - if (businesskeysToDelete.contains(findTModel.getTModelInfos().getTModelInfo().get(i).getTModelKey())) { - found1++; - if (findTModel.getTModelInfos().getTModelInfo().get(i).getName() == null - || findTModel.getTModelInfos().getTModelInfo().get(i).getName().getLang() == null - || findTModel.getTModelInfos().getTModelInfo().get(i).getName().getLang().length() == 0) { - failuremsg += "Tmodel key " + findTModel.getTModelInfos().getTModelInfo().get(i).getTModelKey() - + " has a null or empty lang"; - } - } - - } - } - } catch (Exception ex) { - HandleException(ex); - Assert.fail("unexpected failure"); - } - if (found1 != 1) { - failuremsg += "found " + found1 + " records found instead of 1"; - } - - DeleteTModels(businesskeysToDelete); - if (failuremsg.length() > 0) { - Assert.fail(failuremsg); - } - System.out.println("Pass"); - - } - - //TODO binding template tmodel instance info - //TODO tmodel tests - //TODO create tests for enforcing ref integrity of tmodel keys, after enforcing this, the tests in this class will need to be heavily revised - // - /** - * Converts category bags of tmodels to a readable string - * - * @param categoryBag - * @return - */ - public static String CatBagToString(CategoryBag categoryBag) { - StringBuilder sb = new StringBuilder(); - if (categoryBag == null) { - return "no data"; - } - for (int i = 0; i < categoryBag.getKeyedReference().size(); i++) { - sb.append(KeyedReferenceToString(categoryBag.getKeyedReference().get(i))); - } - for (int i = 0; i < categoryBag.getKeyedReferenceGroup().size(); i++) { - sb.append("Key Ref Grp: TModelKey="); - for (int k = 0; k < categoryBag.getKeyedReferenceGroup().get(i).getKeyedReference().size(); k++) { - sb.append(KeyedReferenceToString(categoryBag.getKeyedReferenceGroup().get(i).getKeyedReference().get(k))); - } - } - return sb.toString(); - } - - public static String KeyedReferenceToString(KeyedReference item) { - StringBuilder sb = new StringBuilder(); - sb.append("Key Ref: Name="). - append(item.getKeyName()). - append(" Value="). - append(item.getKeyValue()). - append(" tModel="). - append(item.getTModelKey()). - append(System.getProperty("line.separator")); - return sb.toString(); - } - - public static void PrintContacts(Contacts contacts) { - if (contacts == null) { - return; - } - for (int i = 0; i < contacts.getContact().size(); i++) { - System.out.println("Contact " + i + " type:" + contacts.getContact().get(i).getUseType()); - for (int k = 0; k < contacts.getContact().get(i).getPersonName().size(); k++) { - System.out.println("Name: " + contacts.getContact().get(i).getPersonName().get(k).getValue()); - } - for (int k = 0; k < contacts.getContact().get(i).getEmail().size(); k++) { - System.out.println("Email: " + contacts.getContact().get(i).getEmail().get(k).getValue()); - } - for (int k = 0; k < contacts.getContact().get(i).getAddress().size(); k++) { - System.out.println("Address sort code " + contacts.getContact().get(i).getAddress().get(k).getSortCode()); - System.out.println("Address use type " + contacts.getContact().get(i).getAddress().get(k).getUseType()); - System.out.println("Address tmodel key " + contacts.getContact().get(i).getAddress().get(k).getTModelKey()); - for (int x = 0; x < contacts.getContact().get(i).getAddress().get(k).getAddressLine().size(); x++) { - System.out.println("Address line value " + contacts.getContact().get(i).getAddress().get(k).getAddressLine().get(x).getValue()); - System.out.println("Address line key name " + contacts.getContact().get(i).getAddress().get(k).getAddressLine().get(x).getKeyName()); - System.out.println("Address line key value " + contacts.getContact().get(i).getAddress().get(k).getAddressLine().get(x).getKeyValue()); - } - } - for (int k = 0; k < contacts.getContact().get(i).getDescription().size(); k++) { - System.out.println("Desc: " + contacts.getContact().get(i).getDescription().get(k).getValue()); - } - for (int k = 0; k < contacts.getContact().get(i).getPhone().size(); k++) { - System.out.println("Phone: " + contacts.getContact().get(i).getPhone().get(k).getValue()); - } - } - - } - - /** - * This function is useful for translating UDDI's somewhat complex data - * format to something that is more useful. - * - * @param bindingTemplates - */ - public static void PrintBindingTemplates(BindingTemplates bindingTemplates) { - if (bindingTemplates == null) { - return; - } - for (int i = 0; i < bindingTemplates.getBindingTemplate().size(); i++) { - System.out.println("Binding Key: " + bindingTemplates.getBindingTemplate().get(i).getBindingKey()); - - if (bindingTemplates.getBindingTemplate().get(i).getAccessPoint() != null) { - System.out.println("Access Point: " + bindingTemplates.getBindingTemplate().get(i).getAccessPoint().getValue() + " type " + bindingTemplates.getBindingTemplate().get(i).getAccessPoint().getUseType()); - } - - if (bindingTemplates.getBindingTemplate().get(i).getHostingRedirector() != null) { - System.out.println("Hosting Redirection: " + bindingTemplates.getBindingTemplate().get(i).getHostingRedirector().getBindingKey()); - } - } - } - - public static void PrintBusinessInfo(BusinessInfos businessInfos) { - if (businessInfos == null) { - System.out.println("No data returned"); - } else { - for (int i = 0; i < businessInfos.getBusinessInfo().size(); i++) { - System.out.println("==============================================="); - System.out.println("Business Key: " + businessInfos.getBusinessInfo().get(i).getBusinessKey()); - System.out.println("Name: " + ListToString(businessInfos.getBusinessInfo().get(i).getName())); - - System.out.println("Name: " + ListToDescString(businessInfos.getBusinessInfo().get(i).getDescription())); - System.out.println("Services:"); - PrintServiceInfo(businessInfos.getBusinessInfo().get(i).getServiceInfos()); - } - } - } - - public static String ListToString(List name) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < name.size(); i++) { - sb.append(name.get(i).getValue()).append(" "); - } - return sb.toString(); - } - - public static String ListToDescString(List name) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < name.size(); i++) { - sb.append(name.get(i).getValue()).append(" "); - } - return sb.toString(); - } - - public static void PrintServiceInfo(ServiceInfos serviceInfos) { - for (int i = 0; i < serviceInfos.getServiceInfo().size(); i++) { - System.out.println("-------------------------------------------"); - System.out.println("Service Key: " + serviceInfos.getServiceInfo().get(i).getServiceKey()); - System.out.println("Owning Business Key: " + serviceInfos.getServiceInfo().get(i).getBusinessKey()); - System.out.println("Name: " + ListToString(serviceInfos.getServiceInfo().get(i).getName())); - } - } - - public static void PrintBusinessDetails(List businessDetail) throws Exception { - - - for (int i = 0; i < businessDetail.size(); i++) { - System.out.println("Business Detail - key: " + businessDetail.get(i).getBusinessKey()); - System.out.println("Name: " + ListToString(businessDetail.get(i).getName())); - System.out.println("CategoryBag: " + CatBagToString(businessDetail.get(i).getCategoryBag())); - PrintContacts(businessDetail.get(i).getContacts()); - } - } - // - - private void DeleteBusinesses(List businesskeysToDelete) { - - - //cleanup - try { - DeleteBusiness db = new DeleteBusiness(); - db.setAuthInfo(authInfoJoe); - db.getBusinessKey().addAll(businesskeysToDelete); - publication.deleteBusiness(db); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - private void DeleteTModels(List businesskeysToDelete) { - - //cleanup - try { - DeleteTModel db = new DeleteTModel(); - db.setAuthInfo(authInfoJoe); - db.getTModelKey().addAll(businesskeysToDelete); - publication.deleteTModel(db); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - org.apache.juddi.v3.client.cryptor.DigSigUtil GetDigSig() throws CertificateException { - org.apache.juddi.v3.client.cryptor.DigSigUtil ds = new DigSigUtil(); - ds.put(DigSigUtil.SIGNATURE_KEYSTORE_FILE, "./src/test/resources/keystore.jks"); - ds.put(DigSigUtil.SIGNATURE_KEYSTORE_FILETYPE, "JKS"); - ds.put(DigSigUtil.SIGNATURE_KEYSTORE_FILE_PASSWORD, "Test"); - ds.put(DigSigUtil.SIGNATURE_KEYSTORE_KEY_ALIAS, "Test"); - ds.put(DigSigUtil.TRUSTSTORE_FILE, "./src/test/resources/truststore.jks"); - ds.put(DigSigUtil.TRUSTSTORE_FILETYPE, "JKS"); - ds.put(DigSigUtil.TRUSTSTORE_FILE_PASSWORD, "Test"); - ds.put(DigSigUtil.SIGNATURE_OPTION_CERT_INCLUSION_BASE64, "true"); - return ds; - } - - @Test() - public void JUDDI_712_SaveBusinessProjectionWithSignature() throws CertificateException { - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("JUDDI_JUDDI_712_SaveBusinessProjectionWithSignature"); - be.getName().add(n); - DigSigUtil ds = GetDigSig(); - be = ds.signUddiEntity(be); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - Assert.fail("unexpected success"); - } catch (Exception ex) { - logger.info("Expected failure: " + ex.getMessage()); - } - } - - @Test() - public void JUDDI_712_SaveBusinessProjectionNoServiceKeyWithSignature() throws CertificateException { - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("JUDDI_712_SaveBusinessProjectionNoServiceKeyWithSignature"); - be.getName().add(n); - be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - - //service has neither business or service key - BusinessService bs = new BusinessService(); - bs.getName().add(new Name("Joe's bs", null)); - be.setBusinessServices(new BusinessServices()); - be.getBusinessServices().getBusinessService().add(bs); - - DigSigUtil ds = GetDigSig(); - be = ds.signUddiEntity(be); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - Assert.fail("unexpected success"); - } catch (Exception ex) { - logger.info("Expected failure: " + ex.getMessage()); - } - } - - @Test() - public void JUDDI_712_SaveBusinessProjectionNoServiceKey2WithSignature() throws CertificateException { - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("JUDDI_712_SaveBusinessProjectionNoServiceKey2WithSignature"); - be.getName().add(n); - be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - - //service has business but not service key - BusinessService bs = new BusinessService(); - bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - bs.getName().add(new Name("Joe's bs", null)); - be.setBusinessServices(new BusinessServices()); - be.getBusinessServices().getBusinessService().add(bs); - - DigSigUtil ds = GetDigSig(); - be = ds.signUddiEntity(be); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - Assert.fail("unexpected success"); - } catch (Exception ex) { - logger.info("Expected failure: " + ex.getMessage()); - } - } - - @Test() - public void JUDDI_712_SaveBusinessProjectionNoServiceKey3WithSignature() throws CertificateException { - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("JUDDI_712_SaveBusinessProjectionNoServiceKey3WithSignature"); - be.getName().add(n); - be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - - //service has business but not service key - BusinessService bs = new BusinessService(); - //bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - bs.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); - bs.getName().add(new Name("Joe's bs", null)); - be.setBusinessServices(new BusinessServices()); - be.getBusinessServices().getBusinessService().add(bs); - - DigSigUtil ds = GetDigSig(); - be = ds.signUddiEntity(be); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - Assert.fail("unexpected success"); - } catch (Exception ex) { - logger.info("Expected failure: " + ex.getMessage()); - } - } - - @Test() - public void JUDDI_712_SaveServiceProjectionNoServiceKey3WithSignature() throws CertificateException { - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("JUDDI_712_SaveServiceProjectionNoServiceKey3WithSignature"); - be.getName().add(n); - be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - - - BusinessService bs = new BusinessService(); - bs.setBusinessKey(null); - bs.setServiceKey(null); - bs.getName().add(new Name("Joe's bs", null)); - DigSigUtil ds = GetDigSig(); - bs = ds.signUddiEntity(bs); - - be.setBusinessServices(new BusinessServices()); - be.getBusinessServices().getBusinessService().add(bs); - - - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - Assert.fail("unexpected success"); - } catch (Exception ex) { - logger.info("Expected failure: " + ex.getMessage()); - } - } - - @Test() - public void JUDDI_712_SaveServiceProjectionNoServiceKey1WithSignature() throws CertificateException { - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("JUDDI_712_SaveServiceProjectionNoServiceKey1WithSignature"); - be.getName().add(n); - be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - - - BusinessService bs = new BusinessService(); - bs.setBusinessKey(null); - bs.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); - bs.getName().add(new Name("Joe's bs", null)); - DigSigUtil ds = GetDigSig(); - bs = ds.signUddiEntity(bs); - - be.setBusinessServices(new BusinessServices()); - be.getBusinessServices().getBusinessService().add(bs); - - - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - Assert.fail("unexpected success"); - } catch (Exception ex) { - logger.info("Expected failure: " + ex.getMessage()); - } - } - - @Test() - public void JUDDI_712_SaveServiceProjectionNoServiceKey2WithSignature() throws CertificateException { - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("JUDDI_712_SaveServiceProjectionNoServiceKey2WithSignature"); - be.getName().add(n); - be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - - - BusinessService bs = new BusinessService(); - bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - bs.setServiceKey(null); - bs.getName().add(new Name("Joe's bs", null)); - DigSigUtil ds = GetDigSig(); - bs = ds.signUddiEntity(bs); - - be.setBusinessServices(new BusinessServices()); - be.getBusinessServices().getBusinessService().add(bs); - - - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - Assert.fail("unexpected success"); - } catch (Exception ex) { - logger.info("Expected failure: " + ex.getMessage()); - } - } - - @Test(expected = ValueNotAllowedException.class) - public void JUDDI_712_SaveBusinessNoneDefined() throws Exception { - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("JUDDI_712_SaveServiceWithSignature"); - be.getName().add(n); - be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - Assert.fail("unexpected success"); - } catch (Exception ex) { - logger.info("Expected failure: " + ex.getMessage()); - throw ex; - } - } - - @Test() - public void JUDDI_712_SaveServiceWithSignature() throws CertificateException { - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("JUDDI_712_SaveServiceWithSignature"); - be.getName().add(n); - be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - } catch (Exception ex) { - logger.info("UnExpected failure: ", ex); - Assert.fail(); - } - - SaveService ss = new SaveService(); - ss.setAuthInfo(authInfoJoe); - BusinessService bs = new BusinessService(); - bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - bs.setServiceKey(null); - bs.getName().add(new Name("Joe's bs", null)); - DigSigUtil ds = GetDigSig(); - bs = ds.signUddiEntity(bs); - - be.setBusinessServices(new BusinessServices()); - be.getBusinessServices().getBusinessService().add(bs); - - - sb.getBusinessEntity().add(be); - try { - publication.saveService(ss); - Assert.fail("unexpected success"); - } catch (Exception ex) { - logger.info("Expected failure: " + ex.getMessage()); - } - } - - @Test() - public void JUDDI_712_SaveService1WithSignature() throws CertificateException { - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("JUDDI_712_SaveService1WithSignature"); - be.getName().add(n); - be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - } catch (Exception ex) { - logger.info("UnExpected failure: ", ex); - Assert.fail(); - } - - SaveService ss = new SaveService(); - ss.setAuthInfo(authInfoJoe); - BusinessService bs = new BusinessService(); - bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - bs.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); - bs.setBindingTemplates(new BindingTemplates()); - BindingTemplate bt = new BindingTemplate(); - bt.setBindingKey(null); - bt.setServiceKey(null); - bt.setAccessPoint(new AccessPoint("http://localhost", "wsdl")); - bs.getBindingTemplates().getBindingTemplate().add(bt); - bs.getName().add(new Name("Joe's bs", null)); - DigSigUtil ds = GetDigSig(); - bs = ds.signUddiEntity(bs); - - be.setBusinessServices(new BusinessServices()); - be.getBusinessServices().getBusinessService().add(bs); - - - sb.getBusinessEntity().add(be); - try { - publication.saveService(ss); - Assert.fail("unexpected success"); - } catch (Exception ex) { - logger.info("Expected failure: " + ex.getMessage()); - } - } - - @Test() - public void JUDDI_712_SaveService2WithSignature() throws CertificateException { - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("JUDDI_712_SaveService2WithSignature"); - be.getName().add(n); - be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - } catch (Exception ex) { - logger.info("UnExpected failure: ", ex); - Assert.fail(); - } - - SaveService ss = new SaveService(); - ss.setAuthInfo(authInfoJoe); - BusinessService bs = new BusinessService(); - bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - bs.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); - bs.setBindingTemplates(new BindingTemplates()); - BindingTemplate bt = new BindingTemplate(); - bt.setBindingKey(null); - bt.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); - bt.setAccessPoint(new AccessPoint("http://localhost", "wsdl")); - bs.getBindingTemplates().getBindingTemplate().add(bt); - bs.getName().add(new Name("Joe's bs", null)); - DigSigUtil ds = GetDigSig(); - bs = ds.signUddiEntity(bs); - - be.setBusinessServices(new BusinessServices()); - be.getBusinessServices().getBusinessService().add(bs); - - - sb.getBusinessEntity().add(be); - try { - publication.saveService(ss); - Assert.fail("unexpected success"); - } catch (Exception ex) { - logger.info("Expected failure: " + ex.getMessage()); - } - } - - @Test() - public void JUDDI_712_SaveService3WithSignature() throws CertificateException { - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("JUDDI_712_SaveService3WithSignature"); - be.getName().add(n); - be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - } catch (Exception ex) { - logger.info("UnExpected failure: ", ex); - Assert.fail(); - } - - SaveService ss = new SaveService(); - ss.setAuthInfo(authInfoJoe); - BusinessService bs = new BusinessService(); - bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - bs.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); - bs.setBindingTemplates(new BindingTemplates()); - BindingTemplate bt = new BindingTemplate(); - bt.setBindingKey(TckBusinessService.JOE_BINDING_KEY_1); - bt.setServiceKey(null); - bt.setAccessPoint(new AccessPoint("http://localhost", "wsdl")); - bs.getBindingTemplates().getBindingTemplate().add(bt); - bs.getName().add(new Name("Joe's bs", null)); - DigSigUtil ds = GetDigSig(); - bs = ds.signUddiEntity(bs); - - be.setBusinessServices(new BusinessServices()); - be.getBusinessServices().getBusinessService().add(bs); - - - sb.getBusinessEntity().add(be); - try { - publication.saveService(ss); - Assert.fail("unexpected success"); - } catch (Exception ex) { - logger.info("Expected failure: " + ex.getMessage()); - } - } - - @Test() - public void JUDDI_712_SaveTModelWithSignature() throws CertificateException { - SaveTModel sb = new SaveTModel(); - sb.setAuthInfo(authInfoJoe); - DigSigUtil ds = GetDigSig(); - TModel bs = new TModel(); - bs.setName(new Name("Joe's Tmodel", null)); - bs = ds.signUddiEntity(bs); - - - sb.getTModel().add(bs); - try { - publication.saveTModel(sb); - Assert.fail("unexpected success"); - } catch (Exception ex) { - logger.info("Expected failure: " + ex.getMessage()); - } - } - - @Test() - public void JUDDI_712_SaveService4BTWithSignature() throws CertificateException { - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("JUDDI_712_SaveService4BTWithSignature"); - be.getName().add(n); - be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - } catch (Exception ex) { - logger.info("UnExpected failure: ", ex); - Assert.fail(); - } - - SaveService ss = new SaveService(); - ss.setAuthInfo(authInfoJoe); - BusinessService bs = new BusinessService(); - bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - bs.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); - bs.setBindingTemplates(new BindingTemplates()); - BindingTemplate bt = new BindingTemplate(); - bt.setBindingKey(TckBusinessService.JOE_BINDING_KEY_1); - bt.setServiceKey(null); - bt.setAccessPoint(new AccessPoint("http://localhost", "wsdl")); - - bs.getName().add(new Name("Joe's bs", null)); - DigSigUtil ds = GetDigSig(); - bt = ds.signUddiEntity(bt); - bs.getBindingTemplates().getBindingTemplate().add(bt); - be.setBusinessServices(new BusinessServices()); - be.getBusinessServices().getBusinessService().add(bs); - - - sb.getBusinessEntity().add(be); - try { - publication.saveService(ss); - Assert.fail("unexpected success"); - } catch (Exception ex) { - logger.info("Expected failure: " + ex.getMessage()); - } - } - - @Test() - public void JUDDI_712_SaveService5BTWithSignature() throws CertificateException { - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("JUDDI_712_SaveService5BTWithSignature"); - be.getName().add(n); - be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - } catch (Exception ex) { - logger.info("UnExpected failure: ", ex); - Assert.fail(); - } - - SaveService ss = new SaveService(); - ss.setAuthInfo(authInfoJoe); - BusinessService bs = new BusinessService(); - bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - bs.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); - bs.setBindingTemplates(new BindingTemplates()); - BindingTemplate bt = new BindingTemplate(); - bt.setBindingKey(null); - bt.setServiceKey(null); - bt.setAccessPoint(new AccessPoint("http://localhost", "wsdl")); - - bs.getName().add(new Name("Joe's bs", null)); - DigSigUtil ds = GetDigSig(); - bt = ds.signUddiEntity(bt); - bs.getBindingTemplates().getBindingTemplate().add(bt); - be.setBusinessServices(new BusinessServices()); - be.getBusinessServices().getBusinessService().add(bs); - - - sb.getBusinessEntity().add(be); - try { - publication.saveService(ss); - Assert.fail("unexpected success"); - } catch (Exception ex) { - logger.info("Expected failure: " + ex.getMessage()); - } - } - - @Test() - public void JUDDI_712_SaveService6BTWithSignature() throws CertificateException { - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("JUDDI_712_SaveService6BTWithSignature"); - be.getName().add(n); - be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - } catch (Exception ex) { - logger.info("UnExpected failure: ", ex); - Assert.fail(); - } - - SaveService ss = new SaveService(); - ss.setAuthInfo(authInfoJoe); - BusinessService bs = new BusinessService(); - bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - bs.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); - bs.setBindingTemplates(new BindingTemplates()); - BindingTemplate bt = new BindingTemplate(); - bt.setBindingKey(null); - bt.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); - bt.setAccessPoint(new AccessPoint("http://localhost", "wsdl")); - - bs.getName().add(new Name("Joe's bs", null)); - DigSigUtil ds = GetDigSig(); - bt = ds.signUddiEntity(bt); - bs.getBindingTemplates().getBindingTemplate().add(bt); - be.setBusinessServices(new BusinessServices()); - be.getBusinessServices().getBusinessService().add(bs); - - - sb.getBusinessEntity().add(be); - try { - publication.saveService(ss); - Assert.fail("unexpected success"); - } catch (Exception ex) { - logger.info("Expected failure: " + ex.getMessage()); - } - } - - @Test() - public void JUDDI_712_SaveBusinessWithSignature() throws CertificateException { - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - Name n = new Name(); - n.setValue("JUDDI_712_SaveBindingWithSignature"); - be.getName().add(n); - be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - } catch (Exception ex) { - logger.info("UnExpected failure: ", ex); - Assert.fail(); - } - - SaveService ss = new SaveService(); - ss.setAuthInfo(authInfoJoe); - BusinessService bs = new BusinessService(); - bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - bs.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); - bs.getName().add(new Name("joe's service", null)); - - - be.setBusinessServices(new BusinessServices()); - be.getBusinessServices().getBusinessService().add(bs); - - - sb.getBusinessEntity().add(be); - ServiceDetail saveService = null; - ss.getBusinessService().add(bs); - try { - saveService = publication.saveService(ss); - } catch (Exception ex) { - //logger.error("unExpected failure: ",ex); - Assert.fail("unexpected failure " + ex.getMessage() + ex.toString()); - } - - - bs = saveService.getBusinessService().get(0); - bs.setBindingTemplates(new BindingTemplates()); - BindingTemplate bt = new BindingTemplate(); - bt.setBindingKey(null); - bt.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); - bt.setAccessPoint(new AccessPoint("http://localhost", "wsdl")); - - bs.getName().add(new Name("Joe's bs", null)); - DigSigUtil ds = GetDigSig(); - bt = ds.signUddiEntity(bt); - bs.getBindingTemplates().getBindingTemplate().add(bt); - - try { - SaveBinding sb1 = new SaveBinding(); - sb1.setAuthInfo(authInfoJoe); - sb1.getBindingTemplate().add(bt); - publication.saveBinding(sb1); - Assert.fail("unexpected success"); - } catch (Exception ex) { - logger.info("Expected failure: " + ex.getMessage()); - } - } - - @Test() - public void JUDDI_716_SaveBusinessWithSignatureX509IssuerSerial() throws CertificateException { - SaveBusiness sb = new SaveBusiness(); - sb.setAuthInfo(authInfoJoe); - BusinessEntity be = new BusinessEntity(); - be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); - - Name n = new Name(); - n.setValue("JUDDI_716_SaveBusinessWithSignatureX509IssuerSerial"); - be.getName().add(n); - DigSigUtil ds = GetDigSig(); - ds.put(DigSigUtil.SIGNATURE_OPTION_CERT_INCLUSION_SERIAL, "true"); - be = ds.signUddiEntity(be); - sb.getBusinessEntity().add(be); - try { - BusinessDetail saveBusiness = publication.saveBusiness(sb); - GetBusinessDetail gsb=new GetBusinessDetail(); - gsb.setAuthInfo(authInfoJoe); - gsb.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); - BusinessDetail businessDetail = inquiry.getBusinessDetail(gsb); - PrintUDDI printer = new PrintUDDI(); - System.out.println(printer.print(businessDetail.getBusinessEntity().get(0))); - AtomicReference msg = new AtomicReference(); - boolean b=ds.verifySignedUddiEntity(businessDetail.getBusinessEntity().get(0), msg); - Assert.assertTrue(msg.get(),b ); - Assert.assertTrue(msg.get()==null || msg.get().length()==0); - - } catch (Exception ex) { - logger.error("unExpected failure: ", ex); - Assert.fail("unexpected failure"); - } - } - - @Test(expected = DispositionReportFaultMessage.class) - public void testJUDDI907_ChangeHistory() throws Exception{ - JUDDIApiImpl j = new JUDDIApiImpl(); - j.getEntityHistory(null); - Assert.fail(); - } - @Test(expected = DispositionReportFaultMessage.class) - public void testJUDDI907_ChangeHistory1() throws Exception{ - JUDDIApiImpl j = new JUDDIApiImpl(); - j.getEntityHistory(new GetEntityHistoryMessageRequest()); - Assert.fail(); - } - - @Test(expected = DispositionReportFaultMessage.class) - public void testJUDDI907_ChangeHistory2() throws Exception{ - JUDDIApiImpl j = new JUDDIApiImpl(); - GetEntityHistoryMessageRequest r = new GetEntityHistoryMessageRequest(); - r.setEntityKey(TckBusiness.JOE_BUSINESS_KEY); - j.getEntityHistory(r); - Assert.fail(); - } - - @Test - public void testJUDDI907_ChangeHistory3() throws Exception{ - TckBusiness tb = new TckBusiness(publication, inquiry); - tb.saveJoePublisherBusiness(authInfoJoe); - JUDDIApiImpl j = new JUDDIApiImpl(); - GetEntityHistoryMessageRequest r = new GetEntityHistoryMessageRequest(); - r.setEntityKey(TckBusiness.JOE_BUSINESS_KEY); - r.setAuthInfo(authInfoJoe); - GetEntityHistoryMessageResponse entityHistory = j.getEntityHistory(r); - tb.deleteJoePublisherBusiness(authInfoJoe); - Assert.assertNotNull(entityHistory); - Assert.assertNotNull(entityHistory.getChangeRecords()); - Assert.assertFalse(entityHistory.getChangeRecords().getChangeRecord().isEmpty()); - } - - @Test - public void testJUDDI907_ChangeHistory4() throws Exception{ - - JUDDIApiImpl j = new JUDDIApiImpl(); - GetEntityHistoryMessageRequest r = new GetEntityHistoryMessageRequest(); - r.setEntityKey(UUID.randomUUID().toString()); - r.setAuthInfo(authInfoJoe); - GetEntityHistoryMessageResponse entityHistory = j.getEntityHistory(r); - Assert.assertNotNull(entityHistory); - Assert.assertNotNull(entityHistory.getChangeRecords()); - Assert.assertTrue(entityHistory.getChangeRecords().getChangeRecord().isEmpty()); - - } - - - @Test - public void testJira996SubscriotionTest() throws Exception { - JUDDIApiImpl j = new JUDDIApiImpl(); - List allClientSubscriptionInfo = j.getAllClientSubscriptionInfo(authInfoJoe); - } -} +/* + * Copyright 2001-2009 The Apache Software Foundation. + * + * 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 org.apache.juddi.api.impl; + +import java.security.cert.CertificateException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; + +import javax.xml.soap.SOAPFault; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.juddi.Registry; +import org.apache.juddi.api_v3.GetEntityHistoryMessageRequest; +import org.apache.juddi.api_v3.GetEntityHistoryMessageResponse; +import org.apache.juddi.api_v3.SubscriptionWrapper; +import org.apache.juddi.jaxb.PrintUDDI; +import org.apache.juddi.v3.client.UDDIConstants; +import org.apache.juddi.v3.client.config.UDDIClient; +import org.apache.juddi.v3.client.cryptor.DigSigUtil; +import org.apache.juddi.v3.error.ValueNotAllowedException; +import org.apache.juddi.v3.tck.TckBusiness; +import org.apache.juddi.v3.tck.TckBusinessService; +import org.apache.juddi.v3.tck.TckPublisher; +import org.apache.juddi.v3.tck.TckSecurity; +import org.apache.juddi.v3.tck.TckTModel; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.uddi.api_v3.AccessPoint; +import org.uddi.api_v3.BindingTemplate; +import org.uddi.api_v3.BindingTemplates; +import org.uddi.api_v3.BusinessDetail; +import org.uddi.api_v3.BusinessEntity; +import org.uddi.api_v3.BusinessInfos; +import org.uddi.api_v3.BusinessList; +import org.uddi.api_v3.BusinessService; +import org.uddi.api_v3.BusinessServices; +import org.uddi.api_v3.CategoryBag; +import org.uddi.api_v3.Contacts; +import org.uddi.api_v3.DeleteBusiness; +import org.uddi.api_v3.DeleteTModel; +import org.uddi.api_v3.Description; +import org.uddi.api_v3.FindBusiness; +import org.uddi.api_v3.FindQualifiers; +import org.uddi.api_v3.FindService; +import org.uddi.api_v3.FindTModel; +import org.uddi.api_v3.GetBusinessDetail; +import org.uddi.api_v3.KeyedReference; +import org.uddi.api_v3.Name; +import org.uddi.api_v3.SaveBinding; +import org.uddi.api_v3.SaveBusiness; +import org.uddi.api_v3.SaveService; +import org.uddi.api_v3.SaveTModel; +import org.uddi.api_v3.ServiceDetail; +import org.uddi.api_v3.ServiceInfos; +import org.uddi.api_v3.ServiceList; +import org.uddi.api_v3.TModel; +import org.uddi.api_v3.TModelDetail; +import org.uddi.api_v3.TModelList; +import org.uddi.v3_service.DispositionReportFaultMessage; +import org.uddi.v3_service.UDDIInquiryPortType; +import org.uddi.v3_service.UDDIPublicationPortType; +import org.uddi.v3_service.UDDISecurityPortType; + +/** + * This test class provides test cases of items discovered or reported through + * the Juddi JIRA issue tracker The idea is that these tests apply to any UDDI + * registry and that the tests are either implied or derived requirements + * defined in the UDDI spec that were missed in other test cases for Juddi. + * + * @author Alex O'Ree + */ +public class API_141_JIRATest { + + private static Log logger = LogFactory.getLog(API_141_JIRATest.class); + static UDDISecurityPortType security = new UDDISecurityImpl(); + static UDDIInquiryPortType inquiry = new UDDIInquiryImpl(); + static UDDIPublicationPortType publication = new UDDIPublicationImpl(); + static TckTModel tckTModel = new TckTModel(new UDDIPublicationImpl(), new UDDIInquiryImpl()); + protected static String authInfoJoe = null; + protected static String authInfoSam = null; + private static UDDIClient manager; + static final String str256 = "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"; + static final String str255 = "uddi:tmodelkey:categories:1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"; + static final String strkey256 = "uddi:tmodelkey:categories:11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"; + static final String strkey256_1 = "uddi:org.apache:omething.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.something.somethi.com"; + static final String str26 = "11111111111111111111111111"; + static final String str27 = "111111111111111111111111110"; + static final String str10 = "0123456789"; + static final String str11 = "01234567890"; + static final String str80 = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; + static final String str81 = "012345678901234567890123456789012345678901234567890123456789012345678901234567891"; + static final String TRANS = "The transaction has been rolled back"; + static final String str4096 = "12345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000XXXXXXXX"; + static final String str4097 = "12345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234567000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000XXXXXXXXZ"; + static final String str51 = "111111111111111111111111111111111111111111111111111"; + static final String str50 = "11111111111111111111111111111111111111111111111111"; + static final String MISSING_RESOURCE = "Can't find resource for bundle"; + + @AfterClass + public static void stopManager() throws ConfigurationException { + Registry.stop(); + } + + @BeforeClass + public static void startManager() throws ConfigurationException { + Registry.start(); + + logger.debug("Getting auth tokens.."); + try { + authInfoJoe = TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(), TckPublisher.getJoePassword()); + authInfoSam = TckSecurity.getAuthToken(security, TckPublisher.getSamPublisherId(), TckPublisher.getSamPassword()); + Assert.assertNotNull(authInfoJoe); + Assert.assertNotNull(authInfoSam); + String authInfoUDDI = TckSecurity.getAuthToken(security, TckPublisher.getUDDIPublisherId(), TckPublisher.getUDDIPassword()); + tckTModel.saveUDDIPublisherTmodel(authInfoUDDI); + tckTModel.saveTModels(authInfoUDDI, TckTModel.TMODELS_XML); + tckTModel.saveJoePublisherTmodel(authInfoJoe); + } catch (Exception e) { + logger.error(e.getMessage(), e); + Assert.fail("Could not obtain authInfo token."); + } + } + + static void HandleException(Exception ex) { + System.err.println("Error caught of type " + ex.getClass().getCanonicalName()); + ex.printStackTrace(); + if (ex.getMessage() != null) { + Assert.assertFalse(ex.getMessage().contains(TRANS)); + Assert.assertFalse(ex.getMessage().contains(MISSING_RESOURCE)); + } + if (ex instanceof SOAPFault) { + SOAPFault sf = (SOAPFault) ex; + if (!sf.getTextContent().contains("org.apache.juddi.v3.error.ValueNotAllowedException")) { + Assert.fail(); + } + } + } + + @Test + public void JUDDI_JIRA_571_Part1_Test() { + //add a business + //add a business with lang defined + //find business with lang defined, expecting one result + //find business without lang defined, expecting 2 results + List businesskeysToDelete = new ArrayList(); + String failuremsg = ""; + System.out.println("JUDDI_JIRA_571_Part1_Test"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + be.setBusinessKey(TckTModel.JOE_PUBLISHER_KEY_PREFIX + UUID.randomUUID().toString()); + Name n = new Name(); + n.setValue("JUDDI_JIRA_571_Part1_Test no lang"); + be.getName().add(n); + sb.getBusinessEntity().add(be); + + be = new BusinessEntity(); + be.setBusinessKey(TckTModel.JOE_PUBLISHER_KEY_PREFIX + UUID.randomUUID().toString()); + n = new Name(); + n.setValue("JUDDI_JIRA_571_Part1_Test with lang"); + n.setLang("en"); + be.getName().add(n); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + businesskeysToDelete.add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + businesskeysToDelete.add(saveBusiness.getBusinessEntity().get(1).getBusinessKey()); + + } catch (Exception ex) { + HandleException(ex); + Assert.fail("unexpected failure"); + } + + int found1 = 0; + FindBusiness fb = new FindBusiness(); + fb.setAuthInfo(authInfoJoe); + n = new Name(); + n.setValue("%"); + fb.getName().add(n); + fb.setFindQualifiers(new FindQualifiers()); + fb.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); + try { + BusinessList findBusiness = inquiry.findBusiness(fb); + if (findBusiness.getBusinessInfos() != null) { + for (int i = 0; i < findBusiness.getBusinessInfos().getBusinessInfo().size(); i++) { + if (businesskeysToDelete.contains(findBusiness.getBusinessInfos().getBusinessInfo().get(i).getBusinessKey())) { + found1++; + } + } + } + } catch (Exception ex) { + HandleException(ex); + Assert.fail("unexpected failure"); + } + if (found1 != 2) { + failuremsg += "No lang defined, " + found1 + " records found instead of 2"; + } + + + + found1 = 0; + fb = new FindBusiness(); + fb.setAuthInfo(authInfoJoe); + n = new Name(); + n.setLang("en"); + n.setValue("%"); + fb.getName().add(n); + fb.setFindQualifiers(new FindQualifiers()); + fb.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); + try { + BusinessList findBusiness = inquiry.findBusiness(fb); + if (findBusiness.getBusinessInfos() != null) { + for (int i = 0; i < findBusiness.getBusinessInfos().getBusinessInfo().size(); i++) { + if (businesskeysToDelete.contains(findBusiness.getBusinessInfos().getBusinessInfo().get(i).getBusinessKey())) { + found1++; + } + } + } + } catch (Exception ex) { + HandleException(ex); + Assert.fail("unexpected failure"); + } + if (found1 != 1) { + failuremsg += "Lang defined, " + found1 + " records found instead of 1"; + } + + + DeleteBusinesses(businesskeysToDelete); + if (failuremsg.length() > 0) { + Assert.fail(failuremsg); + } + System.out.println("Pass"); + + } + + @Test + public void JUDDI_JIRA_571_Part2_Test() { + //add a service + //add a service with lang defined + //find service with lang defined, expecting one result + //find service without lang defined, expecting 2 results + + + + List businesskeysToDelete = new ArrayList(); + List targetServiceKeys = new ArrayList(); + String failuremsg = ""; + System.out.println("JUDDI_JIRA_571_Part2_Test"); + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + be.setBusinessKey(TckTModel.JOE_PUBLISHER_KEY_PREFIX + UUID.randomUUID().toString()); + Name n = new Name(); + n.setValue("JUDDI_JIRA_571_Part2_Test no lang"); + be.getName().add(n); + sb.getBusinessEntity().add(be); + + BusinessService bs = new BusinessService(); + n = new Name(); + bs.setServiceKey(TckTModel.JOE_PUBLISHER_KEY_PREFIX + UUID.randomUUID().toString()); + bs.setBusinessKey(be.getBusinessKey()); + n.setValue("Service1 No Lang"); + bs.getName().add(n); + be.setBusinessServices(new BusinessServices()); + be.getBusinessServices().getBusinessService().add(bs); + + bs = new BusinessService(); + bs.setServiceKey(TckTModel.JOE_PUBLISHER_KEY_PREFIX + UUID.randomUUID().toString()); + bs.setBusinessKey(be.getBusinessKey()); + n = new Name(); + n.setValue("Service2 Lang"); + n.setLang("en"); + bs.getName().add(n); + be.getBusinessServices().getBusinessService().add(bs); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + businesskeysToDelete.add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + targetServiceKeys.add(saveBusiness.getBusinessEntity().get(0).getBusinessServices().getBusinessService().get(0).getServiceKey()); + targetServiceKeys.add(saveBusiness.getBusinessEntity().get(0).getBusinessServices().getBusinessService().get(1).getServiceKey()); + + } catch (Exception ex) { + HandleException(ex); + Assert.fail("unexpected failure"); + } + + int found1 = 0; + FindService fb = new FindService(); + fb.setAuthInfo(authInfoJoe); + n = new Name(); + n.setValue("%"); + fb.getName().add(n); + fb.setFindQualifiers(new FindQualifiers()); + fb.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); + try { + ServiceList findBusiness = inquiry.findService(fb); + if (findBusiness.getServiceInfos() != null) { + for (int i = 0; i < findBusiness.getServiceInfos().getServiceInfo().size(); i++) { + if (targetServiceKeys.contains(findBusiness.getServiceInfos().getServiceInfo().get(i).getServiceKey())) { + found1++; + } + } + } + } catch (Exception ex) { + HandleException(ex); + Assert.fail("unexpected failure"); + } + if (found1 != 2) { + failuremsg += "No lang defined, " + found1 + " records found instead of 2"; + } + + + + found1 = 0; + fb = new FindService(); + fb.setAuthInfo(authInfoJoe); + n = new Name(); + n.setLang("en"); + n.setValue("%"); + fb.getName().add(n); + fb.setFindQualifiers(new FindQualifiers()); + fb.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); + try { + ServiceList findBusiness = inquiry.findService(fb); + if (findBusiness.getServiceInfos() != null) { + for (int i = 0; i < findBusiness.getServiceInfos().getServiceInfo().size(); i++) { + if (businesskeysToDelete.contains(findBusiness.getServiceInfos().getServiceInfo().get(i).getBusinessKey())) { + found1++; + } + } + } + } catch (Exception ex) { + HandleException(ex); + Assert.fail("unexpected failure"); + } + if (found1 != 1) { + failuremsg += "Lang defined, " + found1 + " records found instead of 1"; + } + + + DeleteBusinesses(businesskeysToDelete); + if (failuremsg.length() > 0) { + Assert.fail(failuremsg); + } + System.out.println("Pass"); + + } + + @Test + public void JUDDI_571_Part3_Test() { + //add a tmodel + //add a tmodel with lang defined + //find tmodel with lang defined, expecting one result + //find tmodel without lang defined, expecting 2 results + + + List businesskeysToDelete = new ArrayList(); + + String failuremsg = ""; + System.out.println("JUDDI_571_Part3_Test"); + SaveTModel sb = new SaveTModel(); + sb.setAuthInfo(authInfoJoe); + TModel be = new TModel(); + be.setTModelKey(TckTModel.JOE_PUBLISHER_KEY_PREFIX + UUID.randomUUID().toString()); + Name n = new Name(); + n.setValue("JUDDI_571_Part3_Test no lang"); + be.setName(n); + sb.getTModel().add(be); + + be = new TModel(); + be.setTModelKey(TckTModel.JOE_PUBLISHER_KEY_PREFIX + UUID.randomUUID().toString()); + n = new Name(); + n.setValue("JUDDI_571_Part3_Test lang"); + n.setLang("en"); + be.setName(n); + sb.getTModel().add(be); + + try { + TModelDetail saveTModel = publication.saveTModel(sb); + businesskeysToDelete.add(saveTModel.getTModel().get(0).getTModelKey()); + businesskeysToDelete.add(saveTModel.getTModel().get(1).getTModelKey()); + } catch (Exception ex) { + HandleException(ex); + Assert.fail("unexpected failure"); + } + + int found1 = 0; + FindTModel fb = new FindTModel(); + fb.setAuthInfo(authInfoJoe); + n = new Name(); + n.setValue("%JUDDI_571_Part3_Test%"); + fb.setName(n); + fb.setFindQualifiers(new FindQualifiers()); + fb.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); + try { + TModelList findTModel = inquiry.findTModel(fb); + if (findTModel.getTModelInfos() != null) { + for (int i = 0; i < findTModel.getTModelInfos().getTModelInfo().size(); i++) { + if (businesskeysToDelete.contains(findTModel.getTModelInfos().getTModelInfo().get(i).getTModelKey())) { + found1++; + } + } + } + } catch (Exception ex) { + HandleException(ex); + Assert.fail("unexpected failure"); + } + if (found1 != 2) { + failuremsg += "No lang defined, " + found1 + " records found instead of 2"; + } + + + + found1 = 0; + fb = new FindTModel(); + fb.setAuthInfo(authInfoJoe); + n = new Name(); + n.setLang("en"); + n.setValue("%JUDDI_571_Part3_Test%"); + fb.setName(n); + fb.setFindQualifiers(new FindQualifiers()); + fb.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); + try { + TModelList findTModel = inquiry.findTModel(fb); + if (findTModel.getTModelInfos() != null) { + for (int i = 0; i < findTModel.getTModelInfos().getTModelInfo().size(); i++) { + if (businesskeysToDelete.contains(findTModel.getTModelInfos().getTModelInfo().get(i).getTModelKey())) { + found1++; + } + } + } + } catch (Exception ex) { + HandleException(ex); + Assert.fail("unexpected failure"); + } + if (found1 != 1) { + failuremsg += "Lang defined, " + found1 + " records found instead of 1"; + } + + + DeleteTModels(businesskeysToDelete); + if (failuremsg.length() > 0) { + Assert.fail(failuremsg); + } + System.out.println("Pass"); + + } + + @Test + public void JUDDI_574() { + //make a test model with a lang + + //search for it by name + + //confirm that the lang is present + + List businesskeysToDelete = new ArrayList(); + + String failuremsg = ""; + System.out.println("JUDDI_574"); + SaveTModel sb = new SaveTModel(); + sb.setAuthInfo(authInfoJoe); + TModel be = new TModel(); + be.setTModelKey(TckTModel.JOE_PUBLISHER_KEY_PREFIX + UUID.randomUUID().toString()); + Name n = new Name(); + n.setValue("JUDDI_574"); + n.setLang("en"); + be.setName(n); + sb.getTModel().add(be); + + try { + TModelDetail saveTModel = publication.saveTModel(sb); + businesskeysToDelete.add(saveTModel.getTModel().get(0).getTModelKey()); + System.out.println("tmodel created with key " + saveTModel.getTModel().get(0).getTModelKey()); + } catch (Exception ex) { + HandleException(ex); + Assert.fail("unexpected failure"); + } + int found1 = 0; + FindTModel fb = new FindTModel(); + fb.setAuthInfo(authInfoJoe); + n = new Name(); + n.setValue("JUDDI_574"); + fb.setName(n); + fb.setFindQualifiers(new FindQualifiers()); + fb.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH); + try { + TModelList findTModel = inquiry.findTModel(fb); + if (findTModel.getTModelInfos() != null) { + for (int i = 0; i < findTModel.getTModelInfos().getTModelInfo().size(); i++) { + if (businesskeysToDelete.contains(findTModel.getTModelInfos().getTModelInfo().get(i).getTModelKey())) { + found1++; + if (findTModel.getTModelInfos().getTModelInfo().get(i).getName() == null + || findTModel.getTModelInfos().getTModelInfo().get(i).getName().getLang() == null + || findTModel.getTModelInfos().getTModelInfo().get(i).getName().getLang().length() == 0) { + failuremsg += "Tmodel key " + findTModel.getTModelInfos().getTModelInfo().get(i).getTModelKey() + + " has a null or empty lang"; + } + } + + } + } + } catch (Exception ex) { + HandleException(ex); + Assert.fail("unexpected failure"); + } + if (found1 != 1) { + failuremsg += "found " + found1 + " records found instead of 1"; + } + + DeleteTModels(businesskeysToDelete); + if (failuremsg.length() > 0) { + Assert.fail(failuremsg); + } + System.out.println("Pass"); + + } + + //TODO binding template tmodel instance info + //TODO tmodel tests + //TODO create tests for enforcing ref integrity of tmodel keys, after enforcing this, the tests in this class will need to be heavily revised + // + /** + * Converts category bags of tmodels to a readable string + * + * @param categoryBag + * @return + */ + public static String CatBagToString(CategoryBag categoryBag) { + StringBuilder sb = new StringBuilder(); + if (categoryBag == null) { + return "no data"; + } + for (int i = 0; i < categoryBag.getKeyedReference().size(); i++) { + sb.append(KeyedReferenceToString(categoryBag.getKeyedReference().get(i))); + } + for (int i = 0; i < categoryBag.getKeyedReferenceGroup().size(); i++) { + sb.append("Key Ref Grp: TModelKey="); + for (int k = 0; k < categoryBag.getKeyedReferenceGroup().get(i).getKeyedReference().size(); k++) { + sb.append(KeyedReferenceToString(categoryBag.getKeyedReferenceGroup().get(i).getKeyedReference().get(k))); + } + } + return sb.toString(); + } + + public static String KeyedReferenceToString(KeyedReference item) { + StringBuilder sb = new StringBuilder(); + sb.append("Key Ref: Name="). + append(item.getKeyName()). + append(" Value="). + append(item.getKeyValue()). + append(" tModel="). + append(item.getTModelKey()). + append(System.getProperty("line.separator")); + return sb.toString(); + } + + public static void PrintContacts(Contacts contacts) { + if (contacts == null) { + return; + } + for (int i = 0; i < contacts.getContact().size(); i++) { + System.out.println("Contact " + i + " type:" + contacts.getContact().get(i).getUseType()); + for (int k = 0; k < contacts.getContact().get(i).getPersonName().size(); k++) { + System.out.println("Name: " + contacts.getContact().get(i).getPersonName().get(k).getValue()); + } + for (int k = 0; k < contacts.getContact().get(i).getEmail().size(); k++) { + System.out.println("Email: " + contacts.getContact().get(i).getEmail().get(k).getValue()); + } + for (int k = 0; k < contacts.getContact().get(i).getAddress().size(); k++) { + System.out.println("Address sort code " + contacts.getContact().get(i).getAddress().get(k).getSortCode()); + System.out.println("Address use type " + contacts.getContact().get(i).getAddress().get(k).getUseType()); + System.out.println("Address tmodel key " + contacts.getContact().get(i).getAddress().get(k).getTModelKey()); + for (int x = 0; x < contacts.getContact().get(i).getAddress().get(k).getAddressLine().size(); x++) { + System.out.println("Address line value " + contacts.getContact().get(i).getAddress().get(k).getAddressLine().get(x).getValue()); + System.out.println("Address line key name " + contacts.getContact().get(i).getAddress().get(k).getAddressLine().get(x).getKeyName()); + System.out.println("Address line key value " + contacts.getContact().get(i).getAddress().get(k).getAddressLine().get(x).getKeyValue()); + } + } + for (int k = 0; k < contacts.getContact().get(i).getDescription().size(); k++) { + System.out.println("Desc: " + contacts.getContact().get(i).getDescription().get(k).getValue()); + } + for (int k = 0; k < contacts.getContact().get(i).getPhone().size(); k++) { + System.out.println("Phone: " + contacts.getContact().get(i).getPhone().get(k).getValue()); + } + } + + } + + /** + * This function is useful for translating UDDI's somewhat complex data + * format to something that is more useful. + * + * @param bindingTemplates + */ + public static void PrintBindingTemplates(BindingTemplates bindingTemplates) { + if (bindingTemplates == null) { + return; + } + for (int i = 0; i < bindingTemplates.getBindingTemplate().size(); i++) { + System.out.println("Binding Key: " + bindingTemplates.getBindingTemplate().get(i).getBindingKey()); + + if (bindingTemplates.getBindingTemplate().get(i).getAccessPoint() != null) { + System.out.println("Access Point: " + bindingTemplates.getBindingTemplate().get(i).getAccessPoint().getValue() + " type " + bindingTemplates.getBindingTemplate().get(i).getAccessPoint().getUseType()); + } + + if (bindingTemplates.getBindingTemplate().get(i).getHostingRedirector() != null) { + System.out.println("Hosting Redirection: " + bindingTemplates.getBindingTemplate().get(i).getHostingRedirector().getBindingKey()); + } + } + } + + public static void PrintBusinessInfo(BusinessInfos businessInfos) { + if (businessInfos == null) { + System.out.println("No data returned"); + } else { + for (int i = 0; i < businessInfos.getBusinessInfo().size(); i++) { + System.out.println("==============================================="); + System.out.println("Business Key: " + businessInfos.getBusinessInfo().get(i).getBusinessKey()); + System.out.println("Name: " + ListToString(businessInfos.getBusinessInfo().get(i).getName())); + + System.out.println("Name: " + ListToDescString(businessInfos.getBusinessInfo().get(i).getDescription())); + System.out.println("Services:"); + PrintServiceInfo(businessInfos.getBusinessInfo().get(i).getServiceInfos()); + } + } + } + + public static String ListToString(List name) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < name.size(); i++) { + sb.append(name.get(i).getValue()).append(" "); + } + return sb.toString(); + } + + public static String ListToDescString(List name) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < name.size(); i++) { + sb.append(name.get(i).getValue()).append(" "); + } + return sb.toString(); + } + + public static void PrintServiceInfo(ServiceInfos serviceInfos) { + for (int i = 0; i < serviceInfos.getServiceInfo().size(); i++) { + System.out.println("-------------------------------------------"); + System.out.println("Service Key: " + serviceInfos.getServiceInfo().get(i).getServiceKey()); + System.out.println("Owning Business Key: " + serviceInfos.getServiceInfo().get(i).getBusinessKey()); + System.out.println("Name: " + ListToString(serviceInfos.getServiceInfo().get(i).getName())); + } + } + + public static void PrintBusinessDetails(List businessDetail) throws Exception { + + + for (int i = 0; i < businessDetail.size(); i++) { + System.out.println("Business Detail - key: " + businessDetail.get(i).getBusinessKey()); + System.out.println("Name: " + ListToString(businessDetail.get(i).getName())); + System.out.println("CategoryBag: " + CatBagToString(businessDetail.get(i).getCategoryBag())); + PrintContacts(businessDetail.get(i).getContacts()); + } + } + // + + private void DeleteBusinesses(List businesskeysToDelete) { + + + //cleanup + try { + DeleteBusiness db = new DeleteBusiness(); + db.setAuthInfo(authInfoJoe); + db.getBusinessKey().addAll(businesskeysToDelete); + publication.deleteBusiness(db); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + private void DeleteTModels(List businesskeysToDelete) { + + //cleanup + try { + DeleteTModel db = new DeleteTModel(); + db.setAuthInfo(authInfoJoe); + db.getTModelKey().addAll(businesskeysToDelete); + publication.deleteTModel(db); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + org.apache.juddi.v3.client.cryptor.DigSigUtil GetDigSig() throws CertificateException { + org.apache.juddi.v3.client.cryptor.DigSigUtil ds = new DigSigUtil(); + ds.put(DigSigUtil.SIGNATURE_KEYSTORE_FILE, "./src/test/resources/keystore.jks"); + ds.put(DigSigUtil.SIGNATURE_KEYSTORE_FILETYPE, "JKS"); + ds.put(DigSigUtil.SIGNATURE_KEYSTORE_FILE_PASSWORD, "Test"); + ds.put(DigSigUtil.SIGNATURE_KEYSTORE_KEY_ALIAS, "Test"); + ds.put(DigSigUtil.TRUSTSTORE_FILE, "./src/test/resources/truststore.jks"); + ds.put(DigSigUtil.TRUSTSTORE_FILETYPE, "JKS"); + ds.put(DigSigUtil.TRUSTSTORE_FILE_PASSWORD, "Test"); + ds.put(DigSigUtil.SIGNATURE_OPTION_CERT_INCLUSION_BASE64, "true"); + return ds; + } + + @Test() + public void JUDDI_712_SaveBusinessProjectionWithSignature() throws CertificateException { + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("JUDDI_JUDDI_712_SaveBusinessProjectionWithSignature"); + be.getName().add(n); + DigSigUtil ds = GetDigSig(); + be = ds.signUddiEntity(be); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + Assert.fail("unexpected success"); + } catch (Exception ex) { + logger.info("Expected failure: " + ex.getMessage()); + } + } + + @Test() + public void JUDDI_712_SaveBusinessProjectionNoServiceKeyWithSignature() throws CertificateException { + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("JUDDI_712_SaveBusinessProjectionNoServiceKeyWithSignature"); + be.getName().add(n); + be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + + //service has neither business or service key + BusinessService bs = new BusinessService(); + bs.getName().add(new Name("Joe's bs", null)); + be.setBusinessServices(new BusinessServices()); + be.getBusinessServices().getBusinessService().add(bs); + + DigSigUtil ds = GetDigSig(); + be = ds.signUddiEntity(be); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + Assert.fail("unexpected success"); + } catch (Exception ex) { + logger.info("Expected failure: " + ex.getMessage()); + } + } + + @Test() + public void JUDDI_712_SaveBusinessProjectionNoServiceKey2WithSignature() throws CertificateException { + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("JUDDI_712_SaveBusinessProjectionNoServiceKey2WithSignature"); + be.getName().add(n); + be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + + //service has business but not service key + BusinessService bs = new BusinessService(); + bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + bs.getName().add(new Name("Joe's bs", null)); + be.setBusinessServices(new BusinessServices()); + be.getBusinessServices().getBusinessService().add(bs); + + DigSigUtil ds = GetDigSig(); + be = ds.signUddiEntity(be); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + Assert.fail("unexpected success"); + } catch (Exception ex) { + logger.info("Expected failure: " + ex.getMessage()); + } + } + + @Test() + public void JUDDI_712_SaveBusinessProjectionNoServiceKey3WithSignature() throws CertificateException { + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("JUDDI_712_SaveBusinessProjectionNoServiceKey3WithSignature"); + be.getName().add(n); + be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + + //service has business but not service key + BusinessService bs = new BusinessService(); + //bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + bs.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); + bs.getName().add(new Name("Joe's bs", null)); + be.setBusinessServices(new BusinessServices()); + be.getBusinessServices().getBusinessService().add(bs); + + DigSigUtil ds = GetDigSig(); + be = ds.signUddiEntity(be); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + Assert.fail("unexpected success"); + } catch (Exception ex) { + logger.info("Expected failure: " + ex.getMessage()); + } + } + + @Test() + public void JUDDI_712_SaveServiceProjectionNoServiceKey3WithSignature() throws CertificateException { + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("JUDDI_712_SaveServiceProjectionNoServiceKey3WithSignature"); + be.getName().add(n); + be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + + + BusinessService bs = new BusinessService(); + bs.setBusinessKey(null); + bs.setServiceKey(null); + bs.getName().add(new Name("Joe's bs", null)); + DigSigUtil ds = GetDigSig(); + bs = ds.signUddiEntity(bs); + + be.setBusinessServices(new BusinessServices()); + be.getBusinessServices().getBusinessService().add(bs); + + + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + Assert.fail("unexpected success"); + } catch (Exception ex) { + logger.info("Expected failure: " + ex.getMessage()); + } + } + + @Test() + public void JUDDI_712_SaveServiceProjectionNoServiceKey1WithSignature() throws CertificateException { + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("JUDDI_712_SaveServiceProjectionNoServiceKey1WithSignature"); + be.getName().add(n); + be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + + + BusinessService bs = new BusinessService(); + bs.setBusinessKey(null); + bs.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); + bs.getName().add(new Name("Joe's bs", null)); + DigSigUtil ds = GetDigSig(); + bs = ds.signUddiEntity(bs); + + be.setBusinessServices(new BusinessServices()); + be.getBusinessServices().getBusinessService().add(bs); + + + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + Assert.fail("unexpected success"); + } catch (Exception ex) { + logger.info("Expected failure: " + ex.getMessage()); + } + } + + @Test() + public void JUDDI_712_SaveServiceProjectionNoServiceKey2WithSignature() throws CertificateException { + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("JUDDI_712_SaveServiceProjectionNoServiceKey2WithSignature"); + be.getName().add(n); + be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + + + BusinessService bs = new BusinessService(); + bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + bs.setServiceKey(null); + bs.getName().add(new Name("Joe's bs", null)); + DigSigUtil ds = GetDigSig(); + bs = ds.signUddiEntity(bs); + + be.setBusinessServices(new BusinessServices()); + be.getBusinessServices().getBusinessService().add(bs); + + + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + Assert.fail("unexpected success"); + } catch (Exception ex) { + logger.info("Expected failure: " + ex.getMessage()); + } + } + + @Test(expected = ValueNotAllowedException.class) + public void JUDDI_712_SaveBusinessNoneDefined() throws Exception { + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("JUDDI_712_SaveServiceWithSignature"); + be.getName().add(n); + be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + Assert.fail("unexpected success"); + } catch (Exception ex) { + logger.info("Expected failure: " + ex.getMessage()); + throw ex; + } + } + + @Test() + public void JUDDI_712_SaveServiceWithSignature() throws CertificateException { + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("JUDDI_712_SaveServiceWithSignature"); + be.getName().add(n); + be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + } catch (Exception ex) { + logger.info("UnExpected failure: ", ex); + Assert.fail(); + } + + SaveService ss = new SaveService(); + ss.setAuthInfo(authInfoJoe); + BusinessService bs = new BusinessService(); + bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + bs.setServiceKey(null); + bs.getName().add(new Name("Joe's bs", null)); + DigSigUtil ds = GetDigSig(); + bs = ds.signUddiEntity(bs); + + be.setBusinessServices(new BusinessServices()); + be.getBusinessServices().getBusinessService().add(bs); + + + sb.getBusinessEntity().add(be); + try { + publication.saveService(ss); + Assert.fail("unexpected success"); + } catch (Exception ex) { + logger.info("Expected failure: " + ex.getMessage()); + } + } + + @Test() + public void JUDDI_712_SaveService1WithSignature() throws CertificateException { + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("JUDDI_712_SaveService1WithSignature"); + be.getName().add(n); + be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + } catch (Exception ex) { + logger.info("UnExpected failure: ", ex); + Assert.fail(); + } + + SaveService ss = new SaveService(); + ss.setAuthInfo(authInfoJoe); + BusinessService bs = new BusinessService(); + bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + bs.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); + bs.setBindingTemplates(new BindingTemplates()); + BindingTemplate bt = new BindingTemplate(); + bt.setBindingKey(null); + bt.setServiceKey(null); + bt.setAccessPoint(new AccessPoint("http://localhost", "wsdl")); + bs.getBindingTemplates().getBindingTemplate().add(bt); + bs.getName().add(new Name("Joe's bs", null)); + DigSigUtil ds = GetDigSig(); + bs = ds.signUddiEntity(bs); + + be.setBusinessServices(new BusinessServices()); + be.getBusinessServices().getBusinessService().add(bs); + + + sb.getBusinessEntity().add(be); + try { + publication.saveService(ss); + Assert.fail("unexpected success"); + } catch (Exception ex) { + logger.info("Expected failure: " + ex.getMessage()); + } + } + + @Test() + public void JUDDI_712_SaveService2WithSignature() throws CertificateException { + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("JUDDI_712_SaveService2WithSignature"); + be.getName().add(n); + be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + } catch (Exception ex) { + logger.info("UnExpected failure: ", ex); + Assert.fail(); + } + + SaveService ss = new SaveService(); + ss.setAuthInfo(authInfoJoe); + BusinessService bs = new BusinessService(); + bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + bs.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); + bs.setBindingTemplates(new BindingTemplates()); + BindingTemplate bt = new BindingTemplate(); + bt.setBindingKey(null); + bt.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); + bt.setAccessPoint(new AccessPoint("http://localhost", "wsdl")); + bs.getBindingTemplates().getBindingTemplate().add(bt); + bs.getName().add(new Name("Joe's bs", null)); + DigSigUtil ds = GetDigSig(); + bs = ds.signUddiEntity(bs); + + be.setBusinessServices(new BusinessServices()); + be.getBusinessServices().getBusinessService().add(bs); + + + sb.getBusinessEntity().add(be); + try { + publication.saveService(ss); + Assert.fail("unexpected success"); + } catch (Exception ex) { + logger.info("Expected failure: " + ex.getMessage()); + } + } + + @Test() + public void JUDDI_712_SaveService3WithSignature() throws CertificateException { + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("JUDDI_712_SaveService3WithSignature"); + be.getName().add(n); + be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + } catch (Exception ex) { + logger.info("UnExpected failure: ", ex); + Assert.fail(); + } + + SaveService ss = new SaveService(); + ss.setAuthInfo(authInfoJoe); + BusinessService bs = new BusinessService(); + bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + bs.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); + bs.setBindingTemplates(new BindingTemplates()); + BindingTemplate bt = new BindingTemplate(); + bt.setBindingKey(TckBusinessService.JOE_BINDING_KEY_1); + bt.setServiceKey(null); + bt.setAccessPoint(new AccessPoint("http://localhost", "wsdl")); + bs.getBindingTemplates().getBindingTemplate().add(bt); + bs.getName().add(new Name("Joe's bs", null)); + DigSigUtil ds = GetDigSig(); + bs = ds.signUddiEntity(bs); + + be.setBusinessServices(new BusinessServices()); + be.getBusinessServices().getBusinessService().add(bs); + + + sb.getBusinessEntity().add(be); + try { + publication.saveService(ss); + Assert.fail("unexpected success"); + } catch (Exception ex) { + logger.info("Expected failure: " + ex.getMessage()); + } + } + + @Test() + public void JUDDI_712_SaveTModelWithSignature() throws CertificateException { + SaveTModel sb = new SaveTModel(); + sb.setAuthInfo(authInfoJoe); + DigSigUtil ds = GetDigSig(); + TModel bs = new TModel(); + bs.setName(new Name("Joe's Tmodel", null)); + bs = ds.signUddiEntity(bs); + + + sb.getTModel().add(bs); + try { + publication.saveTModel(sb); + Assert.fail("unexpected success"); + } catch (Exception ex) { + logger.info("Expected failure: " + ex.getMessage()); + } + } + + @Test() + public void JUDDI_712_SaveService4BTWithSignature() throws CertificateException { + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("JUDDI_712_SaveService4BTWithSignature"); + be.getName().add(n); + be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + } catch (Exception ex) { + logger.info("UnExpected failure: ", ex); + Assert.fail(); + } + + SaveService ss = new SaveService(); + ss.setAuthInfo(authInfoJoe); + BusinessService bs = new BusinessService(); + bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + bs.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); + bs.setBindingTemplates(new BindingTemplates()); + BindingTemplate bt = new BindingTemplate(); + bt.setBindingKey(TckBusinessService.JOE_BINDING_KEY_1); + bt.setServiceKey(null); + bt.setAccessPoint(new AccessPoint("http://localhost", "wsdl")); + + bs.getName().add(new Name("Joe's bs", null)); + DigSigUtil ds = GetDigSig(); + bt = ds.signUddiEntity(bt); + bs.getBindingTemplates().getBindingTemplate().add(bt); + be.setBusinessServices(new BusinessServices()); + be.getBusinessServices().getBusinessService().add(bs); + + + sb.getBusinessEntity().add(be); + try { + publication.saveService(ss); + Assert.fail("unexpected success"); + } catch (Exception ex) { + logger.info("Expected failure: " + ex.getMessage()); + } + } + + @Test() + public void JUDDI_712_SaveService5BTWithSignature() throws CertificateException { + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("JUDDI_712_SaveService5BTWithSignature"); + be.getName().add(n); + be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + } catch (Exception ex) { + logger.info("UnExpected failure: ", ex); + Assert.fail(); + } + + SaveService ss = new SaveService(); + ss.setAuthInfo(authInfoJoe); + BusinessService bs = new BusinessService(); + bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + bs.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); + bs.setBindingTemplates(new BindingTemplates()); + BindingTemplate bt = new BindingTemplate(); + bt.setBindingKey(null); + bt.setServiceKey(null); + bt.setAccessPoint(new AccessPoint("http://localhost", "wsdl")); + + bs.getName().add(new Name("Joe's bs", null)); + DigSigUtil ds = GetDigSig(); + bt = ds.signUddiEntity(bt); + bs.getBindingTemplates().getBindingTemplate().add(bt); + be.setBusinessServices(new BusinessServices()); + be.getBusinessServices().getBusinessService().add(bs); + + + sb.getBusinessEntity().add(be); + try { + publication.saveService(ss); + Assert.fail("unexpected success"); + } catch (Exception ex) { + logger.info("Expected failure: " + ex.getMessage()); + } + } + + @Test() + public void JUDDI_712_SaveService6BTWithSignature() throws CertificateException { + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("JUDDI_712_SaveService6BTWithSignature"); + be.getName().add(n); + be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + } catch (Exception ex) { + logger.info("UnExpected failure: ", ex); + Assert.fail(); + } + + SaveService ss = new SaveService(); + ss.setAuthInfo(authInfoJoe); + BusinessService bs = new BusinessService(); + bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + bs.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); + bs.setBindingTemplates(new BindingTemplates()); + BindingTemplate bt = new BindingTemplate(); + bt.setBindingKey(null); + bt.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); + bt.setAccessPoint(new AccessPoint("http://localhost", "wsdl")); + + bs.getName().add(new Name("Joe's bs", null)); + DigSigUtil ds = GetDigSig(); + bt = ds.signUddiEntity(bt); + bs.getBindingTemplates().getBindingTemplate().add(bt); + be.setBusinessServices(new BusinessServices()); + be.getBusinessServices().getBusinessService().add(bs); + + + sb.getBusinessEntity().add(be); + try { + publication.saveService(ss); + Assert.fail("unexpected success"); + } catch (Exception ex) { + logger.info("Expected failure: " + ex.getMessage()); + } + } + + @Test() + public void JUDDI_712_SaveBusinessWithSignature() throws CertificateException { + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + Name n = new Name(); + n.setValue("JUDDI_712_SaveBindingWithSignature"); + be.getName().add(n); + be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + } catch (Exception ex) { + logger.info("UnExpected failure: ", ex); + Assert.fail(); + } + + SaveService ss = new SaveService(); + ss.setAuthInfo(authInfoJoe); + BusinessService bs = new BusinessService(); + bs.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + bs.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); + bs.getName().add(new Name("joe's service", null)); + + + be.setBusinessServices(new BusinessServices()); + be.getBusinessServices().getBusinessService().add(bs); + + + sb.getBusinessEntity().add(be); + ServiceDetail saveService = null; + ss.getBusinessService().add(bs); + try { + saveService = publication.saveService(ss); + } catch (Exception ex) { + //logger.error("unExpected failure: ",ex); + Assert.fail("unexpected failure " + ex.getMessage() + ex.toString()); + } + + + bs = saveService.getBusinessService().get(0); + bs.setBindingTemplates(new BindingTemplates()); + BindingTemplate bt = new BindingTemplate(); + bt.setBindingKey(null); + bt.setServiceKey(TckBusinessService.JOE_SERVICE_KEY); + bt.setAccessPoint(new AccessPoint("http://localhost", "wsdl")); + + bs.getName().add(new Name("Joe's bs", null)); + DigSigUtil ds = GetDigSig(); + bt = ds.signUddiEntity(bt); + bs.getBindingTemplates().getBindingTemplate().add(bt); + + try { + SaveBinding sb1 = new SaveBinding(); + sb1.setAuthInfo(authInfoJoe); + sb1.getBindingTemplate().add(bt); + publication.saveBinding(sb1); + Assert.fail("unexpected success"); + } catch (Exception ex) { + logger.info("Expected failure: " + ex.getMessage()); + } + } + + @Test() + public void JUDDI_716_SaveBusinessWithSignatureX509IssuerSerial() throws CertificateException { + SaveBusiness sb = new SaveBusiness(); + sb.setAuthInfo(authInfoJoe); + BusinessEntity be = new BusinessEntity(); + be.setBusinessKey(TckBusiness.JOE_BUSINESS_KEY); + + Name n = new Name(); + n.setValue("JUDDI_716_SaveBusinessWithSignatureX509IssuerSerial"); + be.getName().add(n); + DigSigUtil ds = GetDigSig(); + ds.put(DigSigUtil.SIGNATURE_OPTION_CERT_INCLUSION_SERIAL, "true"); + be = ds.signUddiEntity(be); + sb.getBusinessEntity().add(be); + try { + BusinessDetail saveBusiness = publication.saveBusiness(sb); + GetBusinessDetail gsb=new GetBusinessDetail(); + gsb.setAuthInfo(authInfoJoe); + gsb.getBusinessKey().add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); + BusinessDetail businessDetail = inquiry.getBusinessDetail(gsb); + PrintUDDI printer = new PrintUDDI(); + System.out.println(printer.print(businessDetail.getBusinessEntity().get(0))); + AtomicReference msg = new AtomicReference(); + boolean b=ds.verifySignedUddiEntity(businessDetail.getBusinessEntity().get(0), msg); + Assert.assertTrue(msg.get(),b ); + Assert.assertTrue(msg.get()==null || msg.get().length()==0); + + } catch (Exception ex) { + logger.error("unExpected failure: ", ex); + Assert.fail("unexpected failure"); + } + } + + @Test(expected = DispositionReportFaultMessage.class) + public void testJUDDI907_ChangeHistory() throws Exception{ + JUDDIApiImpl j = new JUDDIApiImpl(); + j.getEntityHistory(null); + Assert.fail(); + } + @Test(expected = DispositionReportFaultMessage.class) + public void testJUDDI907_ChangeHistory1() throws Exception{ + JUDDIApiImpl j = new JUDDIApiImpl(); + j.getEntityHistory(new GetEntityHistoryMessageRequest()); + Assert.fail(); + } + + @Test(expected = DispositionReportFaultMessage.class) + public void testJUDDI907_ChangeHistory2() throws Exception{ + JUDDIApiImpl j = new JUDDIApiImpl(); + GetEntityHistoryMessageRequest r = new GetEntityHistoryMessageRequest(); + r.setEntityKey(TckBusiness.JOE_BUSINESS_KEY); + j.getEntityHistory(r); + Assert.fail(); + } + + @Test + public void testJUDDI907_ChangeHistory3() throws Exception{ + TckBusiness tb = new TckBusiness(publication, inquiry); + tb.saveJoePublisherBusiness(authInfoJoe); + JUDDIApiImpl j = new JUDDIApiImpl(); + GetEntityHistoryMessageRequest r = new GetEntityHistoryMessageRequest(); + r.setEntityKey(TckBusiness.JOE_BUSINESS_KEY); + r.setAuthInfo(authInfoJoe); + GetEntityHistoryMessageResponse entityHistory = j.getEntityHistory(r); + tb.deleteJoePublisherBusiness(authInfoJoe); + Assert.assertNotNull(entityHistory); + Assert.assertNotNull(entityHistory.getChangeRecords()); + Assert.assertFalse(entityHistory.getChangeRecords().getChangeRecord().isEmpty()); + } + + @Test + public void testJUDDI907_ChangeHistory4() throws Exception{ + + JUDDIApiImpl j = new JUDDIApiImpl(); + GetEntityHistoryMessageRequest r = new GetEntityHistoryMessageRequest(); + r.setEntityKey(UUID.randomUUID().toString()); + r.setAuthInfo(authInfoJoe); + GetEntityHistoryMessageResponse entityHistory = j.getEntityHistory(r); + Assert.assertNotNull(entityHistory); + Assert.assertNotNull(entityHistory.getChangeRecords()); + Assert.assertTrue(entityHistory.getChangeRecords().getChangeRecord().isEmpty()); + + } + + + @Test + public void testJira996SubscriotionTest() throws Exception { + JUDDIApiImpl j = new JUDDIApiImpl(); + List allClientSubscriptionInfo = j.getAllClientSubscriptionInfo(authInfoJoe); + } +} diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_150_ValueSetValidationTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_150_ValueSetValidationTest.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/API_150_ValueSetValidationTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_150_ValueSetValidationTest.java diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_160_ReplicationTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_160_ReplicationTest.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/API_160_ReplicationTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_160_ReplicationTest.java diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/API_170_CustodyTransferTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_170_CustodyTransferTest.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/API_170_CustodyTransferTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/API_170_CustodyTransferTest.java diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/TokenTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/TokenTest.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/TokenTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/TokenTest.java diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/UDDIPublicationImplExt.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/UDDIPublicationImplExt.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/UDDIPublicationImplExt.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/UDDIPublicationImplExt.java diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/UDDISecurityImplExt.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/UDDISecurityImplExt.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/UDDISecurityImplExt.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/UDDISecurityImplExt.java diff --git a/juddi-core/src/test/java/org/apache/juddi/api/impl/package.html b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/package.html similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/api/impl/package.html rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/impl/package.html diff --git a/juddi-core/src/test/java/org/apache/juddi/api/runtime/CLIServerTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/runtime/CLIServerTest.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/api/runtime/CLIServerTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/runtime/CLIServerTest.java diff --git a/juddi-core/src/test/java/org/apache/juddi/api/runtime/JuddiTestimpl.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/runtime/JuddiTestimpl.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/api/runtime/JuddiTestimpl.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/runtime/JuddiTestimpl.java diff --git a/juddi-core/src/test/java/org/apache/juddi/api/runtime/ReplicantImpl.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/api/runtime/ReplicantImpl.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/api/runtime/ReplicantImpl.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/api/runtime/ReplicantImpl.java diff --git a/juddi-core/src/test/java/org/apache/juddi/auth/AuthenticatorTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/auth/AuthenticatorTest.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/auth/AuthenticatorTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/auth/AuthenticatorTest.java diff --git a/juddi-core/src/test/java/org/apache/juddi/auth/MockHttpServletRequest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/auth/MockHttpServletRequest.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/auth/MockHttpServletRequest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/auth/MockHttpServletRequest.java diff --git a/juddi-core/src/test/java/org/apache/juddi/auth/MockMessageContext.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/auth/MockMessageContext.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/auth/MockMessageContext.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/auth/MockMessageContext.java diff --git a/juddi-core/src/test/java/org/apache/juddi/auth/MockWebServiceContext.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/auth/MockWebServiceContext.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/auth/MockWebServiceContext.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/auth/MockWebServiceContext.java diff --git a/juddi-core/src/test/java/org/apache/juddi/config/ApplicationConfigurationTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/config/ApplicationConfigurationTest.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/config/ApplicationConfigurationTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/config/ApplicationConfigurationTest.java diff --git a/juddi-core/src/test/java/org/apache/juddi/config/InstallTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/config/InstallTest.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/config/InstallTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/config/InstallTest.java diff --git a/juddi-core/src/test/java/org/apache/juddi/config/ReleaseVersionTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/config/ReleaseVersionTest.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/config/ReleaseVersionTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/config/ReleaseVersionTest.java diff --git a/juddi-core/src/test/java/org/apache/juddi/keygen/KeyGeneratorTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/keygen/KeyGeneratorTest.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/keygen/KeyGeneratorTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/keygen/KeyGeneratorTest.java diff --git a/juddi-core/src/test/java/org/apache/juddi/replication/ReplicationNotifierTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/replication/ReplicationNotifierTest.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/replication/ReplicationNotifierTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/replication/ReplicationNotifierTest.java diff --git a/juddi-core/src/test/java/org/apache/juddi/subscription/SubscriptionNotifierTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/subscription/SubscriptionNotifierTest.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/subscription/SubscriptionNotifierTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/subscription/SubscriptionNotifierTest.java diff --git a/juddi-core/src/test/java/org/apache/juddi/subscription/notify/NotifierTest.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/subscription/notify/NotifierTest.java similarity index 100% rename from juddi-core/src/test/java/org/apache/juddi/subscription/notify/NotifierTest.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/subscription/notify/NotifierTest.java diff --git a/juddi-core/src/test/java/org/apache/juddi/util/JPAUtil.java b/juddi-core-openjpa/src/test/java/org/apache/juddi/util/JPAUtil.java similarity index 95% rename from juddi-core/src/test/java/org/apache/juddi/util/JPAUtil.java rename to juddi-core-openjpa/src/test/java/org/apache/juddi/util/JPAUtil.java index b8620638a..da4dcbc54 100644 --- a/juddi-core/src/test/java/org/apache/juddi/util/JPAUtil.java +++ b/juddi-core-openjpa/src/test/java/org/apache/juddi/util/JPAUtil.java @@ -1,157 +1,157 @@ -/* - * Copyright 2001-2008 The Apache Software Foundation. - * - * 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 org.apache.juddi.util; - -import javax.persistence.EntityTransaction; -import javax.persistence.EntityManager; - -import javax.persistence.Query; -import java.util.List; - -import org.apache.juddi.config.PersistenceManager; - - -/** - * @author Jeff Faath - * - * Example use: - public void test() { - Object object = JPAUtil.getEntity(Tmodel.class, "uddi:juddi.apache.org:joepublisher:kEYGENERATOR"); - System.out.println("object=" + object); - } - */ -@Deprecated -public class JPAUtil { - //REMOVE Comment from Code Review: This class does not seem to be in use. Do we need it? - - public static void persistEntity(Object uddiEntity, Object entityKey) { - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - Object existingUddiEntity = em.find(uddiEntity.getClass(), entityKey); - if (existingUddiEntity != null) - em.remove(existingUddiEntity); - - em.persist(uddiEntity); - - tx.commit(); - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - public static Object getEntity(Class entityClass, Object entityKey) { - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - Object obj = em.find(entityClass, entityKey); - - tx.commit(); - return obj; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - public static void deleteEntity(Class entityClass, Object entityKey) { - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - Object obj = em.find(entityClass, entityKey); - em.remove(obj); - - tx.commit(); - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - public static List runQuery(String qry, int maxRows, int listHead) { - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - Query q = em.createQuery(qry); - q.setMaxResults(maxRows); - q.setFirstResult(listHead); - List ret = q.getResultList(); - tx.commit(); - return ret; - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - } - - public static void runUpdateQuery(String qry) { - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - Query q = em.createQuery(qry); - q.executeUpdate(); - - tx.commit(); - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - } - - public static void removeAuthTokens() { - - EntityManager em = PersistenceManager.getEntityManager(); - EntityTransaction tx = em.getTransaction(); - try { - tx.begin(); - - Query qry = em.createQuery("delete from AuthToken"); - qry.executeUpdate(); - - tx.commit(); - } finally { - if (tx.isActive()) { - tx.rollback(); - } - em.close(); - } - - } - -} +/* + * Copyright 2001-2008 The Apache Software Foundation. + * + * 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 org.apache.juddi.util; + +import javax.persistence.EntityTransaction; +import javax.persistence.EntityManager; + +import javax.persistence.Query; +import java.util.List; + +import org.apache.juddi.config.PersistenceManager; + + +/** + * @author Jeff Faath + * + * Example use: + public void test() { + Object object = JPAUtil.getEntity(Tmodel.class, "uddi:juddi.apache.org:joepublisher:kEYGENERATOR"); + System.out.println("object=" + object); + } + */ +@Deprecated +public class JPAUtil { + //REMOVE Comment from Code Review: This class does not seem to be in use. Do we need it? + + public static void persistEntity(Object uddiEntity, Object entityKey) { + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + Object existingUddiEntity = em.find(uddiEntity.getClass(), entityKey); + if (existingUddiEntity != null) + em.remove(existingUddiEntity); + + em.persist(uddiEntity); + + tx.commit(); + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + public static Object getEntity(Class entityClass, Object entityKey) { + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + Object obj = em.find(entityClass, entityKey); + + tx.commit(); + return obj; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + public static void deleteEntity(Class entityClass, Object entityKey) { + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + Object obj = em.find(entityClass, entityKey); + em.remove(obj); + + tx.commit(); + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + public static List runQuery(String qry, int maxRows, int listHead) { + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + Query q = em.createQuery(qry); + q.setMaxResults(maxRows); + q.setFirstResult(listHead); + List ret = q.getResultList(); + tx.commit(); + return ret; + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + } + + public static void runUpdateQuery(String qry) { + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + Query q = em.createQuery(qry); + q.executeUpdate(); + + tx.commit(); + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + } + + public static void removeAuthTokens() { + + EntityManager em = PersistenceManager.getEntityManager(); + EntityTransaction tx = em.getTransaction(); + try { + tx.begin(); + + Query qry = em.createQuery("delete from AuthToken"); + qry.executeUpdate(); + + tx.commit(); + } finally { + if (tx.isActive()) { + tx.rollback(); + } + em.close(); + } + + } + +} diff --git a/juddi-core-openjpa/src/test/resources/META-INF/uddi.xml b/juddi-core-openjpa/src/test/resources/META-INF/uddi.xml index 1df0c1387..234c524e2 100644 --- a/juddi-core-openjpa/src/test/resources/META-INF/uddi.xml +++ b/juddi-core-openjpa/src/test/resources/META-INF/uddi.xml @@ -16,71 +16,99 @@ * */ --> - 5000 - - - - - default - InVM jUDDI node - - - - - - org.apache.juddi.v3.client.transport.InVMTransport - org.apache.juddi.api.impl.UDDICustodyTransferImpl - org.apache.juddi.api.impl.UDDIInquiryImpl - http://${serverName}:${serverPort}/juddiv3/services/inquiryRest - org.apache.juddi.api.impl.UDDIPublicationImpl - org.apache.juddi.api.impl.UDDISecurityImpl - org.apache.juddi.api.impl.UDDISubscriptionImpl - org.apache.juddi.api.impl.UDDISubscriptionListenerImpl - org.apache.juddi.api.impl.JUDDIApiImpl - - - - - - - - keystore.jks - JKS - password - password - my special key - http://www.w3.org/2001/10/xml-exc-c14n# - RSA_SHA1 - http://www.w3.org/2000/09/xmldsig# - - truststore.jks - JKS - password + 5000 + + + + + default + InVM jUDDI node + + + + + + + org.apache.juddi.v3.client.transport.InVMTransport + org.apache.juddi.api.impl.UDDICustodyTransferImpl + org.apache.juddi.api.impl.UDDIInquiryImpl + http://${serverName}:${serverPort}/juddiv3/services/inquiryRest + org.apache.juddi.api.impl.UDDIPublicationImpl + org.apache.juddi.api.impl.UDDISecurityImpl + org.apache.juddi.api.impl.UDDISubscriptionImpl + org.apache.juddi.api.impl.UDDISubscriptionListenerImpl + org.apache.juddi.api.impl.JUDDIApiImpl + + + + jaxws + e + + + + + + + org.apache.juddi.v3.client.transport.JAXWSTransportß + org.apache.juddi.api.impl.UDDICustodyTransferImpl + org.apache.juddi.api.impl.UDDIInquiryImpl + http://${serverName}:${serverPort}/juddiv3/services/inquiryRest + org.apache.juddi.api.impl.UDDIPublicationImpl + org.apache.juddi.api.impl.UDDISecurityImpl + org.apache.juddi.api.impl.UDDISubscriptionImpl + org.apache.juddi.api.impl.UDDISubscriptionListenerImpl + org.apache.juddi.api.impl.JUDDIApiImpl + + + + + wsdl/sample.wsdl + + + + + + keystore.jks + JKS + password + password + my special key + http://www.w3.org/2001/10/xml-exc-c14n# + RSA_SHA1 + http://www.w3.org/2000/09/xmldsig# + + truststore.jks + JKS + password - true - true - true - - - uddi:somebusiness - http://MyHostname:4444/callback - false - uddi:somebusiness:someservicekey - DoNothing - - - - false - - + true + true + true + + + uddi:somebusiness + http://MyHostname:4444/callback + false + uddi:somebusiness:someservicekey + DoNothing + + + + false + + \ No newline at end of file diff --git a/juddi-core-openjpa/src/test/resources/juddi-users-hashed.xml b/juddi-core-openjpa/src/test/resources/juddi-users-hashed.xml index 75996be19..31d18fa79 100644 --- a/juddi-core-openjpa/src/test/resources/juddi-users-hashed.xml +++ b/juddi-core-openjpa/src/test/resources/juddi-users-hashed.xml @@ -1,4 +1,5 @@ + uddi:juddi.apache.org:node1 - - + + root @@ -127,9 +127,8 @@ false - - + - 15 + 30 - 15 - + 30 + + true + @@ -166,6 +167,19 @@ true + + + false + ./src/test/resources/truststore.jks + JKS + Test + + true + true + false + diff --git a/juddi-core-openjpa/src/test/resources/juddiv3-enc-aes128.xml b/juddi-core-openjpa/src/test/resources/juddiv3-enc-aes128.xml index 653041ff6..d651011af 100644 --- a/juddi-core-openjpa/src/test/resources/juddiv3-enc-aes128.xml +++ b/juddi-core-openjpa/src/test/resources/juddiv3-enc-aes128.xml @@ -34,12 +34,8 @@ uddi:juddi.apache.org:node1 - - + root - - uddi:juddi.apache.org:businesses-asf - uddi:juddi.apache.org false @@ -127,8 +123,8 @@ false - + - 15 + 30 - 15 - + 30 + + true + @@ -165,6 +163,19 @@ true + + + false + ./src/test/resources/truststore.jks + JKS + Test + + true + true + false + diff --git a/juddi-core-openjpa/src/test/resources/juddiv3-enc-aes256.xml b/juddi-core-openjpa/src/test/resources/juddiv3-enc-aes256.xml index ca9d018ee..cc0746c7b 100644 --- a/juddi-core-openjpa/src/test/resources/juddiv3-enc-aes256.xml +++ b/juddi-core-openjpa/src/test/resources/juddiv3-enc-aes256.xml @@ -34,8 +34,8 @@ uddi:juddi.apache.org:node1 - - + + root @@ -127,6 +127,8 @@ false + + @@ -142,6 +144,7 @@ org.apache.juddi.v3.auth.CryptedXMLDocAuthenticator - XML doc, encrypted org.apache.juddi.v3.auth.MD5XMLDocAuthenticator - XML doc, Hashed --> + org.apache.juddi.v3.auth.JUDDIAuthenticator - 15 + 30 - 15 + 30 + + true @@ -165,6 +170,19 @@ true + + + false + ./src/test/resources/truststore.jks + JKS + Test + + true + true + false + diff --git a/juddi-core-openjpa/src/test/resources/juddiv3-enc-default.xml b/juddi-core-openjpa/src/test/resources/juddiv3-enc-default.xml index 5e85425c3..d145c189f 100644 --- a/juddi-core-openjpa/src/test/resources/juddiv3-enc-default.xml +++ b/juddi-core-openjpa/src/test/resources/juddiv3-enc-default.xml @@ -126,6 +126,7 @@ false + @@ -152,9 +153,11 @@ - 15 + 30 - 15 + 30 + + true @@ -164,6 +167,19 @@ true + + + false + ./src/test/resources/truststore.jks + JKS + Test + + true + true + false + diff --git a/juddi-core-openjpa/src/test/resources/juddiv3.xml b/juddi-core-openjpa/src/test/resources/juddiv3.xml index 0bddb0d15..edf85838a 100644 --- a/juddi-core-openjpa/src/test/resources/juddiv3.xml +++ b/juddi-core-openjpa/src/test/resources/juddiv3.xml @@ -127,7 +127,7 @@ false - + @@ -142,9 +142,11 @@ org.apache.juddi.v3.auth.XMLDocAuthenticator - XML doc, clear text org.apache.juddi.v3.auth.CryptedXMLDocAuthenticator - XML doc, encrypted org.apache.juddi.v3.auth.MD5XMLDocAuthenticator - XML doc, Hashed + + See also, the Jboss Authenticator --> org.apache.juddi.v3.auth.JUDDIAuthenticator - - 15 + 30 - 15 + 30 + + true @@ -166,6 +170,19 @@ true + + + false + ./src/test/resources/truststore.jks + JKS + Test + + true + true + false + diff --git a/juddi-core-openjpa/src/test/resources/juddiv3DisabledTModelKeybag.xml b/juddi-core-openjpa/src/test/resources/juddiv3DisabledTModelKeybag.xml index 8c7c9cbfe..4fb1510f8 100644 --- a/juddi-core-openjpa/src/test/resources/juddiv3DisabledTModelKeybag.xml +++ b/juddi-core-openjpa/src/test/resources/juddiv3DisabledTModelKeybag.xml @@ -156,9 +156,9 @@ - 15 + 30 - 60 + 30 true @@ -170,6 +170,20 @@ true + + + false + ./src/test/resources/truststore.jks + JKS + 8133dcd169105875a711e4b8b3e03bce + + + true + true + false + diff --git a/juddi-core/.gitignore b/juddi-core/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddi-core/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddi-core/pom.xml b/juddi-core/pom.xml deleted file mode 100644 index 941e99922..000000000 --- a/juddi-core/pom.xml +++ /dev/null @@ -1,189 +0,0 @@ - - - - 4.0.0 - - org.apache.juddi - juddi-parent - 3.3.11-SNAPSHOT - - juddi-core - bundle - - jUDDI Core Services - - - - org.apache.felix - maven-bundle-plugin - - - org.apache.juddi, org.apache.juddi.api, - org.apache.juddi.api.impl, - org.apache.juddi.api.util, - org.apache.juddi.config, org.apache.juddi.config, - org.apache.juddi.cryptor, org.apache.juddi.keygen, - org.apache.juddi.mapping, org.apache.juddi.model, - org.apache.juddi.query, org.apache.juddi.query.util, - org.apache.juddi.rmi, org.apache.juddi.subscription, - org.apache.juddi.subscription.notify, - org.apache.juddi.replication, - org.apache.juddi.validation, org.apache.juddi.validation.vsv, org.apache.juddi.v3.auth, - org.apache.juddi.v3.error - juddi_install_data=src/main/resources/juddi_install_data, - src/main/resources/messages.properties - - - - - org.apache.maven.plugins - maven-antrun-plugin - 1.3 - - - generate-resources - - - - - - - run - - - - - - org.codehaus.mojo - hibernate3-maven-plugin - 2.2 - - - - - hbm2ddl - jpaconfiguration - - - - juddiDatabase - schema.ddl - false - true - false - true - - - - - - - - org.apache.juddi - uddi-ws - ${project.parent.version} - - - org.apache.juddi - juddi-client - ${project.parent.version} - - - org.apache.juddi - uddi-tck-base - ${project.parent.version} - test - - - commons-configuration - commons-configuration - - - - org.apache.commons - commons-lang3 - - - - org.hibernate - hibernate-core - - - cglib - cglib - - - - - org.hibernate - hibernate-entitymanager - - - cglib - cglib-nodep - - - commons-codec - commons-codec - - - - org.apache.geronimo.specs - geronimo-jta_1.1_spec - provided - - - org.apache.geronimo.javamail - geronimo-javamail_1.4_mail - provided - - - org.apache.derby - derby - test - - - mysql - mysql-connector-java - test - - - org.postgresql - postgresql - test - - - org.mockejb - mockejb - 0.6-beta2 - test - - - dumbster - dumbster - test - - - commons-collections - commons-collections - - - javax.servlet - servlet-api - - - org.audit4j - audit4j-core - 2.2.0 - - - - diff --git a/juddi-core/src/test/resources/META-INF/orm.xml b/juddi-core/src/test/resources/META-INF/orm.xml deleted file mode 100644 index 547a301d4..000000000 --- a/juddi-core/src/test/resources/META-INF/orm.xml +++ /dev/null @@ -1,241 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/juddi-core/src/test/resources/META-INF/persistence.xml b/juddi-core/src/test/resources/META-INF/persistence.xml deleted file mode 100644 index 725e81e54..000000000 --- a/juddi-core/src/test/resources/META-INF/persistence.xml +++ /dev/null @@ -1,118 +0,0 @@ - - - - - org.hibernate.ejb.HibernatePersistence - - org.apache.juddi.model.Address - org.apache.juddi.model.AddressLine - org.apache.juddi.model.AuthToken - org.apache.juddi.model.BindingCategoryBag - org.apache.juddi.model.BindingDescr - org.apache.juddi.model.BindingTemplate - org.apache.juddi.model.BusinessCategoryBag - org.apache.juddi.model.BusinessDescr - org.apache.juddi.model.BusinessEntity - org.apache.juddi.model.BusinessIdentifier - org.apache.juddi.model.BusinessName - org.apache.juddi.model.BusinessService - org.apache.juddi.model.CanonicalizationMethod - org.apache.juddi.model.CategoryBag - org.apache.juddi.model.Clerk - org.apache.juddi.model.ClientSubscriptionInfo - org.apache.juddi.model.Contact - org.apache.juddi.model.ContactDescr - org.apache.juddi.model.DiscoveryUrl - org.apache.juddi.model.Email - org.apache.juddi.model.InstanceDetailsDescr - org.apache.juddi.model.InstanceDetailsDocDescr - org.apache.juddi.model.KeyedReference - org.apache.juddi.model.KeyedReferenceGroup - org.apache.juddi.model.KeyDataValue - org.apache.juddi.model.KeyInfo - org.apache.juddi.model.Node - org.apache.juddi.model.ObjectType - org.apache.juddi.model.ObjectTypeContent - org.apache.juddi.model.OverviewDoc - org.apache.juddi.model.OverviewDocDescr - org.apache.juddi.model.PersonName - org.apache.juddi.model.Phone - org.apache.juddi.model.Publisher - org.apache.juddi.model.PublisherAssertion - org.apache.juddi.model.PublisherAssertionId - org.apache.juddi.model.Reference - org.apache.juddi.model.ServiceCategoryBag - org.apache.juddi.model.ServiceDescr - org.apache.juddi.model.ServiceName - org.apache.juddi.model.ServiceProjection - org.apache.juddi.model.ServiceProjectionId - org.apache.juddi.model.Signature - org.apache.juddi.model.SignatureMethod - org.apache.juddi.model.SignatureTransform - org.apache.juddi.model.SignatureTransformDataValue - org.apache.juddi.model.SignatureValue - org.apache.juddi.model.SignedInfo - org.apache.juddi.model.Subscription - org.apache.juddi.model.SubscriptionChunkToken - org.apache.juddi.model.SubscriptionMatch - org.apache.juddi.model.TempKey - org.apache.juddi.model.TempKeyPK - org.apache.juddi.model.Tmodel - org.apache.juddi.model.TmodelCategoryBag - org.apache.juddi.model.TmodelDescr - org.apache.juddi.model.TmodelIdentifier - org.apache.juddi.model.TmodelInstanceInfo - org.apache.juddi.model.TmodelInstanceInfoDescr - org.apache.juddi.model.TransferToken - org.apache.juddi.model.TransferTokenKey - org.apache.juddi.model.UddiEntity - org.apache.juddi.model.UddiEntityPublisher - org.apache.juddi.model.ValueSetValues - org.apache.juddi.model.ChangeRecord - org.apache.juddi.model.Operator - org.apache.juddi.model.ReplicationConfiguration - org.apache.juddi.model.Edge - org.apache.juddi.model.ControlMessage - org.apache.juddi.model.ReplicationConfigurationNode - org.apache.juddi.model.EdgeReceiverAlternate - - - - - - - - - - - - - - - - - - - diff --git a/juddi-core/src/test/resources/META-INF/uddi.xml b/juddi-core/src/test/resources/META-INF/uddi.xml deleted file mode 100644 index 234c524e2..000000000 --- a/juddi-core/src/test/resources/META-INF/uddi.xml +++ /dev/null @@ -1,114 +0,0 @@ - - - - 5000 - - - - - default - InVM jUDDI node - - - - - - - org.apache.juddi.v3.client.transport.InVMTransport - org.apache.juddi.api.impl.UDDICustodyTransferImpl - org.apache.juddi.api.impl.UDDIInquiryImpl - http://${serverName}:${serverPort}/juddiv3/services/inquiryRest - org.apache.juddi.api.impl.UDDIPublicationImpl - org.apache.juddi.api.impl.UDDISecurityImpl - org.apache.juddi.api.impl.UDDISubscriptionImpl - org.apache.juddi.api.impl.UDDISubscriptionListenerImpl - org.apache.juddi.api.impl.JUDDIApiImpl - - - - jaxws - e - - - - - - - org.apache.juddi.v3.client.transport.JAXWSTransportß - org.apache.juddi.api.impl.UDDICustodyTransferImpl - org.apache.juddi.api.impl.UDDIInquiryImpl - http://${serverName}:${serverPort}/juddiv3/services/inquiryRest - org.apache.juddi.api.impl.UDDIPublicationImpl - org.apache.juddi.api.impl.UDDISecurityImpl - org.apache.juddi.api.impl.UDDISubscriptionImpl - org.apache.juddi.api.impl.UDDISubscriptionListenerImpl - org.apache.juddi.api.impl.JUDDIApiImpl - - - - - wsdl/sample.wsdl - - - - - - keystore.jks - JKS - password - password - my special key - http://www.w3.org/2001/10/xml-exc-c14n# - RSA_SHA1 - http://www.w3.org/2000/09/xmldsig# - - truststore.jks - JKS - password - - true - true - true - - - uddi:somebusiness - http://MyHostname:4444/callback - false - uddi:somebusiness:someservicekey - DoNothing - - - - false - - - \ No newline at end of file diff --git a/juddi-core/src/test/resources/juddi-users-encrypted.xml b/juddi-core/src/test/resources/juddi-users-encrypted.xml deleted file mode 100644 index 6f0f93f8b..000000000 --- a/juddi-core/src/test/resources/juddi-users-encrypted.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/juddi-core/src/test/resources/juddi-users-hashed.xml b/juddi-core/src/test/resources/juddi-users-hashed.xml deleted file mode 100644 index 31d18fa79..000000000 --- a/juddi-core/src/test/resources/juddi-users-hashed.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/juddi-core/src/test/resources/juddi-users.xml b/juddi-core/src/test/resources/juddi-users.xml deleted file mode 100644 index 44c07be0d..000000000 --- a/juddi-core/src/test/resources/juddi-users.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/juddi-core/src/test/resources/juddiv3-enc-3des.xml b/juddi-core/src/test/resources/juddiv3-enc-3des.xml deleted file mode 100644 index add9726af..000000000 --- a/juddi-core/src/test/resources/juddiv3-enc-3des.xml +++ /dev/null @@ -1,222 +0,0 @@ - - - - - - - - http://localhost:8080/juddiv3 - https://localhost:8443/juddiv3 - - - uddi:juddi.apache.org:node1 - - - - root - - uddi:juddi.apache.org:businesses-asf - uddi:juddi.apache.org - - - false - - - - - juddiDatabase - - - - - - 2000 - - - - en_US - - - admin@local.localhost - - - 255 - 5 - - - - 1000 - - 1000 - - - 100 - 100 - 100 - 100 - - - - - 3 - - - - - - - 30 - - - - - 5 - - - - 1000 - - - - org.apache.juddi.uuidgen.DefaultUUIDGen - - - org.apache.juddi.v3.client.cryptor.DefaultCryptor - - - org.apache.juddi.keygen.DefaultKeyGenerator - - - - 5000 - - - 0 - - 1000 - 3 - - 600000 - false - - - - - false - - - - - org.apache.juddi.v3.auth.JUDDIAuthenticator - - - - - - 30 - - 30 - - true - - - - - - - - - true - - - false - ./src/test/resources/truststore.jks - JKS - Test - - true - true - false - - - - - - - - - - - - - - - - - - - - - - - - - - - 7WJq9dOME/hvPMmxKliDKw== - - - - \ No newline at end of file diff --git a/juddi-core/src/test/resources/juddiv3-enc-aes128.xml b/juddi-core/src/test/resources/juddiv3-enc-aes128.xml deleted file mode 100644 index d651011af..000000000 --- a/juddi-core/src/test/resources/juddiv3-enc-aes128.xml +++ /dev/null @@ -1,218 +0,0 @@ - - - - - - - - http://localhost:8080/juddiv3 - https://localhost:8443/juddiv3 - - - uddi:juddi.apache.org:node1 - - root - - - false - - - - - juddiDatabase - - - - - - 2000 - - - - en_US - - - admin@local.localhost - - - 255 - 5 - - - - 1000 - - 1000 - - - 100 - 100 - 100 - 100 - - - - - 3 - - - - - - - 30 - - - - - 5 - - - - 1000 - - - - org.apache.juddi.uuidgen.DefaultUUIDGen - - - org.apache.juddi.v3.client.cryptor.DefaultCryptor - - - org.apache.juddi.keygen.DefaultKeyGenerator - - - - 5000 - - - 0 - - 1000 - 3 - - 600000 - false - - - - - false - - - - - - org.apache.juddi.v3.auth.JUDDIAuthenticator - - - - - - 30 - - 30 - - true - - - - - - - - - true - - - false - ./src/test/resources/truststore.jks - JKS - Test - - true - true - false - - - - - - - - - - - - - - - - - - - - - - - - - - - 18604180541d172f9827e08c998db568 - - - - \ No newline at end of file diff --git a/juddi-core/src/test/resources/juddiv3-enc-aes256.xml b/juddi-core/src/test/resources/juddiv3-enc-aes256.xml deleted file mode 100644 index cc0746c7b..000000000 --- a/juddi-core/src/test/resources/juddiv3-enc-aes256.xml +++ /dev/null @@ -1,225 +0,0 @@ - - - - - - - - http://localhost:8080/juddiv3 - https://localhost:8443/juddiv3 - - - uddi:juddi.apache.org:node1 - - - - root - - uddi:juddi.apache.org:businesses-asf - uddi:juddi.apache.org - - - false - - - - - juddiDatabase - - - - - - 2000 - - - - en_US - - - admin@local.localhost - - - 255 - 5 - - - - 1000 - - 1000 - - - 100 - 100 - 100 - 100 - - - - - 3 - - - - - - - 30 - - - - - 5 - - - - 1000 - - - - org.apache.juddi.uuidgen.DefaultUUIDGen - - - org.apache.juddi.v3.client.cryptor.DefaultCryptor - - - org.apache.juddi.keygen.DefaultKeyGenerator - - - - 5000 - - - 0 - - 1000 - 3 - - 600000 - false - - - - - false - - - - - - - - org.apache.juddi.v3.auth.JUDDIAuthenticator - - - - - - 30 - - 30 - - true - - - - - - - - - true - - - false - ./src/test/resources/truststore.jks - JKS - Test - - true - true - false - - - - - - - - - - - - - - - - - - - - - - - - - - - cce2f4b3f1dfe3211408c71cd8c38ee3 - - - - \ No newline at end of file diff --git a/juddi-core/src/test/resources/juddiv3-enc-default.xml b/juddi-core/src/test/resources/juddiv3-enc-default.xml deleted file mode 100644 index d145c189f..000000000 --- a/juddi-core/src/test/resources/juddiv3-enc-default.xml +++ /dev/null @@ -1,222 +0,0 @@ - - - - - - - - http://localhost:8080/juddiv3 - https://localhost:8443/juddiv3 - - - uddi:juddi.apache.org:node1 - - - root - - uddi:juddi.apache.org:businesses-asf - uddi:juddi.apache.org - - - false - - - - - juddiDatabase - - - - - - 2000 - - - - en_US - - - admin@local.localhost - - - 255 - 5 - - - - 1000 - - 1000 - - - 100 - 100 - 100 - 100 - - - - - 3 - - - - - - - 30 - - - - - 5 - - - - 1000 - - - - org.apache.juddi.uuidgen.DefaultUUIDGen - - - org.apache.juddi.v3.client.cryptor.DefaultCryptor - - - org.apache.juddi.keygen.DefaultKeyGenerator - - - - 5000 - - - 0 - - 1000 - 3 - - 600000 - false - - - - - false - - - - - - org.apache.juddi.v3.auth.JUDDIAuthenticator - - - - - - 30 - - 30 - - true - - - - - - - - - true - - - false - ./src/test/resources/truststore.jks - JKS - Test - - true - true - false - - - - - - - - - - - - - - - - - - - - - - - - - - - +j/kXkZJftwTFTBH6Cf6IQ== - - - - \ No newline at end of file diff --git a/juddi-core/src/test/resources/juddiv3.xml b/juddi-core/src/test/resources/juddiv3.xml deleted file mode 100644 index edf85838a..000000000 --- a/juddi-core/src/test/resources/juddiv3.xml +++ /dev/null @@ -1,225 +0,0 @@ - - - - - - - - http://localhost:8080/juddiv3 - https://localhost:8443/juddiv3 - - - uddi:juddi.apache.org:node1 - - - - root - - uddi:juddi.apache.org:businesses-asf - uddi:juddi.apache.org - - - false - - - - - juddiDatabase - - - - - - 2000 - - - - en_US - - - admin@local.localhost - - - 255 - 5 - - - - 1000 - - 1000 - - - 100 - 100 - 100 - 100 - - - - - 3 - - - - - - - 30 - - - - - 5 - - - - 1000 - - - - org.apache.juddi.uuidgen.DefaultUUIDGen - - - org.apache.juddi.v3.client.cryptor.DefaultCryptor - - - org.apache.juddi.keygen.DefaultKeyGenerator - - - - 5000 - - - 0 - - 1000 - 3 - - 600000 - false - - - - - false - - - - - - org.apache.juddi.v3.auth.JUDDIAuthenticator - - - - - - 30 - - 30 - - true - - - - - - - - - true - - - false - ./src/test/resources/truststore.jks - JKS - Test - - true - true - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/juddi-core/src/test/resources/juddiv3DisabledTModelKeybag.xml b/juddi-core/src/test/resources/juddiv3DisabledTModelKeybag.xml deleted file mode 100644 index 82ea96e3e..000000000 --- a/juddi-core/src/test/resources/juddiv3DisabledTModelKeybag.xml +++ /dev/null @@ -1,230 +0,0 @@ - - - - - - - - http://localhost:8080/juddiv3 - https://localhost:8443/juddiv3 - - - uddi:juddi.apache.org:node1 - - - - root - - uddi:juddi.apache.org:businesses-asf - uddi:juddi.apache.org - - - false - - - - - juddiDatabase - - - - - - 2000 - - - - en_US - - - admin@local.localhost - - - 255 - 5 - - - - 1000 - - 1000 - - - 100 - 100 - 100 - 100 - - - - - 3 - - - - - - - 30 - - - - - 5 - - - - 1000 - - - - org.apache.juddi.uuidgen.DefaultUUIDGen - - - org.apache.juddi.v3.client.cryptor.DefaultCryptor - - - org.apache.juddi.keygen.DefaultKeyGenerator - - - - 5000 - - - 0 - - 1000 - 3 - - 600000 - false - - - - - false - - - - - - org.apache.juddi.v3.auth.JUDDIAuthenticator - - - - - - 30 - - 30 - - true - - - - - - - - - true - - - false - ./src/test/resources/truststore.jks - JKS - 8133dcd169105875a711e4b8b3e03bce - - - true - true - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - false - - - \ No newline at end of file diff --git a/juddi-core/src/test/resources/keystore.jks b/juddi-core/src/test/resources/keystore.jks deleted file mode 100644 index 436747622974720ae6ff3d395e66d5b1f82ea370..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2253 zcmd6o`8N~_8^>oeS!OD`Y6c@@Z^nqRFClC8Vk}+zGD4W_%2=)~OIcHvu}5AC#URU! zt!o=pMqJyqFIOTGuG=~9d-@aJAD$mR&vMRlzUMjL=Xm3I0{{SkP6PNeAc3v{fv2D@ zNRQPA0GI%1666Q^ERZ@)xma4gm!0l&hC{@Un?ks@R=1}jlS+rRfSG} zk^u;$5P+`=eo?$ug-UJ;l)33`RFZ|D+s`P&jyE5EzeMdT+ih4$V2p9Id-$}?B-@hH z2AYz1b@h#GGW~D#o2!$`j_^?zGsBS_Dyk0$Y+k>g=9?GgB2N18Fn(Xe3kG2Do51Ht zHe6h(8{yR>Po*~hjuuh>yeVNd-zfsp~*fz!hv{-G!pQK=%af32N2*k;lD(gCNQQ_-OPY z-{L|h?&kap?w+x}c;K`Wr|jL@Npu>c>RtZ=-txmnmIX(OzQcHTSZfS+JgCm+0sIQS zoN!!^ncceTiu|ZgtkIc#YLn=Grpw$-Bup@YKnN3V!!UG8sp;Rj%|Aq@#y;-33Z@1; zx68YOwJWaLtA$Mr^d`>S8_u{OrAey&{ zr1EYh5tfM7P#hM~F`m$pbFwjFZ{vMQTxpFu6y9h`o=tSW-@59uKLbm_|wDT<)rMOcv&hh7vtGgqiIZgJ6OpYVrYQb*}g- z|AXmf#g%f3AeCRkHFIK$MM=#>;&o2@P#!z0JSgEv7b}d2n-e%ZmaSreGxcl9uL&6H z2VRx>Y+#iQwQTfG;OH@xmUWpaO4&>;73EBDEf_oA4o#Ip`_O&Gj7)AcmZvq2iK^-( zmJ%T)#dTm*sAsvpN&C2%RJjyWCPXuMvZSh^XZ?I^*9VLPs}Ya=cKp0R*i;CovJ?xR zo8pvQny>Y2gBGckqhm0V$Plx>QH>N0vyJ;KBYs3Q5$ga;w><>qZ7(; zi_uoyJafIkd|=7Md)zJn;WxA2Y;q9lLTeNCk{))xOn@Whs(y=5b}n3z|85OP7yUji zWUG{ia%Ha<=Ja8H2We%n=`_6;`!;>Ur|9`3XXH2G@Laalyf&+kwGE@AV(;E)EKnN= zQ7g_Rzu%f1?j5wB@WmTZqqMreUt%w~`6XUq%vvfrMIn}NYzKnyg7@do(I(bjqWIGV zk9`ovwpuA|q=&I1MKQZ(Dlg8gQlKa;2_aa8L^3gBHPHYT&1%3qO;<@3vm9zq&G0`QBZhE*rSc}OY(Eyo(jsy8N>qOK zd{X@aLqP7+mM8OyavqGtLB~~L*88Q%JS`j=x7~2c?qa(k(v?~-$`b|R+eQn}rnaA| z9)NJ=No4?Kg6vTwL#KcoAJ(JY^jH9GyK} zWqkeJF>GiSDA)=DYqo?ic(&*^&el z`c=Nu-vTB9&z(LUAS;Lj1Ol?tB+R0D$f2_G+K05eR4m!?t2_T=43`uBWX_5+pTFJk z?tGbMO3P*)v+}`%rxcNj@o`%1l*Mch!~a0*tu{Z~l1Nflbh*Y&yPl%(_q2|;;AF4l zDSDC$PiJtc0Dk5%=S#P~V%Q7_+YI_r`!`}@nUfaj6;a{o7O_WuH{2Q|yX zx`qve|L}zc8`^Z%gx-(Ui=>+niWA+0t0TBVSC%O>)a&FpBZ_IwwQ@8bn^JeqXF-kI zPSt76Z%4A(R#Y|xxx4LNBPe&AjH`|>W$q0zrXgEl*;8sGHY&C|(hl;A;$P-J43+xb zUV9G*4Oy5*JFz#T-X!#{YCqxr7#p^A_$phGY5KE1ee}u^UA+3$nxXK=tv`qSk191> ug7|h;9qPe(4&GVD*%>nb84)7b#MH~hEb3NnjwV{}PlPOG2hHhFr~d&T?AoXR diff --git a/juddi-core/src/test/resources/log4j.xml b/juddi-core/src/test/resources/log4j.xml deleted file mode 100644 index db3109868..000000000 --- a/juddi-core/src/test/resources/log4j.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/juddi-core/src/test/resources/truststore.jks b/juddi-core/src/test/resources/truststore.jks deleted file mode 100644 index e75138467a6469e69163964adf6f72c785cd9ec9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 965 zcmezO_TO6u1_mY|W(3nLC8@|vN3e2*;QX|b^2DN41-Jatyp+U}%=|n< zJ_8<*c5WV4uTU2kPeWb2i|{MUtZaKMEC| zCwIU*_wh2vzCG_Ya#;VYpS4?c#nr1vH{1<=c>Gq;Pp2I&a@@~VyAL-nckqijzOd%> z(Stjfd$M}&Uh1|HJ5;e$KI*|F;k9We7xO$|GTz1XX~PGZn=gcq)@9YM$V{vKcB#2+ zjrdASr+~h%N4XzO9jgkv}n%NVh-M01((|{sP4?Rl`Y^pbj62F>Oep&f0WAcImVI` z`%Ipjt$RH!N5=WZ*)>aQ*B-Y|W;2ayd*k25&AXe4nUR4JIfQ@-3>ZQ{L9RnZZ_7@z zG~Zg#ajCc~{b$2*FNUtGYzKQeJPyk=UYU}%Y}v()8)CJzokLVo&X<`OrX<(C^>R`C zkg9FU`b}K5Zq3A#_okRHTFiUSae4LO3tlQ`@_8z}BM+^sDr@zqyX2p}xGPO%O|3}P z%NM(kDsJv+^VuD+&UCp!lyToi{=6r4qA|8fuM0kF?}}D4>XZHYF@2qa$-f?pH62Si zPE`6HmEFrT{jS}`NSo--x^ZUDG(SDQc7AC=`0LZWOy`3Gnv(=~DQ@pP@ycbg==Ij> z_rEtyw`9F{$Me!<^}m-i*KB(2t#bYS{qseCS30DWOMHG6w}p9jT+TG#=~ML9UsTGD bY_Xc^(PN=}v^0N0spH9KQf>?1O>Y4JQf_EL diff --git a/juddi-core/src/test/resources/wsdl/sample.wsdl b/juddi-core/src/test/resources/wsdl/sample.wsdl deleted file mode 100644 index f20ac1908..000000000 --- a/juddi-core/src/test/resources/wsdl/sample.wsdl +++ /dev/null @@ -1,70 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/juddi-ddl-generator/pom.xml b/juddi-ddl-generator/pom.xml index 6f0cd814e..a19fdec03 100644 --- a/juddi-ddl-generator/pom.xml +++ b/juddi-ddl-generator/pom.xml @@ -36,12 +36,13 @@ org.apache.juddi - juddi-core + juddi-core-openjpa ${project.version} org.hibernate hibernate-core + 5.4.18.Final cglib @@ -52,6 +53,7 @@ org.hibernate hibernate-entitymanager + 5.4.18.Final org.apache.derby diff --git a/juddi-dist/.gitignore b/juddi-dist/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddi-dist/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddi-dist/pom.xml b/juddi-dist/pom.xml index ad299c745..ba5f47e63 100644 --- a/juddi-dist/pom.xml +++ b/juddi-dist/pom.xml @@ -34,7 +34,7 @@ org.apache.juddi - juddi-core + juddi-core-openjpa ${project.parent.version} @@ -76,7 +76,7 @@ org.apache.juddi - juddi-core + juddi-core-openjpa ${project.parent.version} sources @@ -114,7 +114,7 @@ org.apache.juddi - juddi-core + juddi-core-openjpa ${project.parent.version} javadoc diff --git a/juddi-examples/.gitignore b/juddi-examples/.gitignore deleted file mode 100644 index d229ff0f1..000000000 --- a/juddi-examples/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/ diff --git a/juddi-examples/ValueSetValidator/pom.xml b/juddi-examples/ValueSetValidator/pom.xml index bd6b733e2..ddbc5273c 100644 --- a/juddi-examples/ValueSetValidator/pom.xml +++ b/juddi-examples/ValueSetValidator/pom.xml @@ -33,7 +33,7 @@ org.apache.juddi - juddi-core + juddi-core-openjpa ${project.version} provided diff --git a/juddi-examples/hello-world-embedded/.gitignore b/juddi-examples/hello-world-embedded/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddi-examples/hello-world-embedded/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddi-examples/hello-world-embedded/pom.xml b/juddi-examples/hello-world-embedded/pom.xml index 328fc480b..702d69908 100644 --- a/juddi-examples/hello-world-embedded/pom.xml +++ b/juddi-examples/hello-world-embedded/pom.xml @@ -40,7 +40,7 @@ org.apache.juddi - juddi-core + juddi-core-openjpa ${project.parent.version} diff --git a/juddi-examples/hello-world/.gitignore b/juddi-examples/hello-world/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddi-examples/hello-world/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddi-examples/juddi-embedded/pom.xml b/juddi-examples/juddi-embedded/pom.xml index c5e5ad0dd..b877e2d29 100644 --- a/juddi-examples/juddi-embedded/pom.xml +++ b/juddi-examples/juddi-embedded/pom.xml @@ -24,7 +24,7 @@ org.apache.juddi - juddi-core + juddi-core-openjpa ${project.version} diff --git a/juddi-examples/more-uddi-samples/.gitignore b/juddi-examples/more-uddi-samples/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddi-examples/more-uddi-samples/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddi-examples/service-version/.gitignore b/juddi-examples/service-version/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddi-examples/service-version/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddi-examples/simple-browse/.gitignore b/juddi-examples/simple-browse/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddi-examples/simple-browse/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddi-examples/simple-publish-clerk/.gitignore b/juddi-examples/simple-publish-clerk/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddi-examples/simple-publish-clerk/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddi-examples/simple-publish-portable/.gitignore b/juddi-examples/simple-publish-portable/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddi-examples/simple-publish-portable/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddi-examples/subscription-notification-amqp/pom.xml b/juddi-examples/subscription-notification-amqp/pom.xml index aadbb031c..87a0a0f56 100644 --- a/juddi-examples/subscription-notification-amqp/pom.xml +++ b/juddi-examples/subscription-notification-amqp/pom.xml @@ -44,7 +44,7 @@ org.apache.juddi - juddi-core + juddi-core-openjpa ${project.parent.version} provided diff --git a/juddi-examples/uddi-annotations/.gitignore b/juddi-examples/uddi-annotations/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddi-examples/uddi-annotations/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddi-examples/uddiv2-api-bridge-example/.gitignore b/juddi-examples/uddiv2-api-bridge-example/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddi-examples/uddiv2-api-bridge-example/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddi-examples/wsdl2uddi-lifecyle/.gitignore b/juddi-examples/wsdl2uddi-lifecyle/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddi-examples/wsdl2uddi-lifecyle/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddi-examples/wsdl2uddi/.gitignore b/juddi-examples/wsdl2uddi/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddi-examples/wsdl2uddi/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddi-extras/.gitignore b/juddi-extras/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddi-extras/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddi-gui/.gitignore b/juddi-gui/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddi-gui/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddi-rest-cxf/.gitignore b/juddi-rest-cxf/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddi-rest-cxf/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddi-rest-cxf/pom.xml b/juddi-rest-cxf/pom.xml index 7c161cffd..953083c82 100644 --- a/juddi-rest-cxf/pom.xml +++ b/juddi-rest-cxf/pom.xml @@ -39,9 +39,10 @@ org.apache.juddi - juddi-core + juddi-core-openjpa ${project.parent.version} provided + bundle org.apache.juddi diff --git a/juddi-tomcat/.gitignore b/juddi-tomcat/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddi-tomcat/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddiv3-war-repl/.gitignore b/juddiv3-war-repl/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddiv3-war-repl/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddiv3-war-repl/pom.xml b/juddiv3-war-repl/pom.xml index 80a89f419..a4322faaf 100644 --- a/juddiv3-war-repl/pom.xml +++ b/juddiv3-war-repl/pom.xml @@ -60,199 +60,7 @@ juddiv3replication - - - hibernate-jbossws-native - - false - - - - - org.apache.maven.plugins - maven-war-plugin - - - - JPA/Hibernate-JBoss - - - JAX-WS/JBossWS-Native - - - - - - - - - juddi-core - org.apache.juddi - ${project.version} - - - javax.persistence - persistence-api - 1.0 - provided - - - - org.hibernate - hibernate-entitymanager - provided - - - - - - hibernate-jbossws-cxf - - false - - - - - org.apache.maven.plugins - maven-war-plugin - - - - JPA/Hibernate-JBoss - - - JAX-WS/JBossWS-CXF - - - - - - - - - juddi-core - org.apache.juddi - ${project.version} - - - juddi-rest-cxf - org.apache.juddi - ${project.version} - - - javax.persistence - persistence-api - 1.0 - provided - - - org.hibernate - hibernate - provided - - - org.hibernate - hibernate-entitymanager - provided - - - cglib - cglib-nodep - 2.1_3 - provided - - - org.apache.cxf - cxf-rt-frontend-jaxrs - ${cxf.version} - - - org.apache.cxf - cxf-rt-rs-client - ${cxf.version} - - - org.apache.cxf - cxf-rt-rs-service-description - ${cxf.version} - - - - - - hibernate - - false - - - - - org.apache.maven.plugins - maven-war-plugin - - - - JPA/Hibernate - - - JAX-WS/CXF - - - - - - - - - juddi-core - org.apache.juddi - ${project.version} - - - juddi-rest-cxf - org.apache.juddi - ${project.version} - - - - org.apache.cxf - cxf-rt-frontend-jaxws - ${cxf.version} - - - org.apache.cxf - cxf-rt-frontend-jaxrs - ${cxf.version} - - - org.apache.cxf - cxf-rt-transports-http - ${cxf.version} - - - cglib - cglib - - - - - org.springframework - spring-context - ${springframework.version} - - - org.springframework - spring-web - ${springframework.version} - - - org.apache.geronimo.javamail - geronimo-javamail_1.4_mail - - - + @@ -360,186 +168,6 @@ - - - axis2 - - false - - - - - org.apache.maven.plugins - maven-war-plugin - - - - JPA/OpenJPA - - - JAX-WS/Axis2 - - - - - - org.apache.maven.plugins - maven-antrun-plugin - 1.6 - - - default-cli - - - - - - - - - - compile - - run - - - - - - - - - - juddi-core-openjpa - org.apache.juddi - ${project.version} - - - junit - junit - - - - - - org.apache.axis2 - axis2 - 1.6.3 - - - org.apache.axis2 - axis2-jaxws - 1.6.2 - - - org.apache.axis2 - axis2-transport-http - 1.6.2 - - - org.apache.axis2 - axis2-transport-local - 1.6.2 - - - org.apache.xmlbeans - xmlbeans - 2.4.0 - - - org.apache.geronimo.javamail - geronimo-javamail_1.4_mail - - - - - jboss7up - - false - - - - - org.apache.maven.plugins - maven-war-plugin - - - - WEB-INF/lib/hibernate*.jar, - WEB-INF/lib/cglib*.jar, - WEB-INF/lib/log4j*.jar, - WEB-INF/lib/stax*.jar, - WEB-INF/lib/commons-log*.jar, - WEB-INF/classes/commons*, - WEB-INF/classes/log* - - - - JPA/Hibernate-JBossAS7Up - - - JAX-WS/CXF-JBossAS7Up - - - - - - - - - - juddi-core - org.apache.juddi - ${project.version} - - - junit - junit - - - org.hibernate - hibernate-core - - - org.hibernate - hibernate-entitymanager - - - org.hibernate - hibernate-jpa - - - - - juddi-rest-cxf - org.apache.juddi - ${project.version} - - - org.apache.cxf - cxf-rt-rs-extension-providers - - - cglib - cglib-nodep - - - org.hibernate - hibernate-core - - - org.hibernate - hibernate-entitymanager - - - org.hibernate - hibernate-jpa - - - - - - + diff --git a/juddiv3-war/.gitignore b/juddiv3-war/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/juddiv3-war/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/juddiv3-war/pom.xml b/juddiv3-war/pom.xml index a0a87bff7..45a0e36c4 100644 --- a/juddiv3-war/pom.xml +++ b/juddiv3-war/pom.xml @@ -59,200 +59,7 @@ language governing permissions and * limitations under the License. * */ --> juddiv3 - - - hibernate-jbossws-native - - false - - - - - org.apache.maven.plugins - maven-war-plugin - - - - JPA/Hibernate-JBoss - - - JAX-WS/JBossWS-Native - - - - - - - - - juddi-core - org.apache.juddi - ${project.version} - - - javax.persistence - persistence-api - - provided - - - org.hibernate - hibernate - - provided - - - org.hibernate - hibernate-entitymanager - - provided - - - - - - hibernate-jbossws-cxf - - false - - - - - org.apache.maven.plugins - maven-war-plugin - - - - JPA/Hibernate-JBoss - - - JAX-WS/JBossWS-CXF - - - - - - - - - juddi-core - org.apache.juddi - ${project.version} - - - juddi-rest-cxf - org.apache.juddi - ${project.version} - - - javax.persistence - persistence-api - - provided - - - org.apache.cxf - cxf-rt-frontend-jaxrs - ${cxf.version} - - - org.apache.cxf - cxf-rt-rs-client - ${cxf.version} - - - org.apache.cxf - cxf-rt-rs-service-description - ${cxf.version} - - - - org.hibernate - hibernate-entitymanager - provided - - - cglib - cglib-nodep - provided - - - - - - hibernate - - false - - - - - org.apache.maven.plugins - maven-war-plugin - - - - JPA/Hibernate - - - JAX-WS/CXF - - - - - - - - - juddi-core - org.apache.juddi - ${project.version} - - - juddi-rest-cxf - org.apache.juddi - ${project.version} - - - - org.apache.cxf - cxf-rt-frontend-jaxws - ${cxf.version} - - - org.apache.cxf - cxf-rt-frontend-jaxrs - ${cxf.version} - - - org.apache.cxf - cxf-rt-transports-http - ${cxf.version} - - - cglib - cglib - - - - - org.springframework - spring-context - ${springframework.version} - - - org.springframework - spring-web - ${springframework.version} - - - org.apache.geronimo.javamail - geronimo-javamail_1.4_mail - - - + @@ -356,184 +163,6 @@ language governing permissions and * limitations under the License. * */ --> - - - axis2 - - false - - - - - org.apache.maven.plugins - maven-war-plugin - - - - JPA/OpenJPA - - - JAX-WS/Axis2 - - - - - - org.apache.maven.plugins - maven-antrun-plugin - 1.6 - - - default-cli - - - - - - - - - - compile - - run - - - - - - - - - - juddi-core-openjpa - org.apache.juddi - ${project.version} - - - junit - junit - - - - - - org.apache.axis2 - axis2 - - - org.apache.axis2 - axis2-jaxws - - - - org.apache.axis2 - axis2-transport-http - - - - org.apache.axis2 - axis2-transport-local - - - - org.apache.xmlbeans - xmlbeans - - - - org.apache.geronimo.javamail - geronimo-javamail_1.4_mail - - - - - jboss7up - - false - - - - - org.apache.maven.plugins - maven-war-plugin - - - WEB-INF/lib/hibernate*.jar, - WEB-INF/lib/cglib*.jar, - WEB-INF/lib/log4j*.jar, - WEB-INF/lib/stax*.jar, - WEB-INF/lib/commons-log*.jar, - WEB-INF/classes/commons*, - WEB-INF/classes/log* - - - - JPA/Hibernate-JBossAS7Up - - - JAX-WS/CXF-JBossAS7Up - - - - - - - - - - juddi-core - org.apache.juddi - ${project.version} - - - junit - junit - - - org.hibernate - hibernate-core - - - org.hibernate - hibernate-entitymanager - - - org.hibernate - hibernate-jpa - - - - - juddi-rest-cxf - org.apache.juddi - ${project.version} - - - org.apache.cxf - cxf-rt-rs-extension-providers - - - cglib - cglib-nodep - - - org.hibernate - hibernate-core - - - org.hibernate - hibernate-entitymanager - - - org.hibernate - hibernate-jpa - - - - - - + diff --git a/pom.xml b/pom.xml index abe27285b..109dd5589 100644 --- a/pom.xml +++ b/pom.xml @@ -568,7 +568,6 @@ under the License. juddi-client juddi-client-cli uddi-migration-tool - juddi-core juddi-rest-cxf juddi-core-openjpa juddiv3-war @@ -772,19 +771,7 @@ under the License. - - org.hibernate - hibernate-core - 5.4.18.Final - - - - org.hibernate - hibernate-entitymanager - 5.4.18.Final - - - + org.apache.axis2 axis2 @@ -875,14 +862,14 @@ under the License. src/site/site.xml - + + force the juddi docs module to build org.apache.juddi.juddi-docs juddi-docs @@ -915,7 +902,7 @@ under the License. - + --> diff --git a/uddi-client-dist/.gitignore b/uddi-client-dist/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/uddi-client-dist/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/uddi-migration-tool/.gitignore b/uddi-migration-tool/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/uddi-migration-tool/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/uddi-tck-base/.gitignore b/uddi-tck-base/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/uddi-tck-base/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/uddi-tck-runner/.gitignore b/uddi-tck-runner/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/uddi-tck-runner/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/uddi-tck/.gitignore b/uddi-tck/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/uddi-tck/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/* diff --git a/uddi-ws/.gitignore b/uddi-ws/.gitignore deleted file mode 100644 index c1a69fdf9..000000000 --- a/uddi-ws/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -target -**/target/* -**/derby.log -**/.project -**/.classpath -**/.settings/*