You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@juddi.apache.org by al...@apache.org on 2022/09/25 02:15:01 UTC

[juddi] branch bug/JUDDI-1024 created (now c091e365e)

This is an automated email from the ASF dual-hosted git repository.

alexoree pushed a change to branch bug/JUDDI-1024
in repository https://gitbox.apache.org/repos/asf/juddi.git


      at c091e365e JUDDI-1024 a possible solution, by removing hibernate support

This branch includes the following new commits:

     new c091e365e JUDDI-1024 a possible solution, by removing hibernate support

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@juddi.apache.org
For additional commands, e-mail: commits-help@juddi.apache.org


[juddi] 01/01: JUDDI-1024 a possible solution, by removing hibernate support

Posted by al...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

alexoree pushed a commit to branch bug/JUDDI-1024
in repository https://gitbox.apache.org/repos/asf/juddi.git

commit c091e365ed247db91478ebeabf40bc1f3e0f03eb
Author: Alex O'Ree <al...@apache.org>
AuthorDate: Sat Sep 24 22:14:55 2022 -0400

    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 -
 .../src/main/java/org/apache/juddi/ClassUtil.java  |    0
 .../src/main/java/org/apache/juddi/Registry.java   |    0
 .../juddi/api/impl/AuthenticatedService.java       |  506 +-
 .../org/apache/juddi/api/impl/InquiryHelper.java   | 1300 ++---
 .../org/apache/juddi/api/impl/JUDDIApiImpl.java    | 3366 ++++++-------
 .../apache/juddi/api/impl/PublicationHelper.java   |  124 +-
 .../api/impl/ServiceCounterLifecycleResource.java  |    0
 .../juddi/api/impl/UDDICustodyTransferImpl.java    |  942 ++--
 .../org/apache/juddi/api/impl/UDDIInquiryImpl.java | 1260 ++---
 .../apache/juddi/api/impl/UDDIPublicationImpl.java | 3206 ++++++------
 .../apache/juddi/api/impl/UDDIReplicationImpl.java | 2752 +++++------
 .../apache/juddi/api/impl/UDDISecurityImpl.java    |  350 +-
 .../apache/juddi/api/impl/UDDIServiceCounter.java  |    0
 .../juddi/api/impl/UDDIServiceCounterMBean.java    |    0
 .../juddi/api/impl/UDDISubscriptionImpl.java       | 2092 ++++----
 .../api/impl/UDDISubscriptionListenerImpl.java     |  230 +-
 .../juddi/api/impl/UDDIValueSetCachingImpl.java    |  194 +-
 .../juddi/api/impl/UDDIValueSetValidationImpl.java |  736 +--
 .../apache/juddi/api/impl/UDDIv2InquiryImpl.java   |    0
 .../apache/juddi/api/impl/UDDIv2PublishImpl.java   |    0
 .../org/apache/juddi/api/impl/XRegisterHelper.java |  354 +-
 .../org/apache/juddi/api/impl/package-info.java    |    0
 .../juddi/api/util/CustodyTransferQuery.java       |    0
 .../org/apache/juddi/api/util/InquiryQuery.java    |    0
 .../java/org/apache/juddi/api/util/JUDDIQuery.java |    0
 .../apache/juddi/api/util/PublicationQuery.java    |    0
 .../org/apache/juddi/api/util/QueryStatus.java     |    0
 .../apache/juddi/api/util/ReplicationQuery.java    |    0
 .../org/apache/juddi/api/util/SecurityQuery.java   |    0
 .../juddi/api/util/SubscriptionListenerQuery.java  |    0
 .../apache/juddi/api/util/SubscriptionQuery.java   |    0
 .../java/org/apache/juddi/api/util/UDDIQuery.java  |    0
 .../juddi/api/util/ValueSetCachingQuery.java       |    0
 .../juddi/api/util/ValueSetValidationQuery.java    |    0
 .../org/apache/juddi/api/util/package-info.java    |    0
 .../java/org/apache/juddi/config/AppConfig.java    |    0
 .../java/org/apache/juddi/config/Constants.java    |   60 +-
 .../main/java/org/apache/juddi/config/Install.java | 1676 +++----
 .../apache/juddi/config/PersistenceManager.java    |    0
 .../java/org/apache/juddi/config/Property.java     |    0
 .../apache/juddi/config/PublisherFileFilter.java   |    0
 .../main/java/org/apache/juddi/config/Release.java |    0
 .../org/apache/juddi/config/ResourceConfig.java    |  104 +-
 .../java/org/apache/juddi/config/package-info.java |    0
 .../org/apache/juddi/cryptor/CryptorFactory.java   |  212 +-
 .../org/apache/juddi/cryptor/package-info.java     |    0
 .../apache/juddi/keygen/DefaultKeyGenerator.java   |  164 +-
 .../java/org/apache/juddi/keygen/KeyGenerator.java |   68 +-
 .../apache/juddi/keygen/KeyGeneratorFactory.java   |  212 +-
 .../java/org/apache/juddi/keygen/package-info.java |    0
 .../apache/juddi/mapping/MappingApiToModel.java    | 3384 ++++++-------
 .../apache/juddi/mapping/MappingModelToApi.java    | 2728 +++++------
 .../org/apache/juddi/mapping/package-info.java     |    0
 .../main/java/org/apache/juddi/model/Address.java  |    1 +
 .../java/org/apache/juddi/model/AddressLine.java   |    0
 .../java/org/apache/juddi/model/AuthToken.java     |    0
 .../org/apache/juddi/model/BindingCategoryBag.java |    0
 .../java/org/apache/juddi/model/BindingDescr.java  |    0
 .../org/apache/juddi/model/BindingTemplate.java    |    0
 .../apache/juddi/model/BusinessCategoryBag.java    |    0
 .../java/org/apache/juddi/model/BusinessDescr.java |    0
 .../org/apache/juddi/model/BusinessEntity.java     |    0
 .../org/apache/juddi/model/BusinessIdentifier.java |    0
 .../java/org/apache/juddi/model/BusinessName.java  |    0
 .../org/apache/juddi/model/BusinessService.java    |    0
 .../apache/juddi/model/CanonicalizationMethod.java |    0
 .../java/org/apache/juddi/model/CategoryBag.java   |    0
 .../java/org/apache/juddi/model/ChangeRecord.java  |    0
 .../main/java/org/apache/juddi/model/Clerk.java    |    0
 .../apache/juddi/model/ClientSubscriptionInfo.java |    0
 .../main/java/org/apache/juddi/model/Contact.java  |    0
 .../java/org/apache/juddi/model/ContactDescr.java  |    0
 .../org/apache/juddi/model/ControlMessage.java     |    0
 .../java/org/apache/juddi/model/DiscoveryUrl.java  |    0
 .../src/main/java/org/apache/juddi/model/Edge.java |    0
 .../apache/juddi/model/EdgeReceiverAlternate.java  |    0
 .../main/java/org/apache/juddi/model/Email.java    |    0
 .../apache/juddi/model/InstanceDetailsDescr.java   |    0
 .../juddi/model/InstanceDetailsDocDescr.java       |    0
 .../java/org/apache/juddi/model/KeyDataValue.java  |    0
 .../main/java/org/apache/juddi/model/KeyInfo.java  |    0
 .../org/apache/juddi/model/KeyedReference.java     |    0
 .../apache/juddi/model/KeyedReferenceGroup.java    |    0
 .../src/main/java/org/apache/juddi/model/Node.java |    0
 .../java/org/apache/juddi/model/ObjectType.java    |    0
 .../org/apache/juddi/model/ObjectTypeContent.java  |    0
 .../main/java/org/apache/juddi/model/Operator.java |    0
 .../org/apache/juddi/model/OperatorStatusType.java |    0
 .../java/org/apache/juddi/model/OverviewDoc.java   |    0
 .../org/apache/juddi/model/OverviewDocDescr.java   |    0
 .../java/org/apache/juddi/model/PersonName.java    |    0
 .../main/java/org/apache/juddi/model/Phone.java    |    0
 .../java/org/apache/juddi/model/Publisher.java     |    0
 .../org/apache/juddi/model/PublisherAssertion.java |    0
 .../apache/juddi/model/PublisherAssertionId.java   |    0
 .../java/org/apache/juddi/model/Reference.java     |    0
 .../juddi/model/ReplicationConfiguration.java      |    0
 .../juddi/model/ReplicationConfigurationNode.java  |    0
 .../org/apache/juddi/model/ServiceCategoryBag.java |    0
 .../java/org/apache/juddi/model/ServiceDescr.java  |    0
 .../java/org/apache/juddi/model/ServiceName.java   |    0
 .../org/apache/juddi/model/ServiceProjection.java  |  154 +-
 .../apache/juddi/model/ServiceProjectionId.java    |  146 +-
 .../java/org/apache/juddi/model/Signature.java     |    0
 .../org/apache/juddi/model/SignatureMethod.java    |    0
 .../org/apache/juddi/model/SignatureTransform.java |    0
 .../juddi/model/SignatureTransformDataValue.java   |    0
 .../org/apache/juddi/model/SignatureValue.java     |    0
 .../java/org/apache/juddi/model/SignedInfo.java    |    0
 .../java/org/apache/juddi/model/Subscription.java  |    0
 .../apache/juddi/model/SubscriptionChunkToken.java |  208 +-
 .../org/apache/juddi/model/SubscriptionMatch.java  |  154 +-
 .../main/java/org/apache/juddi/model/TempKey.java  |    6 +-
 .../java/org/apache/juddi/model/TempKeyPK.java     |  158 +-
 .../main/java/org/apache/juddi/model/Tmodel.java   |    0
 .../org/apache/juddi/model/TmodelCategoryBag.java  |    0
 .../java/org/apache/juddi/model/TmodelDescr.java   |    0
 .../org/apache/juddi/model/TmodelIdentifier.java   |    0
 .../org/apache/juddi/model/TmodelInstanceInfo.java |    0
 .../juddi/model/TmodelInstanceInfoDescr.java       |    0
 .../java/org/apache/juddi/model/TransferToken.java |    4 +-
 .../org/apache/juddi/model/TransferTokenKey.java   |    0
 .../java/org/apache/juddi/model/UddiEntity.java    |  258 +-
 .../apache/juddi/model/UddiEntityPublisher.java    |  442 +-
 .../org/apache/juddi/model/ValueSetValues.java     |    0
 .../java/org/apache/juddi/model/package-info.java  |    0
 .../apache/juddi/query/BindingTemplateQuery.java   |   92 +-
 .../apache/juddi/query/BusinessEntityQuery.java    |   86 +-
 .../apache/juddi/query/BusinessServiceQuery.java   |   90 +-
 .../DeletePublisherAssertionByBusinessQuery.java   |  138 +-
 .../java/org/apache/juddi/query/EntityQuery.java   |  372 +-
 .../juddi/query/FetchBindingTemplatesQuery.java    |  250 +-
 .../juddi/query/FetchBusinessEntitiesQuery.java    |  300 +-
 .../juddi/query/FetchBusinessServicesQuery.java    |  296 +-
 .../org/apache/juddi/query/FetchTModelsQuery.java  |  292 +-
 .../query/FindBindingByCategoryGroupQuery.java     |  138 +-
 .../juddi/query/FindBindingByCategoryQuery.java    |  126 +-
 .../juddi/query/FindBindingByTModelKeyQuery.java   |  320 +-
 .../query/FindBusinessByCategoryGroupQuery.java    |  126 +-
 .../juddi/query/FindBusinessByCategoryQuery.java   |  114 +-
 .../query/FindBusinessByCombinedCategoryQuery.java |    0
 .../query/FindBusinessByDiscoveryURLQuery.java     |  240 +-
 .../juddi/query/FindBusinessByIdentifierQuery.java |  114 +-
 .../juddi/query/FindBusinessByNameQuery.java       |  130 +-
 .../juddi/query/FindBusinessByPublisherQuery.java  |  102 +-
 .../juddi/query/FindBusinessByTModelKeyQuery.java  |  328 +-
 .../query/FindEntityByCategoryGroupQuery.java      |  650 +--
 .../juddi/query/FindEntityByCategoryQuery.java     |  616 +--
 .../query/FindEntityByCombinedCategoryQuery.java   |    0
 .../juddi/query/FindEntityByIdentifierQuery.java   |  576 +--
 .../apache/juddi/query/FindEntityByNamesQuery.java |  356 +-
 .../juddi/query/FindEntityByPublisherQuery.java    |  216 +-
 .../FindPublisherAssertionByBusinessQuery.java     |  204 +-
 .../query/FindServiceByCategoryGroupQuery.java     |  136 +-
 .../juddi/query/FindServiceByCategoryQuery.java    |  126 +-
 .../query/FindServiceByCombinedCategoryQuery.java  |    0
 .../apache/juddi/query/FindServiceByNameQuery.java |  142 +-
 .../juddi/query/FindServiceByTModelKeyQuery.java   |  334 +-
 .../query/FindSubscriptionByPublisherQuery.java    |   80 +-
 .../query/FindTModelByCategoryGroupQuery.java      |  130 +-
 .../juddi/query/FindTModelByCategoryQuery.java     |  118 +-
 .../juddi/query/FindTModelByIdentifierQuery.java   |  116 +-
 .../apache/juddi/query/FindTModelByNameQuery.java  |  210 +-
 .../juddi/query/FindTModelByPublisherQuery.java    |  102 +-
 .../juddi/query/PublisherAssertionQuery.java       |   98 +-
 .../org/apache/juddi/query/SubscriptionQuery.java  |   80 +-
 .../java/org/apache/juddi/query/TModelQuery.java   |   84 +-
 .../java/org/apache/juddi/query/package-info.java  |    0
 .../org/apache/juddi/query/util/DynamicQuery.java  |  506 +-
 .../apache/juddi/query/util/FindQualifiers.java    |  740 +--
 .../query/util/KeyedRefGroupTModelComparator.java  |   96 +-
 .../juddi/query/util/KeyedRefTModelComparator.java |   96 +-
 .../juddi/replication/ReplicationNotifier.java     |    0
 .../juddi/subscription/NotificationList.java       |    0
 .../juddi/subscription/SubscriptionNotifier.java   |    0
 .../apache/juddi/subscription/TypeConvertor.java   |    0
 .../juddi/subscription/notify/HTTPNotifier.java    |    0
 .../apache/juddi/subscription/notify/Notifier.java |    0
 .../juddi/subscription/notify/NotifierFactory.java |    0
 .../juddi/subscription/notify/SMTPNotifier.java    |    0
 .../notify/TemporaryMailContainer.java             |    0
 .../notify/USERFRIENDLYSMTPNotifier.java           |    0
 .../juddi/subscription/notify/package-info.java    |    0
 .../apache/juddi/subscription/package-info.java    |    0
 .../org/apache/juddi/v3/auth/Authenticator.java    |  122 +-
 .../apache/juddi/v3/auth/AuthenticatorFactory.java |  198 +-
 .../juddi/v3/auth/CryptedXMLDocAuthenticator.java  |  402 +-
 .../juddi/v3/auth/HTTPContainerAuthenticator.java  |    0
 .../juddi/v3/auth/HTTPHeaderAuthenticator.java     |    0
 .../apache/juddi/v3/auth/JUDDIAuthenticator.java   |  254 +-
 .../java/org/apache/juddi/v3/auth/JuddiUsers.java  |    0
 .../juddi/v3/auth/LdapExpandedAuthenticator.java   |    0
 .../juddi/v3/auth/LdapSimpleAuthenticator.java     |    0
 .../juddi/v3/auth/MD5XMLDocAuthenticator.java      |  348 +-
 .../main/java/org/apache/juddi/v3/auth/User.java   |    0
 .../apache/juddi/v3/auth/XMLDocAuthenticator.java  |  464 +-
 .../org/apache/juddi/v3/auth/package-info.java     |    0
 .../juddi/v3/error/AssertionNotFoundException.java |   72 +-
 .../juddi/v3/error/AuthTokenExpiredException.java  |   72 +-
 .../juddi/v3/error/AuthTokenRequiredException.java |   72 +-
 .../juddi/v3/error/AuthenticationException.java    |   72 +-
 .../org/apache/juddi/v3/error/ErrorMessage.java    |  122 +-
 .../apache/juddi/v3/error/FatalErrorException.java |   72 +-
 .../v3/error/InvalidCombinationException.java      |   74 +-
 .../juddi/v3/error/InvalidKeyPassedException.java  |   74 +-
 .../juddi/v3/error/InvalidProjectionException.java |   74 +-
 .../juddi/v3/error/InvalidTimeException.java       |   74 +-
 .../juddi/v3/error/InvalidValueException.java      |   80 +-
 .../juddi/v3/error/KeyUnavailableException.java    |   72 +-
 .../v3/error/MaxEntitiesExceededException.java     |   74 +-
 .../apache/juddi/v3/error/RegistryException.java   |   72 +-
 .../v3/error/TokenAlreadyExistsException.java      |   74 +-
 .../v3/error/TransferNotAllowedException.java      |   74 +-
 .../org/apache/juddi/v3/error/UDDIErrorHelper.java |  422 +-
 .../juddi/v3/error/UnknownUserException.java       |   72 +-
 .../juddi/v3/error/UnsupportedException.java       |   72 +-
 .../juddi/v3/error/UserMismatchException.java      |   64 +-
 .../juddi/v3/error/ValueNotAllowedException.java   |   74 +-
 .../org/apache/juddi/v3/error/package-info.java    |    0
 .../org/apache/juddi/validation/ValidateClerk.java |  198 +-
 .../validation/ValidateClientSubscriptionInfo.java |  280 +-
 .../juddi/validation/ValidateCustodyTransfer.java  |    0
 .../apache/juddi/validation/ValidateInquiry.java   | 1604 +++---
 .../org/apache/juddi/validation/ValidateNode.java  |  246 +-
 .../apache/juddi/validation/ValidatePublish.java   | 5102 ++++++++++----------
 .../apache/juddi/validation/ValidatePublisher.java |  288 +-
 .../juddi/validation/ValidateReplication.java      |    0
 .../apache/juddi/validation/ValidateSecurity.java  |    0
 .../juddi/validation/ValidateSubscription.java     |    0
 .../validation/ValidateSubscriptionListener.java   |   80 +-
 .../apache/juddi/validation/ValidateUDDIApi.java   |  172 +-
 .../apache/juddi/validation/ValidateUDDIKey.java   |  320 +-
 .../juddi/validation/ValidateUDDIv2Inquiry.java    |    0
 .../juddi/validation/ValidateValueSetCaching.java  |    0
 .../validation/ValidateValueSetValidation.java     |    0
 .../validation/ValidateValuesFromWebService.java   |    0
 .../juddi/validation/ValidationConstants.java      |    0
 .../org/apache/juddi/validation/package-info.java  |    0
 .../validation/vsv/AbstractSimpleValidator.java    |    0
 .../vsv/Uddiuddiorgcategorizationderivedfrom.java  |    0
 .../Uddiuddiorgcategorizationentitykeyvalues.java  |    0
 .../vsv/Uddiuddiorgcategorizationnodes.java        |    0
 .../Uddiuddiorgcategorizationowningbusiness.java   |    0
 .../vsv/Uddiuddiorgcategorizationtypes.java        |    0
 .../vsv/Uddiuddiorgcategorizationvalidatedby.java  |    0
 .../vsv/Uddiuddiorgidentifierisreplacedby.java     |    0
 .../validation/vsv/Uddiuddiorgrelationships.java   |    0
 .../vsv/Uuid25b22e3e3dfa3024b02a3438b9050b59.java  |    0
 .../vsv/Uuid327a56f032994461bc235cd513e95c55.java  |    0
 .../vsv/Uuid4064c0646d144f3589539652106476a9.java  |    0
 .../vsv/Uuid5678dd4ff95d35f99ea6f79a7dd64656.java  |    0
 .../vsv/Uuid807a2c6aee22470dadc7e0424a337c03.java  |    0
 .../vsv/Uuid916b87bf075639198eae97dfa325e5a4.java  |    0
 .../vsv/Uuidc1acf26d967244049d7039b756e62ab4.java  |    0
 .../vsv/Uuide59ae32077a511d5b8980004ac49cc1e.java  |    0
 .../juddi/validation/vsv/ValueSetValidator.java    |    0
 .../juddi_install_data/UDDI_Publisher.xml          |   44 +-
 .../resources/juddi_install_data/UDDI_tModels.xml  | 4850 +++++++++----------
 .../juddi_install_data/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 +--
 .../apache/juddi/api/impl/API_020_TmodelTest.java  |  250 +-
 .../juddi/api/impl/API_030_BusinessEntityTest.java |  320 +-
 .../api/impl/API_040_BusinessServiceLoadTest.java  |  344 +-
 .../api/impl/API_040_BusinessServiceTest.java      |  362 +-
 .../api/impl/API_050_BindingTemplateTest.java      |  618 +--
 .../api/impl/API_051_BindingTemplateWSDLTest.java  |  288 +-
 .../api/impl/API_060_PublisherAssertionTest.java   | 1014 ++--
 .../juddi/api/impl/API_070_FindEntityTest.java     |  628 +--
 .../juddi/api/impl/API_080_SubscriptionTest.java   |  322 +-
 ...PI_090_SubscriptionListenerIntegrationTest.java |    0
 .../apache/juddi/api/impl/API_099_LoadTest.java    |    0
 .../impl/API_100_ClientSubscriptionInfoTest.java   |  406 +-
 .../juddi/api/impl/API_110_FindBusinessTest.java   |    0
 ...API_120_CombineCategoryBagsFindServiceTest.java |    0
 ...PI_130_CombineCategoryBagsFindBusinessTest.java |    0
 .../api/impl/API_140_NegativePublicationTest.java  | 4888 +++++++++----------
 .../apache/juddi/api/impl/API_141_JIRATest.java    | 2838 +++++------
 .../api/impl/API_150_ValueSetValidationTest.java   |    0
 .../juddi/api/impl/API_160_ReplicationTest.java    |    0
 .../api/impl/API_170_CustodyTransferTest.java      |    0
 .../java/org/apache/juddi/api/impl/TokenTest.java  |    0
 .../juddi/api/impl/UDDIPublicationImplExt.java     |    0
 .../apache/juddi/api/impl/UDDISecurityImplExt.java |    0
 .../java/org/apache/juddi/api/impl/package.html    |    0
 .../apache/juddi/api/runtime/CLIServerTest.java    |    0
 .../apache/juddi/api/runtime/JuddiTestimpl.java    |    0
 .../apache/juddi/api/runtime/ReplicantImpl.java    |    0
 .../org/apache/juddi/auth/AuthenticatorTest.java   |    0
 .../apache/juddi/auth/MockHttpServletRequest.java  |    0
 .../org/apache/juddi/auth/MockMessageContext.java  |    0
 .../apache/juddi/auth/MockWebServiceContext.java   |    0
 .../juddi/config/ApplicationConfigurationTest.java |    0
 .../java/org/apache/juddi/config/InstallTest.java  |    0
 .../apache/juddi/config/ReleaseVersionTest.java    |    0
 .../org/apache/juddi/keygen/KeyGeneratorTest.java  |    0
 .../juddi/replication/ReplicationNotifierTest.java |    0
 .../subscription/SubscriptionNotifierTest.java     |    0
 .../juddi/subscription/notify/NotifierTest.java    |    0
 .../test/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 +-
 .../src/test/resources/juddiv3-enc-default.xml     |   20 +-
 juddi-core-openjpa/src/test/resources/juddiv3.xml  |   25 +-
 .../test/resources/juddiv3DisabledTModelKeybag.xml |   18 +-
 juddi-core/.gitignore                              |    6 -
 juddi-core/pom.xml                                 |  189 -
 juddi-core/src/test/resources/META-INF/orm.xml     |  241 -
 .../src/test/resources/META-INF/persistence.xml    |  118 -
 juddi-core/src/test/resources/META-INF/uddi.xml    |  114 -
 .../src/test/resources/juddi-users-encrypted.xml   |   22 -
 .../src/test/resources/juddi-users-hashed.xml      |   23 -
 juddi-core/src/test/resources/juddi-users.xml      |   22 -
 juddi-core/src/test/resources/juddiv3-enc-3des.xml |  222 -
 .../src/test/resources/juddiv3-enc-aes128.xml      |  218 -
 .../src/test/resources/juddiv3-enc-aes256.xml      |  225 -
 .../src/test/resources/juddiv3-enc-default.xml     |  222 -
 juddi-core/src/test/resources/juddiv3.xml          |  225 -
 .../test/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
 juddi-core/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 +-
 juddi-examples/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 -
 juddi-examples/simple-publish-clerk/.gitignore     |    6 -
 juddi-examples/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(-)

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 @@
 		</dependency>
 		<dependency>
 			<groupId>org.apache.juddi</groupId>
-			<artifactId>juddi-core</artifactId>
+			<artifactId>juddi-core-openjpa</artifactId>
 			<version>${project.parent.version}</version>
 			<scope>compile</scope>
 		</dependency>
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.
     </description>
     <build>
-        <sourceDirectory>../juddi-core/src/main/java</sourceDirectory>
-        <testSourceDirectory>../juddi-core/src/test/java</testSourceDirectory>
-        <resources>
-            <resource>
-                <directory>../juddi-core/src/main/resources</directory>
-            </resource>
-        </resources>
+        
         <plugins>
             <plugin>
                 <groupId>org.apache.felix</groupId>
@@ -62,7 +56,7 @@
             <plugin>
                 <groupId>org.apache.openjpa</groupId>
                 <artifactId>openjpa-maven-plugin</artifactId>
-                <version>3.1.0</version>
+                <version>3.2.2</version>
                 <configuration>
                     <includes>**/org/apache/juddi/model/*.class</includes>
                     <addDefaultConstructor>true</addDefaultConstructor>
@@ -82,34 +76,12 @@
                     <dependency>
                         <groupId>org.apache.openjpa</groupId>
                         <artifactId>openjpa</artifactId>
-                        <version>3.1.0</version>
+                        <version>3.2.2</version>
                     </dependency>
                 </dependencies>
             </plugin>
 
-            <plugin>
-                <artifactId>maven-clean-plugin</artifactId>
-                <version>2.6.1</version>
-                <configuration>
-                    <filesets>
-                        <fileset>
-                            <directory>src/main/java</directory>
-                            <includes>
-                                <include>**/*</include>
-                            </includes>
-                            <followSymlinks>false</followSymlinks>
-                        </fileset>
-                        <fileset>
-                            <directory>src/test/java</directory>
-                            <includes>
-                                <include>**/*</include>
-                            </includes>
-                            <followSymlinks>false</followSymlinks>
-                        </fileset>
-                    </filesets>
-                </configuration>
-            </plugin>
-
+           
         </plugins>
     </build>
     <dependencies>
@@ -140,7 +112,7 @@
         <dependency>
             <groupId>org.apache.openjpa</groupId>
             <artifactId>openjpa</artifactId>
-            <version>2.3.0</version>
+            <version>3.2.2</version>
         </dependency>
         <dependency>
             <groupId>org.apache.geronimo.specs</groupId>
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 <a href="mailto:jfaath@apache.org">Jeff Faath</a>
- *
- * @author <a href="mailto:alexoree@apache.org">Alex O'Ree</a> - 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 <a href="mailto:jfaath@apache.org">Jeff Faath</a>
+ *
+ * @author <a href="mailto:alexoree@apache.org">Alex O'Ree</a> - 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 <a href="mailto:jfaath@apache.org">Jeff Faath</a>
- */
-public class InquiryHelper {
-
-	private static Log logger = LogFactory.getLog(InquiryHelper.class);
-	
-	public static List<Object> findBinding(FindBinding body, FindQualifiers findQualifiers, EntityManager em) throws DispositionReportFaultMessage {
-
-		List<Object> keysFound = new LinkedList<Object>();
-                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<Integer> 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<Object> findBusiness(FindBusiness body, FindQualifiers findQualifiers, EntityManager em) throws DispositionReportFaultMessage {
-
-		List<Object> 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<Object> relatedBusinessKeys = new ArrayList<Object>(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<Integer> 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<Object> keysIn = new ArrayList<Object>();
-                                List<org.apache.juddi.model.BusinessService> 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<org.apache.juddi.model.BusinessService>) 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<Object> 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<Integer> 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<Object> findTModel(FindTModel body, FindQualifiers findQualifiers, EntityManager em) throws DispositionReportFaultMessage {
-		List<Object> 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<Integer> 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<org.apache.juddi.model.PublisherAssertion> 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<Object> 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<Object> findBindingsByServiceKey(EntityManager em, String serviceKey, List<Object> 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 <a href="mailto:jfaath@apache.org">Jeff Faath</a>
+ */
+public class InquiryHelper {
+
+	private static Log logger = LogFactory.getLog(InquiryHelper.class);
+	
+	public static List<Object> findBinding(FindBinding body, FindQualifiers findQualifiers, EntityManager em) throws DispositionReportFaultMessage {
+
+		List<Object> keysFound = new LinkedList<Object>();
+                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<Integer> 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<Object> findBusiness(FindBusiness body, FindQualifiers findQualifiers, EntityManager em) throws DispositionReportFaultMessage {
+
+		List<Object> 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<Object> relatedBusinessKeys = new ArrayList<Object>(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<Integer> 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<Object> keysIn = new ArrayList<Object>();
+                                List<org.apache.juddi.model.BusinessService> 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<org.apache.juddi.model.BusinessService>) 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<Object> 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<Integer> 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<Object> findTModel(FindTModel body, FindQualifiers findQualifiers, EntityManager em) throws DispositionReportFaultMessage {
+		List<Object> 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<Integer> 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<org.apache.juddi.model.PublisherAssertion> 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<Object> 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<Object> findBindingsByServiceKey(EntityManager em, String serviceKey, List<Object> 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 <a href="mailto:jfaath@apache.org">Jeff Faath</a>
- * @author <a href="mailto:kstam@apache.org">Kurt T Stam</a>
- * @author <a href="mailto:alexoree@apache.org">Alex O'Ree</a>
- */
-@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<org.apache.juddi.api_v3.Publisher> 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<String> entityKeyList = body.getPublisherId();
-                        List<Publisher> deletedPubs = new ArrayList<Publisher>();
-                        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<BusinessInfo> 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<TModelInfo> 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<String> 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<Publisher> 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.<br>
-         * 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<ChangeRecord> changes = new ArrayList<ChangeRecord>();
-                        List<String> 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<String> 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<org.apache.juddi.api_v3.ClientSubscriptionInfo> 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<org.apache.juddi.model.ClientSubscriptionInfo> 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<String> 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<org.apache.juddi.api_v3.Clerk> 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<org.apache.juddi.api_v3.Node> 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<String, org.apache.juddi.api_v3.ClientSubscriptionInfo> clientSubscriptionInfoMap
-                        = new HashMap<String, org.apache.juddi.api_v3.ClientSubscriptionInfo>();
-                //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<String> 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<org.apache.juddi.model.Node> 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<org.apache.juddi.model.Clerk> 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<ValidValues> 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<String> 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<TemporaryMailContainer> notifications = new ArrayList<TemporaryMailContainer>();
-                        List<String> 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<AdminSaveBusinessWrapper> 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<AdminSaveTModelWrapper> 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<SubscriptionWrapper> getAllClientSubscriptionInfo(String authInfo) throws DispositionReportFaultMessage, RemoteException {
-                long startTime = System.currentTimeMillis();
-
-                List<SubscriptionWrapper> r = new ArrayList<SubscriptionWrapper>();
-
-                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<org.apache.juddi.model.Subscription> 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<List<Subscription>> 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<ChangeRecord> 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<ChangeRecord> 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 <a href="mailto:jfaath@apache.org">Jeff Faath</a>
+ * @author <a href="mailto:kstam@apache.org">Kurt T Stam</a>
+ * @author <a href="mailto:alexoree@apache.org">Alex O'Ree</a>
+ */
+@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<org.apache.juddi.api_v3.Publisher> 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<String> entityKeyList = body.getPublisherId();
+                        List<Publisher> deletedPubs = new ArrayList<Publisher>();
+                        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<BusinessInfo> 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<TModelInfo> 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<String> 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<Publisher> 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.<br>
+         * 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<ChangeRecord> changes = new ArrayList<ChangeRecord>();
+                        List<String> 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<String> 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<org.apache.juddi.api_v3.ClientSubscriptionInfo> 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<org.apache.juddi.model.ClientSubscriptionInfo> 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<String> 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<org.apache.juddi.api_v3.Clerk> 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<org.apache.juddi.api_v3.Node> 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<String, org.apache.juddi.api_v3.ClientSubscriptionInfo> clientSubscriptionInfoMap
+                        = new HashMap<String, org.apache.juddi.api_v3.ClientSubscriptionInfo>();
+                //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<String> 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<org.apache.juddi.model.Node> 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<org.apache.juddi.model.Clerk> 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<ValidValues> 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<String> 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<TemporaryMailContainer> notifications = new ArrayList<TemporaryMailContainer>();
+                        List<String> 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<AdminSaveBusinessWrapper> 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<AdminSaveTModelWrapper> 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<SubscriptionWrapper> getAllClientSubscriptionInfo(String authInfo) throws DispositionReportFaultMessage, RemoteException {
+                long startTime = System.currentTimeMillis();
+
+                List<SubscriptionWrapper> r = new ArrayList<SubscriptionWrapper>();
+
+                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<org.apache.juddi.model.Subscription> 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<List<Subscription>> 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<ChangeRecord> 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<ChangeRecord> 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 <a href="mailto:jfaath@apache.org">Jeff Faath</a>
- */
-public class PublicationHelper {
-
-	public static List<AssertionStatusItem> getAssertionStatusItemList(UddiEntityPublisher publisher, CompletionStatus completionStatus, EntityManager em) throws DispositionReportFaultMessage {
-		List<org.uddi.api_v3.AssertionStatusItem> result = new ArrayList<org.uddi.api_v3.AssertionStatusItem>(0);
-
-		List<?> businessKeysFound = null;
-		businessKeysFound = FindBusinessByPublisherQuery.select(em, null, publisher, businessKeysFound);
-		
-		List<org.apache.juddi.model.PublisherAssertion> 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 <a href="mailto:jfaath@apache.org">Jeff Faath</a>
+ */
+public class PublicationHelper {
+
+	public static List<AssertionStatusItem> getAssertionStatusItemList(UddiEntityPublisher publisher, CompletionStatus completionStatus, EntityManager em) throws DispositionReportFaultMessage {
+		List<org.uddi.api_v3.AssertionStatusItem> result = new ArrayList<org.uddi.api_v3.AssertionStatusItem>(0);
+
+		List<?> businessKeysFound = null;
+		businessKeysFound = FindBusinessByPublisherQuery.select(em, null, publisher, businessKeysFound);
+		
+		List<org.apache.juddi.model.PublisherAssertion> 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<String> keyList = keyBag.getKey();
-                                Vector<DynamicQuery.Parameter> params = new Vector<DynamicQuery.Parameter>(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<org.apache.juddi.model.TransferToken> 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<String> nodeID, Holder<XMLGregorianCalendar> expirationTime,
-                Holder<byte[]> 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<String> 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<ChangeRecord> changes = new ArrayList<ChangeRecord>();
-                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<String> 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<ChangeRecord> executeTransfer(TransferEntities body, EntityManager em, String transferToPublisher, String transferToNode) throws DispositionReportFaultMessage {
-                // Once validated, the ownership transfer is as simple as switching the publisher
-                List<ChangeRecord> changes = new ArrayList<ChangeRecord>();;
-                KeyBag keyBag = body.getKeyBag();
-                List<String> 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<BusinessService> bsList = be.getBusinessServices();
-                                for (BusinessService bs : bsList) {
-                                        bs.setAuthorizedName(transferToPublisher);
-                                        bs.setNodeId(transferToNode);
-                                        bs.setModified(now);
-                                        bs.setModifiedIncludingChildren(now);
-
-                                        List<BindingTemplate> 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<String> keyList = keyBag.getKey();
+                                Vector<DynamicQuery.Parameter> params = new Vector<DynamicQuery.Parameter>(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<org.apache.juddi.model.TransferToken> 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<String> nodeID, Holder<XMLGregorianCalendar> expirationTime,
+                Holder<byte[]> 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<String> 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<ChangeRecord> changes = new ArrayList<ChangeRecord>();
+                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<String> 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<ChangeRecord> executeTransfer(TransferEntities body, EntityManager em, String transferToPublisher, String transferToNode) throws DispositionReportFaultMessage {
+                // Once validated, the ownership transfer is as simple as switching the publisher
+                List<ChangeRecord> changes = new ArrayList<ChangeRecord>();;
+                KeyBag keyBag = body.getKeyBag();
+                List<String> 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<BusinessService> bsList = be.getBusinessServices();
+                                for (BusinessService bs : bsList) {
+                                        bs.setAuthorizedName(transferToPublisher);
+                                        bs.setNodeId(transferToNode);
+                                        bs.setModified(now);
+                                        bs.setModifiedIncludingChildren(now);
+
+                                        List<BindingTemplate> 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 <a href="mailto:jfaath@apache.org">Jeff Faath</a>
- */
-@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<String> 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<String> 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<String> 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<String> 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<String> 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 <a href="mailto:jfaath@apache.org">Jeff Faath</a>
+ */
+@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<String> 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<String> 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<String> 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<String> 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<String> 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 <a href="mailto:jfaath@apache.org">Jeff Faath</a> (and many others)
- * @author <a href="mailto:alexoree@apache.org">Alex O'Ree</a> 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<org.uddi.api_v3.PublisherAssertion> apiPubAssertionList = body.getPublisherAssertion();
-                        List<ChangeRecord> changes = new ArrayList<ChangeRecord>();
-                        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<String> entityKeyList = body.getBindingKey();
-                        List<ChangeRecord> changes = new ArrayList<ChangeRecord>();
-                        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<String> entityKeyList = body.getBusinessKey();
-                        List<ChangeRecord> changes = new ArrayList<ChangeRecord>();
-                        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<org.uddi.api_v3.PublisherAssertion> entityList = body.getPublisherAssertion();
-                        List<ChangeRecord> changes = new ArrayList<ChangeRecord>();
-                        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<String> entityKeyList = body.getServiceKey();
-                        List<ChangeRecord> changes = new ArrayList<ChangeRecord>();
-                        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<String> entityKeyList = body.getTModelKey();
-                        List<ChangeRecord> changes = new ArrayList<ChangeRecord>();
-                        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<AssertionStatusItem> 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<org.uddi.api_v3.AssertionStatusItem> 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<PublisherAssertion> 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<org.uddi.api_v3.PublisherAssertion> result = new ArrayList<org.uddi.api_v3.PublisherAssertion>(0);
-
-                        List<?> businessKeysFound = null;
-                        businessKeysFound = FindBusinessByPublisherQuery.select(em, null, publisher, businessKeysFound);
-
-                        List<org.apache.juddi.model.PublisherAssertion> 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<org.uddi.api_v3.BindingTemplate> apiBindingTemplateList = body.getBindingTemplate();
-                        List<org.apache.juddi.model.ChangeRecord> changes = new ArrayList<ChangeRecord>();
-
-                        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<org.uddi.api_v3.BusinessEntity> apiBusinessEntityList = body.getBusinessEntity();
-                        List<ChangeRecord> changes = new ArrayList<ChangeRecord>();
-
-                        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<org.uddi.api_v3.BusinessService> apiBusinessServiceList = body.getBusinessService();
-                        List<ChangeRecord> changes = new ArrayList<ChangeRecord>();
-                        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<org.uddi.api_v3.TModel> apiTModelList = body.getTModel();
-                        List<ChangeRecord> changes = new ArrayList<ChangeRecord>();
-                        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<List<PublisherAssertion>> publisherAssertion)
-                throws DispositionReportFaultMessage {
-                long startTime = System.currentTimeMillis();
-
-                EntityManager em = PersistenceManager.getEntityManager();
-                EntityTransaction tx = em.getTransaction();
-                List<ChangeRecord> changes = new ArrayList<ChangeRecord>();
-                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<org.apache.juddi.model.PublisherAssertion> existingAssertions = FindPublisherAssertionByBusinessQuery.select(em, businessKeysFound, null);
-
-                        logger.debug(">>>> Existing assertions " + existingAssertions.size() + ", inbound set " + publisherAssertion.value.size());
-                        List<org.apache.juddi.model.PublisherAssertion> 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<org.uddi.api_v3.PublisherAssertion> 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<org.apache.juddi.model.BusinessService> 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<org.apache.juddi.model.BindingTemplate> 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<org.apache.juddi.model.PublisherAssertion> diff(List<PublisherAssertion> value, List<org.apache.juddi.model.PublisherAssertion> existingAssertions) throws DispositionReportFaultMessage {
-                List<org.apache.juddi.model.PublisherAssertion> ret = new ArrayList<org.apache.juddi.model.PublisherAssertion>();
-                if (value == null || value.isEmpty()) {
-                        return existingAssertions;
-                }
-                if (existingAssertions == null) {
-                        return new ArrayList<org.apache.juddi.model.PublisherAssertion>();
-                }
-                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<Signature> 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 <a href="mailto:jfaath@apache.org">Jeff Faath</a> (and many others)
+ * @author <a href="mailto:alexoree@apache.org">Alex O'Ree</a> 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<org.uddi.api_v3.PublisherAssertion> apiPubAssertionList = body.getPublisherAssertion();
+                        List<ChangeRecord> changes = new ArrayList<ChangeRecord>();
+                        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<String> entityKeyList = body.getBindingKey();
+                        List<ChangeRecord> changes = new ArrayList<ChangeRecord>();
+                        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;
... 65739 lines suppressed ...


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@juddi.apache.org
For additional commands, e-mail: commits-help@juddi.apache.org